| [ Web Proxy ] |
| Viewing: https://developers.cloudflare.com/pages/functions/get-started/ | [Back] [Original] |
This guide will instruct you on creating and deploying a Pages Function.
You must have a Pages project set up on your local machine or deployed on the Cloudflare dashboard. To create a Pages project, refer to Get started.
To get started with generating a Pages Function, create a /functions directory. Make sure that the /functions directory is at the root of your Pages project (and not in the static root, such as /dist).
Advanced mode
For existing applications where Pages Functions built-in file path based routing and middleware system is not desirable, use Advanced mode. Advanced mode allows you to develop your Pages Functions with a _worker.js file rather than the /functions directory.
Writing your Functions files in the /functions directory will automatically generate a Worker with custom functionality at predesignated routes.
Copy and paste the following code into a helloworld.js file that you create in your /functions folder:
export function onRequest(context) {
return new Response("Hello, world!");
}
In the above example code, the onRequest handler takes a request context object. The handler must return a Response or a Promise of a Response.
This Function will run on the /helloworld route and returns "Hello, world!". The reason this Function is available on this route is because the file is named helloworld.js. Similarly, if this file was called howdyworld.js, this function would run on /howdyworld.
Refer to Routing for more information on route customization.
Workers runtime features are configurable on Pages Functions, including compatibility with a subset of Node.js APIs and the ability to set a compatibility date or compatibility flag.
Set these configurations by passing an argument to your Wrangler command or by setting them in the dashboard. To set Pages compatibility flags in the Cloudflare dashboard:
Additionally, use other Cloudflare products such as D1 (serverless DB) and R2 from within your Pages project by configuring bindings.
After you have set up your Function, deploy your Pages project. Deploy your project by:
Caution
Direct Upload from the Cloudflare dashboard is currently not supported with Functions.
| Web Proxy Viewer | New URL | Original Page |