Skip to content

Vercel / Next.js middleware

Next.js middleware (or Vercel Routing Middleware) sends crawlers to Prebaked and lets every other request continue to your site. If Prebaked fails or takes over 5 seconds, crawlers get your normal page.

A middleware that runs before your pages. Crawlers (search engines, AI crawlers, link previews) get the page prerendered by Prebaked; for every other request it returns nothing, so the request continues to your site unchanged.

What it does

Same rules as the Cloudflare Worker:

  • Prerenders only GET / HEAD requests from a known crawler user agent. Static files, other methods and requests carrying X-Prerender continue to your site.
  • Calls GET https://service.prebaked.io/<full page URL> with X-Prerender-Token.
  • Passes Prebaked's 200, redirects, 404 and 410 to the crawler.
  • Lets the request continue to your site when Prebaked cannot be reached, takes longer than 5 seconds, or answers 401/403, 400 or 5xx.

1. Copy the files

Into the project root (next to package.json, or into src/ if you use it):

  • middleware.ts. On Next.js 16 and later, name it proxy.ts; the default export works for both.
  • lib/prebaked-edge.ts (bot detection, service URL, fallback; no dependencies)

If you already have a middleware, call the Prebaked part first and return its response when there is one:

ts
import { fetchPrerendered } from './lib/prebaked-edge';

const prerendered = await fetchPrerendered(request, {
  serviceUrl: process.env.PREBAKED_SERVICE_URL,
  token: process.env.PREBAKED_TOKEN,
  clientIp: request.headers.get('x-real-ip'),
  integration: 'vercel',
});
if (prerendered) return prerendered;
// ... your existing middleware

For other frameworks on Vercel, the same middleware.ts works as Vercel Routing Middleware.

2. Set the environment variables

In the Vercel project settings (Environment Variables) or with the CLI:

sh
vercel env add PREBAKED_SERVICE_URL   # https://service.prebaked.io/
vercel env add PREBAKED_TOKEN         # your token

Without either variable every request continues to your site.

3. Deploy and check

sh
curl -A "Googlebot" https://www.<your-domain>/        # rendered HTML
curl https://www.<your-domain>/                      # your normal page

The first crawler request appears in the Prebaked dashboard request log.

Notes

  • config.matcher skips /_next/static and /_next/image; other static files are skipped in code by extension.
  • The visitor IP (x-real-ip) is sent as X-Forwarded-For so Prebaked can verify crawler IPs.

Other integrations

Switching from another prerender service? Read the switch guide.

Start a 30-day free trial.

No card needed. Add and verify your domain, copy your token, paste it into the config above.

Start free trial