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:

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

  1. Ask the legal service's maintainer for:

    • the service address (e.g. https://legal.yourdomain.com), which becomes LEGAL_URL in step 3;
    • your site key (e.g. my-site). The maintainer registers the site's name, domain and support email under it.
  2. Check which docs exist for you by opening each one in a browser:

    • https://legal.yourdomain.com/<site-key>/terms
    • https://legal.yourdomain.com/<site-key>/privacy
    • https://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.

  3. 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:

  1. Copy everything from // ==== legal pages down to // ==== end legal pages (from the code in 3a) and paste it into your existing file, above its onRequest export. Don't copy the last line (export const onRequest = [legalPages];).

  2. Edit the config block as described in 3a.

  3. Add legalPages to your existing onRequest export, 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, onRequestPost or another method-specific handler. Keep those exports as they are. Add export 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.

Step 5A: Single-page app (type A)

  1. 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.

  2. Add the component. Create LegalDoc.tsx next 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.

  3. 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.

  4. 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>
    
  5. 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"); }, []);
    
  6. 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)

  1. 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.

  2. Set SHELL in the middleware to the URL your build serves that page at:

    • legal.html or pages/legal.tsx (default Next.js export) → "/legal"
    • legal/index.html, or Next.js with trailingSlash: 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.

  3. Remove the old legal pages (e.g. terms.html, pages/terms.tsx), so the middleware is the only thing serving those paths.

  4. Links: use plain <a href="/terms">. In Next.js, don't use next/link for 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:

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.