Add custom HTTP headers
More advanced customization of HTTP headers is available through Cloudflare Workers serverless functions ↗.
If you have not deployed a Worker before, get started with our tutorial. For the purpose of this tutorial, accomplish steps one (Sign up for a Workers account) through four (Generate a new project) before returning to this page.
Before continuing, ensure that your Cloudflare Pages project is connected to a custom domain.
Workers functions are written in JavaScript ↗. When a Worker makes a request to a Cloudflare Pages application, it will receive a response. The response a Worker receives is immutable, meaning it cannot be changed. In order to add, delete, or alter headers, clone the response and modify the headers on a new Response
instance. Return the new response to the browser with your desired header changes. An example of this is shown below:
The easiest way to start deploying your Workers function is by typing workers.new ↗ in the browser. Log in to your account to be automatically directed to the Workers & Pages dashboard. From the Workers & Pages dashboard, write your function or use one of the examples from the Workers documentation.
Select Save and Deploy when your script is ready and set a route in your domain's zone settings.
For example, here is a Workers script you can copy and paste into the Workers dashboard that sets common security headers whenever a request hits your Pages URL, such as X-XSS-Protection, X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security, Content-Security-Policy (CSP), and more.
If you would like to skip writing this file yourself, you can use our custom-headers-example
template ↗ to generate a new Workers function with wrangler, the Workers CLI tool.
To operate your Workers function alongside your Pages application, deploy it to the same custom domain as your Pages application. To do this, update the wrangler.toml
file in your project with your account and zone details:
If you do not know how to find your Account ID and Zone ID, refer to our guide.
Once you have configured your wrangler.toml
, run npx wrangler deploy
in your terminal to deploy your Worker:
After you have deployed your Worker, your desired HTTP header adjustments will take effect. While the Worker is deployed, you should continue to see the content from your Pages application as normal.