# Next.js Static Export on Cloudflare Workers: Fix Trailing Slash 404s

> Canonical URL: https://stackquota.com/guides/nextjs-static-export-cloudflare-workers-trailing-slash-404/
> Checked: 2026-12-04 · Published: 2026-12-04

Fix Next.js output: 'export' trailing slash 404s and 308 redirect loops on Cloudflare Workers Static Assets with wrangler.jsonc and zero-bill routing.

Deploying a Next.js 16 static export (`output: 'export'`) onto Cloudflare Workers Static Assets gives you global edge caching, `$0` bandwidth egress, and optional D1/R2 API routes in one `wrangler.jsonc` deployment. Yet one mismatched slash setting between `next.config.mjs` and Wrangler routinely breaks hard page refreshes with `404 Not Found`, triggers `308` redirect loops, or silently bills `25` Worker invocations per page view.

Below is the exact production configuration we use to align Next.js static directory output, React Server Component (RSC) `.txt` flight payloads, custom `404.html` status codes, multi-subdomain CORS headers, and zero-cost asset routing.

## Why do Next.js static exports return 404 or 308 loops on Cloudflare Workers?

**Quick answer:** Next.js `output: 'export'` emits flat `route.html` files by default (`trailingSlash: false`) rather than `route/index.html` directories. When Cloudflare's `html_handling` setting or zone redirect rules disagree with Next.js's link format, direct refreshes and RSC `.txt` prefetches either miss on disk (`404`) or bounce endlessly between `/route` and `/route/`.

To see why client navigation works locally in `next dev` while hard refreshes fail on the edge, look at what `next build` actually writes into `./out` for `app/guides/[slug]/page.tsx`:

- **With `trailingSlash: false` (Next.js default):** Next.js writes `out/guides/d1-fix.html` and `out/guides/d1-fix.txt`. There is **no** `out/guides/d1-fix/index.html` folder unless nested child routes also exist. If an external link, sitemap entry, or Cloudflare rule appends a trailing slash (`/guides/d1-fix/`) while `html_handling` is set to `"none"` or `"force-trailing-slash"` without index fallback alignment, asset lookup misses.
- **RSC flight payload mismatch:** During client-side `<Link>` hover prefetching, Next.js App Router requests RSC metadata payloads (`.txt` / `__next.*.txt` segments) matching its configured `trailingSlash` convention. If a Worker or CDN rule rewrites HTML paths without matching directory semantics, HTML loads on first hit while client transitions fail or force full-document reloads.
- **308 / 301 infinite redirect loops:** Suppose you enable `trailingSlash: true` in `next.config.mjs` (emitting `out/guides/d1-fix/index.html` and canonical `<link rel="canonical" href=".../guides/d1-fix/">`), yet configure `html_handling: "drop-trailing-slash"` in `wrangler.jsonc`, or leave an old Cloudflare Page Rule / Redirect Rule normalizing URLs by stripping trailing slashes. Requesting `/guides/d1-fix/` returns `307`/`308` to `/guides/d1-fix`, while your internal links, canonicals, or custom Worker router redirect `/guides/d1-fix` right back to `/guides/d1-fix/`, tripping `ERR_TOO_MANY_REDIRECTS`.

## How should you pair next.config.mjs and wrangler.jsonc for clean URLs?

**Quick answer:** Set `output: 'export'` and `trailingSlash: true` in `next.config.mjs`, and pair them with `html_handling: "auto-trailing-slash"` and `not_found_handling: "404-page"` in `wrangler.jsonc`. Every route builds cleanly to `out/<path>/index.html`, `/path` canonicalizes to `/path/`, and missing URLs return a real HTTP `404`.

Lock in the Next.js side first in `next.config.mjs`:

```js
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
  trailingSlash: true,
  images: {
    // Required for pure static export unless using a custom Cloudflare Image Loader
    unoptimized: true,
  },
};

export default nextConfig;
```

If you serve responsive editorial photography and want edge WebP/AVIF resizing without Vercel Image Optimization overages, swap `unoptimized: true` for a custom `loaderFile` as shown in our [Next.js Image Optimization Cloudflare Loader Fix](/guides/nextjs-image-optimization-bill-spike-cloudflare-loader-fix/).

Next, pair `./out` in `wrangler.jsonc`:

```jsonc
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "prod-web",
  "main": "worker/index.ts",
  "compatibility_date": "2026-12-04",
  "assets": {
    "directory": "./out",
    "binding": "ASSETS",
    "html_handling": "auto-trailing-slash",
    "not_found_handling": "404-page",
    "run_worker_first": ["/api/*"]
  },
  "observability": {
    "enabled": true,
    "logs": { "enabled": true, "head_sampling_rate": 1 },
    "traces": { "enabled": true, "head_sampling_rate": 0.05 }
  }
}
```

Here is how each `html_handling` and `not_found_handling` combination behaves against Next.js `output: 'export'`:

| `next.config.mjs` | `wrangler.jsonc` `assets` | Disk Output (`./out`) | `/guides/slug` Request | `/guides/slug/` Request | Missing Route Status |
| --- | --- | --- | --- | --- | --- |
| `trailingSlash: true` | `html_handling: "auto-trailing-slash"`, `not_found_handling: "404-page"` | `guides/slug/index.html` | `307` -> `/guides/slug/` | **`200 OK`** | **`404`** (`out/404.html`) |
| `trailingSlash: true` | `html_handling: "drop-trailing-slash"` | `guides/slug/index.html` | `200 OK` (rewrites internally) | `307` -> `/guides/slug` (clashes with `<Link href=".../">`!) | `404` |
| `trailingSlash: false` | `html_handling: "none"` | `guides/slug.html` | **`404`** (expects `.html` ext) | **`404`** | `404` |
| Any | `not_found_handling: "single-page-application"` | `index.html` | `200 OK` | `200 OK` | **`200 OK`** (SEO Soft-404 bug!) |

Never use `not_found_handling: "single-page-application"` on a static-exported Next.js site with pre-rendered routes. Returning HTTP `200` with root `index.html` on dead URLs pollutes Google Search Console with Soft-404 errors and breaks AdSense/crawler verification on missing paths.

## Why do dynamic routes 404 without complete generateStaticParams?

**Quick answer:** Static exports run zero server rendering at request time, so every `[slug]` value not returned by `generateStaticParams()` during `next build` omits its `out/.../index.html` file and serves `404` on Cloudflare Workers. Enforce `dynamicParams = false` and verify `app/not-found.tsx` generates `out/404.html`.

In Next.js 16 App Router, dynamic segments (`app/guides/[slug]/page.tsx`) must enumerate every valid parameter object at build time:

```tsx
import { getAllGuideSlugs, getGuideBySlug } from "@/lib/guides";

// Fail fast during local dev if an unlisted slug is requested
export const dynamicParams = false;

export async function generateStaticParams() {
  const slugs = await getAllGuideSlugs();
  // Return bare segment strings—never include leading or trailing slashes!
  return slugs.map((slug) => ({ slug }));
}

export default async function GuidePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const guide = await getGuideBySlug(slug);
  return <article>{guide.title}</article>;
}
```

Audit three subtle build traps whenever a specific dynamic route returns `404` in production:
1. **Slashes or URL-encoding inside `generateStaticParams()`:** Returning `{ slug: "/my-guide/" }` instead of `{ slug: "my-guide" }` creates malformed nested folders during export.
2. **Case-sensitive Linux/Cloudflare asset matching:** macOS APFS is case-insensitive by default, so `<Link href="/guides/D1-Fix/">` may appear to resolve locally against `d1-fix`, yet Cloudflare's asset manifest performs exact case-sensitive path lookups (`404`). Normalize all slugs to lowercase kebab-case.
3. **Verify `out/404.html` exists at the root of `./out`:** Define `app/not-found.tsx` in your App Router project. Next.js exports `out/404.html` (alongside `out/404/index.html` when `trailingSlash: true`), which `not_found_handling: "404-page"` serves automatically with HTTP status `404` without invoking your Worker.

## Should you set security and CORS headers in _headers or Worker code?

**Quick answer:** Place static cache rules and security headers in `public/_headers` so Cloudflare's Asset Worker applies them for `$0.00` with zero Worker invocations. Reserve custom Worker code exclusively for `/api/*` routes or multi-subdomain setups requiring dynamic `Origin` allowlist reflection.

Cloudflare Workers Static Assets natively parses `out/_headers` (copied automatically from `public/_headers` during `next build`). Put immutable asset caching and baseline security headers there:

```text
/*
  X-Content-Type-Options: nosniff
  Referrer-Policy: strict-origin-when-cross-origin
  X-Frame-Options: DENY

/_next/static/*
  Cache-Control: public, max-age=31536000, immutable
```

Where `public/_headers` hits a hard ceiling is **authenticated multi-subdomain CORS** (for example, `app.example.com`, `admin.example.com`, and staging `*-preview.workers.dev` calling `api` or shared JSON manifests with credentials). Static `_headers` rules cannot inspect the incoming `Origin` header and echo back a validated single origin alongside `Vary: Origin`. And browsers reject `Access-Control-Allow-Origin: *` whenever `credentials: "include"` is set.

Keep static pages on `out/_headers` and handle dynamic multi-subdomain CORS strictly inside `worker/index.ts` for paths matched by `run_worker_first: ["/api/*"]`:

```ts
const ALLOWED_ORIGINS = new Set([
  "https://example.com",
  "https://app.example.com",
  "https://docs.example.com",
]);

function buildCorsHeaders(origin: string | null): HeadersInit {
  if (!origin || !ALLOWED_ORIGINS.has(origin)) {
    return { Vary: "Origin" };
  }
  return {
    "Access-Control-Allow-Origin": origin,
    "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Allow-Credentials": "true",
    Vary: "Origin",
  };
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const cors = buildCorsHeaders(request.headers.get("Origin"));

    if (request.method === "OPTIONS") {
      return new Response(null, { status: 204, headers: cors });
    }

    if (url.pathname.startsWith("/api/")) {
      const data = { ok: true, ts: Date.now() };
      return Response.json(data, { headers: cors });
    }

    return env.ASSETS.fetch(request);
  },
} satisfies ExportedHandler<Env>;
```

## How does run_worker_first impact your Cloudflare Workers monthly bill?

**Quick answer:** Requests served directly by Cloudflare Workers Static Assets cost `$0.00` and consume zero Worker quota. Setting `run_worker_first: true` routes every JS chunk, CSS file, image, and RSC `.txt` prefetch through your User Worker first, multiplying billable Worker invocations by `20x–30x` per page view.

Under verified December 2026 Cloudflare Workers pricing:
- **Workers Free:** `100,000` Worker requests/day (`10 ms` CPU limit per invocation), **unlimited free static asset requests**.
- **Workers Paid (`$5.00/mo` base):** `10,000,000` (`10M`) Worker requests/mo included (`+$0.30` per extra million), `30,000,000` (`30M`) CPU ms/mo included (`+$0.02` per extra million CPU ms), **unlimited free static asset requests**, and `$0.00/GB` egress.

Watch what happens when a developer sets `"run_worker_first": true` just to attach a response header in TypeScript instead of using `public/_headers`. One typical Next.js page view loads `1` HTML document, `14` `/_next/static/` JS/CSS chunks, `6` viewport `<Link>` RSC `.txt` prefetches, and `4` icons/fonts = **`25` HTTP requests**.

- On **Workers Free (`100K/day`)**, `run_worker_first: true` burns all `100,000` daily invocations after just **`4,000` page views/day**, taking your site offline with `1027` quota errors until UTC midnight!
- At **`4,000,000` monthly page views** (`100M` static/HTML hits + `4M` `/api/*` calls = `104M` total requests) on **Workers Paid**:
  - With `"run_worker_first": true`: All `104M` requests invoke your User Worker -> `$5.00 + ((104 - 10) * $0.30) = $33.20/mo`.
  - With `"run_worker_first": ["/api/*"]`: `100M` static/HTML requests hit the free Asset Worker (`$0.00`), and only `4M` `/api/*` calls invoke your User Worker (well inside the `10M` Paid base quota) -> **`$5.00/mo` flat** (or `$0.00/mo` at smaller scale on Free!).

Wrangler 4 also supports **negative glob rules** inside the `run_worker_first` array. Suppose your build generates static OpenAPI schema files at `out/api/docs/openapi.json` alongside dynamic D1 endpoints under `/api/*`. Setting `"run_worker_first": ["/api/*", "!/api/docs/*"]` routes dynamic API mutations to your User Worker while letting static schema documents bypass the Worker and serve directly from the free Asset Worker.

Model your exact mix of static traffic, `/api/*` Worker calls, D1 queries, and R2 media reads in our [Cloudflare Workers, D1 & R2 Cost Calculator](/calculators/cloudflare-workers-d1-r2-cost/). And when those `/api/*` handlers query D1 or stream JSON payloads, pair this routing setup with our [Cloudflare D1 rows_read Spike & Covering Index Fix](/guides/cloudflare-d1-rows-read-spike-unindexed-query-fix/) and [Cloudflare Workers Error 1102 CPU & Memory Limit Fix](/guides/cloudflare-workers-error-1102-cpu-memory-limit-fix/).

## Step-by-Step verification checklist with curl before production deploy

**Quick answer:** Verify single-hop `307` trailing-slash normalization, `200 OK` on trailing-slash HTML and RSC `.txt` files, true HTTP `404` on unknown paths, and zero User Worker log entries on static asset hits.

Run these five checks against your `wrangler deploy --config wrangler.preview.jsonc` preview URL before promoting to production:

```bash
# 1. Slashless URL canonicalizes cleanly in 1 hop (never a 308/307 loop)
curl -sI https://preview.example.com/guides/d1-fix | grep -E "HTTP/|location:"

# 2. Trailing-slash canonical route returns 200 OK HTML
curl -sI https://preview.example.com/guides/d1-fix/ | head -n 5

# 3. Missing route returns real HTTP 404 (not 200 Soft-404 index.html)
curl -sI https://preview.example.com/guides/does-not-exist/ | head -n 5

# 4. Static JS chunks carry immutable 1-year cache headers from public/_headers
curl -sI https://preview.example.com/_next/static/chunks/main.js | grep -i "cache-control"
```

Finally, open **Workers Logs** (`npx wrangler tail`) while clicking across `5` static pages in your browser. If `run_worker_first` is properly scoped to `["/api/*"]`, `wrangler tail` will emit **zero** Worker execution events for HTML, CSS, JS, and image requests, confirming `100%` of your static export serves straight from Cloudflare's free edge asset layer.
