Adding legal pages to a site
Step-by-step instructions for making a site show its legal pages (terms, privacy
policy, and so on) from a central legal service. The service is one deployment
that holds the legal text for many sites, at an address such as
legal.yourdomain.com; this guide uses that name throughout. Everything you need is
in this document. You don't need access to any other project.
Result: a visitor opens https://<your-domain>/terms. The page shows the
current legal text inside your site's normal layout and styling, and the address
bar stays on your domain. View-source shows your own HTML and CSS, the legal text,
and no mention of the legal service. The legal wording is maintained centrally.
Your site never stores a copy.
How it works: one file in your site, functions/_middleware.ts, runs on your
Cloudflare Pages project. For the legal paths you list, it fetches the finished
HTML from https://legal.yourdomain.com/<site-key>/<doc> on the server. It then
inserts the HTML into one of your own pages at an element with id="legal-doc",
and returns that page with status 200. Every other request passes through
untouched.
Step 0: Check that this guide applies
This guide works when all of these are true:
- The site is deployed on Cloudflare Pages, not a plain Worker, Vercel, Netlify or similar.
- Pages Functions are available. They are, unless a framework adapter owns
functions/(e.g.@cloudflare/next-on-pagesor Astro/SvelteKit SSR adapters). - The site is one of:
- Type A: single-page app. One
index.htmlwith an empty root element (<div id="root">), and all pages rendered in the browser. Examples: Vite + React, Create React App, Vite + Vue. - Type B: static site. Each page is its own pre-built HTML file. Examples:
plain HTML, Next.js with
output: 'export', Astro static, Hugo, Eleventy.
- Type A: single-page app. One
If any box is unchecked, stop. This guide doesn't cover that setup yet. Ask the legal service's maintainer.
Step 1: Get the service address, your site key and doc names
Ask the legal service's maintainer for:
- the service address (e.g.
https://legal.yourdomain.com), which becomesLEGAL_URLin step 3; - your site key (e.g.
my-site). The maintainer registers the site's name, domain and support email under it.
- the service address (e.g.
Check which docs exist for you by opening each one in a browser:
https://legal.yourdomain.com/<site-key>/termshttps://legal.yourdomain.com/<site-key>/privacyhttps://legal.yourdomain.com/<site-key>/affiliate-disclosure(only some sites have one)
A doc that returns 404 doesn't exist for your site. Don't route it.
Read the text and confirm it shows your site's name and domain.
Step 2: Choose your paths
Decide which path on your site shows each doc, e.g. /terms → terms and
/privacy-policy → privacy. Keep the paths your site already uses so
existing links, bookmarks and search results keep working. Write them down; you'll
need them in steps 3 and 4.
Step 3: Add functions/_middleware.ts
functions/ belongs at the root of the Pages project (the build root
directory), next to package.json. It does not go inside the build output
(dist/, out/, build/).
3a. Your site has no functions/_middleware.ts yet
Create functions/_middleware.ts with exactly this content, then edit the
config block. Leave everything below it unchanged.
// ==== legal pages (central legal service) =================================
// Serves this site's legal pages from a central legal service. The HTML is
// fetched server-side and inserted into one of this site's own pages, so the
// address bar stays on this domain and view-source shows only this site's
// HTML and CSS. Requests for any other path pass through untouched.
// ---- config -------------------------------------------------------------
const SITE = "your-site-key"; // this site's key at the legal service
const ROUTES: Record<string, string> = {
// this site's path -> legal doc name
"/terms": "terms",
"/privacy": "privacy",
// List only docs this site has. Unlisted paths never reach this code.
};
// Path of the page the legal HTML is inserted into. It must contain an
// element with id="legal-doc".
// single-page app: "/" (index.html with <template id="legal-doc"></template>)
// static site: "/legal" (a normal page with <main id="legal-doc"></main>)
const SHELL = "/";
const LEGAL_URL = "https://legal.yourdomain.com"; // the legal service's address
// -------------------------------------------------------------------------
async function legalPages(context: any) {
const { request, next, env } = context;
// "/terms/" and "/terms" are the same page.
const path = new URL(request.url).pathname.replace(/(.)\/$/, "$1");
const doc = ROUTES[path];
if (!doc) return next();
const [legal, shell] = await Promise.all([
fetch(`${LEGAL_URL}/${SITE}/${doc}`),
env.ASSETS.fetch(new URL(SHELL, request.url)),
]);
// No such doc for this site: behave as if the route didn't exist, so the
// site's normal 404 handling applies.
if (legal.status === 404) return next();
if (!legal.ok || !shell.ok) {
return new Response("Legal document temporarily unavailable", { status: 503 });
}
const html = await legal.text();
// Via globalThis so this compiles with or without @cloudflare/workers-types.
const Rewriter = (globalThis as any).HTMLRewriter;
const page = new Rewriter()
.on("#legal-doc", {
element(el: any) {
el.setInnerContent(html, { html: true });
},
})
.transform(shell);
// Always 200: a single-page app's shell may come from a 404.html fallback.
return new Response(page.body, { status: 200, headers: page.headers });
}
// ==== end legal pages =====================================================
export const onRequest = [legalPages];
Set the config:
| Setting | Value |
|---|---|
SITE |
Your site key from step 1. |
ROUTES |
Your paths from step 2, each mapped to a doc name that exists for you. Paths start with / and have no trailing slash. |
SHELL |
Type A: "/". Type B: the path of the shell page you'll create in step 5B. |
LEGAL_URL |
The service address from step 1, with no trailing slash, e.g. "https://legal.yourdomain.com". |
3b. Your site already has functions/_middleware.ts
Don't replace the file. Merge into it:
Copy everything from
// ==== legal pagesdown to// ==== end legal pages(from the code in 3a) and paste it into your existing file, above itsonRequestexport. Don't copy the last line (export const onRequest = [legalPages];).Edit the config block as described in 3a.
Add
legalPagesto your existingonRequestexport, using the case that matches your file:Case 1: the export is a single function.
// before export const onRequest = async (context) => { /* your code */ }; // after: give your function a name, then export both const siteMiddleware = async (context) => { /* your code, unchanged */ }; export const onRequest = [siteMiddleware, legalPages];Case 2: the export is a function declaration.
// before export async function onRequest(context) { /* your code */ } // after async function siteMiddleware(context) { /* your code, unchanged */ } export const onRequest = [siteMiddleware, legalPages];Case 3: the export is already an array.
// before export const onRequest = [auth, headers]; // after: add legalPages at the end export const onRequest = [auth, headers, legalPages];Case 4: the file exports
onRequestGet,onRequestPostor another method-specific handler. Keep those exports as they are. Addexport const onRequest = [legalPages];as a separate line.
Order matters. Middleware runs left to right, and each one calls next() to pass
the request on. Put legalPages after anything that must apply to every page
(redirects, auth, security headers), so those also apply to the legal pages. It must
also come before anything that returns a response without calling next() for
the legal paths.
Your existing middleware must call next() for the legal paths. If it returns its
own response for them (e.g. a catch-all), legalPages never runs.
Step 4: Let Pages Functions run on your legal paths
Look for a _routes.json in the project root or in public/. It may also be copied
into the build output by a build script.
No
_routes.json: Functions run on every path. Nothing to do._routes.jsonexists: add each legal path from step 2 to"include", and make sure none of them is listed under"exclude":// before { "version": 1, "include": ["/api/*"], "exclude": [] } // after { "version": 1, "include": ["/api/*", "/terms", "/privacy-policy"], "exclude": [] }Without this, Pages never runs your middleware on those paths, and they show whatever the site served before.
Step 5A: Single-page app (type A)
index.html: add an empty template inside<body>, right after your root element:<div id="root"></div> <template id="legal-doc"></template>A
<template>is never displayed by the browser. It only carries the HTML for your app to render.Add the component. Create
LegalDoc.tsxnext to your other components, with exactly this content:// Renders the legal HTML that functions/_middleware.ts inserted into // index.html's <template id="legal-doc">. Use it only on legal routes, and // reach those routes with a full page load (see the integration guide). export function LegalDoc() { const html = document.querySelector<HTMLTemplateElement>("#legal-doc")?.innerHTML ?? ""; if (!html) { // Reached by client-side navigation, or running without Pages Functions (vite dev). return ( <p> <a href={window.location.pathname}>Load this document</a> </p> ); } return <article className="legal-doc" dangerouslySetInnerHTML={{ __html: html }} />; }Not using React? Do the same thing in your framework: read
document.getElementById("legal-doc").innerHTML, and render it as raw HTML.Render it on each legal route, inside your normal page layout. Put it in the wrapper you use for long-form text, so it picks up your typography, e.g.:
<Route path="/terms" element={<Page title="Terms and Conditions"><div className="prose"><LegalDoc /></div></Page>} />The HTML contains its own
<h1>, effective date, headings, lists and links. Style.legal-doc(or the wrapper) the way you style other text pages.Make every link to a legal page do a full page load. The legal HTML is only there when the page is served by the middleware. A client-side navigation skips the server, and the page then shows only the "Load this document" link. Search the codebase for every link to each legal path (footer, cookie banner, signup forms, emails) and change them:
// react-router: add reloadDocument <Link to="/terms" reloadDocument>Terms and Conditions</Link> // anything else: a plain anchor <a href="/terms">Terms and Conditions</a>Other URLs that show the same doc (aliases such as
/legal/terms): send them to the real path with a full load, e.g. in that route's component:useEffect(() => { window.location.replace("/terms"); }, []);Remove the old legal content: markdown, JSON, components or PDFs that held the text, plus their imports. Keep only what's still used by other pages.
Local development: the Vite (or similar) dev server doesn't run Pages Functions, so legal pages only show the "Load this document" link there. That's expected. To test for real, build and serve the output with Pages Functions:
npm run build
npx wrangler pages dev dist --compatibility-date=2026-09-18 # use your output dir
Then open http://127.0.0.1:8788/terms.
Step 5B: Static site (type B)
Create a shell page. This is one ordinary page of your site, built with your normal layout (header, footer, CSS), containing an empty element where the legal text goes:
<main id="legal-doc" class="prose"></main>Style it the way you style other text pages. Examples:
- Plain HTML:
legal.html. - Next.js pages router (
output: 'export'):pages/legal.tsx, returning your layout with<main id="legal-doc" className="prose"></main>. - Next.js app router:
app/legal/page.tsx, the same way.
Optionally add
<meta name="robots" content="noindex">to it, because on its own it shows an empty article.- Plain HTML:
Set
SHELLin the middleware to the URL your build serves that page at:legal.htmlorpages/legal.tsx(default Next.js export) →"/legal"legal/index.html, or Next.js withtrailingSlash: true→"/legal/"
Check it by opening that URL on a deployed preview. It must load directly with 200, not redirect. A redirect makes the legal pages fail with a 503.
Remove the old legal pages (e.g.
terms.html,pages/terms.tsx), so the middleware is the only thing serving those paths.Links: use plain
<a href="/terms">. In Next.js, don't usenext/linkfor legal pages, because it tries to prefetch a page that no longer exists in the export.
Step 6: Deploy and verify
Deploy the site as usual, then check each legal path from step 2:
-
curl -s -o /dev/null -w "%{http_code}\n" https://<your-domain>/termsprints 200. - In a browser, the page shows the legal text inside your normal layout, and the address bar still shows your domain.
- View-source contains the legal text and your own CSS links, and does not
contain the legal service's address (e.g.
legal.yourdomain.com) or.md. -
/terms/(with a trailing slash) shows the same page. - Every link to a legal page loads the text. Click them from other pages (footer, banners). This matters most for type A.
- A doc you didn't route (e.g.
/affiliate-disclosure) shows your normal 404 page. - Non-legal pages behave exactly as before.
Step 7: Leave a note for future maintainers
Add this to the site's README.md or CLAUDE.md, filling in the brackets:
## Legal pages
[/terms, /privacy-policy, ...] are served from [legal service address] (site key
`[your-site-key]`) by `functions/_middleware.ts`. The wording is not in this repo,
so change it in the legal service, not here. Links to these pages must do a
full page load. Under the local dev server they show only a "Load this document"
link; that's expected.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Legal path shows the site's old page, 404, or empty layout | Middleware not running on that path | Add the path to _routes.json "include" (step 4). Check functions/ is at the project root (step 3). |
| Page loads, but only shows "Load this document" | Reached by client-side navigation, or the dev server has no Functions | Make the link a full load (step 5A.4). Test with wrangler pages dev (step 5A). |
| "Legal document temporarily unavailable" (503) | The legal service or your shell page failed | Open https://legal.yourdomain.com/<site-key>/<doc>, and check that LEGAL_URL is right. Check that SHELL loads directly with 200 and no redirect. |
| Your site's 404 on a routed legal path | That doc doesn't exist for your site key | Check the doc URL from step 1. Fix the doc name in ROUTES, or remove the route. |
| Text appears, but unstyled | The element isn't inside your text styling | Put <LegalDoc /> / #legal-doc inside your prose/typography wrapper. |
| Other middleware stopped working, or legal pages skip it | Wrong order in the onRequest array |
See Order matters in step 3b. |
| Wrong site name or domain in the text | Wrong SITE value |
Use your own site key. The service never mixes sites. |