How to write Cloudflare Workers? Common patterns with examples - Part 3
Common Cloudflare Worker patterns with examples: modify requests and responses, redirect and block at the edge, route to back-ends and handle origin failures.
How to write Cloudflare Workers? Common patterns with examples - Part 3
Once the development environment is ready, the next question is what to write. Most worker code we have written falls into a handful of patterns: change the request before it reaches the origin, change the response before it reaches the user, answer the request at the edge, or choose where the request should go. Once you know these patterns, most real requirements are a combination of two or three of them. In the previous article, we discussed how to set up a local development environment, unit test and deploy a worker. In this article, we are going to see the common worker patterns with examples, and how to unit test a worker which calls the origin.
Cloudflare Workers series:
- What is Cloudflare Worker and why do we need it?
- How to set up a local development environment for Cloudflare Workers?
- How to write Cloudflare Workers? Common patterns with examples (this article)
- Cloudflare Workers use cases and lessons learned
TL;DR Summary
- Requests and responses are immutable in a worker; create a new
RequestorResponseto modify them. - Modify the request to add headers or rewrite the URL before it goes to the origin.
- Modify the response to add security headers or remove internal headers.
- Respond at the edge for redirects, blocked requests and simple answers, without touching the origin.
- Route requests to different back-ends, and normalize URLs to improve the cache hit ratio.
- Handle origin failures with a fallback response, and unit test the origin calls with a fake
fetch.
All the examples below are written as the handleRequest function from the previous article, so they can be unit tested in the same way. The entry file stays the same.
Before we start: immutable requests and responses
In a worker, the incoming Request and the Response returned by fetch are immutable; their headers can’t be changed directly. To modify them, we create a new object from the existing one.
// Copy a request so we can change it
const newRequest = new Request(request);
// Copy a response so we can change it
const newResponse = new Response(response.body, response);
Keep this in mind; almost every pattern below uses it.
Pattern 1: Modify the request
Add a header to every request which goes to the origin, for example, to tell the origin that the request came through the worker.
export async function handleRequest(request: Request): Promise<Response> {
const newRequest = new Request(request);
newRequest.headers.set('x-edge-worker', 'true');
return fetch(newRequest);
}
The same pattern is used to rewrite the URL, for example, to serve /blog/* from another path on the origin,
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
if (url.pathname.startsWith('/blog/')) {
url.pathname = url.pathname.replace('/blog/', '/content/blog/');
}
return fetch(new Request(url.toString(), request));
}
Pattern 2: Modify the response
Add security headers to every response, and remove the headers which disclose internal details.
const securityHeaders: { [name: string]: string } = {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin'
};
export async function handleRequest(request: Request): Promise<Response> {
const response = await fetch(request);
const newResponse = new Response(response.body, response);
Object.keys(securityHeaders).forEach(name => newResponse.headers.set(name, securityHeaders[name]));
newResponse.headers.delete('X-Powered-By');
newResponse.headers.delete('X-AspNet-Version');
return newResponse;
}
This gives every application behind the zone the same security headers, without changing any of them.
Pattern 3: Respond at the edge
Redirects from a lookup table
Page rules can redirect URL patterns, but a few hundred one-to-one redirects (for example, after a site migration) are much easier to maintain as a lookup table.
const redirects: { [path: string]: string } = {
'/old-products': '/products',
'/about-us.aspx': '/about',
'/contact.aspx': '/contact'
};
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const target = redirects[url.pathname.toLowerCase()];
if (target) {
return Response.redirect(url.origin + target, 301);
}
return fetch(request);
}
Block requests with custom rules
Block the requests which match a custom rule, before they reach the origin. For example, block the access to the admin area from outside the office network, and block a known bad user agent.
const allowedAdminIps = ['<office ip address 1>', '<office ip address 2>'];
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const clientIp = request.headers.get('CF-Connecting-IP') || '';
const userAgent = request.headers.get('User-Agent') || '';
if (url.pathname.startsWith('/admin') && allowedAdminIps.indexOf(clientIp) === -1) {
return new Response('Forbidden', { status: 403 });
}
if (userAgent.indexOf('<bad bot name>') !== -1) {
return new Response('Forbidden', { status: 403 });
}
return fetch(request);
}
Cloudflare adds the CF-Connecting-IP header with the IP address of the user to every request, so we don’t need to parse X-Forwarded-For.
Pattern 4: Route to different back-ends
Send the requests to different back-ends based on the path. For example, keep the website on the main origin, but serve /api/* from the API servers and /docs/* from a static site.
const backends: { prefix: string; host: string }[] = [
{ prefix: '/api/', host: 'https://api-origin.example.com' },
{ prefix: '/docs/', host: 'https://docs-origin.example.com' }
];
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const backend = backends.find(b => url.pathname.startsWith(b.prefix));
if (backend) {
return fetch(new Request(backend.host + url.pathname + url.search, request));
}
return fetch(request);
}
The same pattern works with other inputs. For example, when IP Geolocation is enabled for the zone, Cloudflare adds the CF-IPCountry header with the country code of the user, and we can route the users to a country specific site or back-end.
const country = request.headers.get('CF-IPCountry'); // e.g. "GB", "IN"
Pattern 5: Normalize URLs to improve caching
The Cloudflare cache key includes the URL as it is. So, /Products?b=2&a=1 and /products?a=1&b=2 are cached as two different entries, even when the origin returns the same content. Normalizing the URL in the worker makes them one.
export function normalizeUrl(input: string): string {
const url = new URL(input);
url.pathname = url.pathname.toLowerCase();
const params: string[] = [];
url.searchParams.forEach((value, key) => params.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`));
url.search = params.sort().join('&');
return url.toString();
}
export async function handleRequest(request: Request): Promise<Response> {
return fetch(new Request(normalizeUrl(request.url), request));
}
The subrequest uses the normalized URL, so the cache (and the page rules) see one URL for all the variations. Only normalize the parts which really don’t matter to your origin; if your origin treats the case of the path or a query parameter as meaningful, keep it.
Pattern 6: Handle origin failures
When the origin is down or returns a server error, serve a friendly maintenance page instead of the error.
const maintenancePage = `<!DOCTYPE html>
<html><body><h1>We'll be back soon</h1><p>We are performing maintenance. Please try again in a few minutes.</p></body></html>`;
export async function handleRequest(request: Request): Promise<Response> {
try {
const response = await fetch(request);
if (response.status < 500) {
return response;
}
} catch (e) {
// The origin is not reachable; fall through to the maintenance page
}
return new Response(maintenancePage, {
status: 503,
headers: { 'content-type': 'text/html', 'retry-after': '300' }
});
}
In the entry file, we can also call event.passThroughOnException() before respondWith. When the worker code itself throws an unhandled exception, the request is then sent to the origin as if there was no worker (fail open), instead of returning an error to the user.
addEventListener('fetch', event => {
event.passThroughOnException();
event.respondWith(handleRequest(event.request));
});
How to unit test a worker which calls the origin?
Don’t call the real origin from the unit tests. Replace the global fetch with a fake function, capture the request the worker sends, and return a prepared response. For example, the test for the security headers pattern,
import './setup';
import { expect } from 'chai';
import { handleRequest } from '../src/handler';
describe('security headers', () => {
it('should add security headers and remove X-Powered-By', async () => {
// Arrange
(global as any).fetch = async () =>
new Response('ok', { headers: { 'X-Powered-By': 'ASP.NET' } });
// Act
const response = await handleRequest(new Request('https://www.example.com/'));
// Assert
expect(response.headers.get('X-Frame-Options')).to.equal('DENY');
expect(response.headers.get('X-Powered-By')).to.equal(null);
});
});
And for the URL normalization, test the pure function directly with all the variations you expect,
it('should normalize the case and the order of the query string', () => {
expect(normalizeUrl('https://www.example.com/Products?b=2&a=1'))
.to.equal('https://www.example.com/products?a=1&b=2');
});
Most of the worker logic can be written as pure functions like normalizeUrl, which are the easiest to test.
Wrap up
In this article, we have looked at the common worker patterns: modifying the request and the response, responding at the edge with redirects and blocks, routing to different back-ends, normalizing URLs for caching and handling origin failures, along with how to unit test them with a fake fetch. I really appreciate that you took the time to read this article. In the next article, I will walk you through the real world use cases where we used workers, and the lessons we learned running them in production.
Related Posts
Cloudflare Workers use cases and lessons learned - Part 4
Where Cloudflare Workers fit best, how a worker cut our origin requests by about 84%, and the lessons we learned running it in production.
What is Cloudflare Worker and why do we need it? - Part 1
Cloudflare Workers run our JavaScript at the edge. See what a worker is, how it works with routes, how it compares with page rules and when to use it.
How to set up a local development environment for Cloudflare Workers? - Part 2
Set up a local development environment for Cloudflare Workers with Node.js, Yeoman and TypeScript, unit test the handler and bundle it with webpack.