Advanced mode
Advanced mode allows you to develop your Pages Functions with a _worker.js
file rather than the /functions
directory.
In some cases, Pages Functions' built-in file path based routing and middleware system is not desirable for existing applications. You may have a Worker that is complex and difficult to splice up into Pages' file-based routing system. For these cases, Pages offers the ability to define a _worker.js
file in the output directory of your Pages project.
When using a _worker.js
file, the entire /functions
directory is ignored, including its routing and middleware characteristics. Instead, the _worker.js
file is deployed and must be written using the Module Worker syntax. If you have never used Module syntax, refer to the JavaScript modules blog post ↗ to learn more. Using Module syntax enables JavaScript frameworks to generate a Worker as part of the Pages output directory contents.
In advanced mode, your Function will assume full control of all incoming HTTP requests to your domain. Your Function is required to make or forward requests to your project's static assets. Failure to do so will result in broken or unwanted behavior. Your Function must be written in Module syntax.
After making a _worker.js
file in your output directory, add the following code snippet:
In the above code, you have configured your Function to return a response under all requests headed for /api/
. Otherwise, your Function will fallback to returning static assets.
- The
env.ASSETS.fetch()
function will allow you to return assets on a given request. env
is the object that contains your environment variables and bindings.ASSETS
is a default Function binding that allows communication between your Function and Pages' asset serving resource.fetch()
calls to Pages' asset-serving resource and serves the requested asset.
To migrate an existing Worker to your Pages project, copy your Worker code and paste it into your new _worker.js
file. Then handle static assets by adding the following code snippet to _worker.js
:
After you have set up a new Function or migrated your Worker to _worker.js
, make sure your _worker.js
file is placed in your Pages' project output directory. Deploy your project through your Git integration for advanced mode to take effect.