Skip to main content
This middleware rejects every request that does not carry a valid bearer token. The check runs before the cache lookup, so it also protects content that is already in the cache.
Put access checks in onClientRequest, and enable before cache execution. Origin hooks, such as onOriginRequest, run only on a cache MISS. After one authorized request fills the cache, the CDN serves the cached response to every client, with no check.
The example is for content that is the same for all authorized users, such as private files or reports. Responses that differ per user need their own cache keys, which this example does not cover.
If you only need signed, expiring URLs, use Token Authentication instead. It needs no script.

Script

When onClientRequest returns a response, the CDN sends it as it is. onClientResponse does not run, so set every header you need on the rejection response itself.

Set up

1

Create the script

Create a Middleware script, and paste the code above. See the quickstart.
2

Add the secret

Add a secret named ACCESS_TOKEN that holds the token. See Secrets.
3

Publish and link the script

Publish the script, and link it to the Pull Zone that serves the private content.
4

Enable before cache execution

In the Pull Zone, go to General > Origin, and enable Run script before cache. If you skip this step, onClientRequest does not run, and the CDN serves the content to all clients with no error.
You can also do the last two steps with the Update Pull Zone API. Set MiddlewareScriptId to the script ID, and EdgeScriptExecutionPhase to 2 for before cache execution. The default value, 0, runs the script after the cache.

Verify

Test against the Pull Zone hostname, not a local server. The CDN-Cache response header shows whether the CDN served the response from the cache.
Step 2 is the important test. A 401 on a URL that is already cached shows that the check runs before the cache.

Close other access paths

The script protects only the Pull Zone that it is linked to. Make sure clients cannot get the same content another way:
  • Do not serve the same origin or Storage Zone through a second Pull Zone that has no protection.
  • If your origin is a public server, make it accept requests only from the CDN. For example, add a secret header in onOriginRequest, and reject requests without it at the origin.
  • A Storage Zone does not serve files without its password, so a Storage-backed Pull Zone has no public origin to protect.
Last modified on October 28, 2026