Prebaked
Integration

Vercel / Next.js middleware

Last reviewed

A middleware that runs before your pages sends search engines, AI crawlers and link preview bots to Prebaked, and lets every other request continue to your site unchanged. Use it for a client-rendered app on Vercel: Next.js pages that render in the browser, or another framework through Vercel Routing Middleware. Pages that Next.js already renders on the server or at build time do not need Prebaked.

How it works

For visitors the middleware returns nothing, so the request continues to your site. For crawlers it returns the page rendered by Prebaked.

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.

Prerequisites

  • A Prebaked account with your domain added and verified.
  • Your domain token from the domain's Setup page.
  • A Vercel project you can change, and the Vercel project settings or CLI to set environment variables.

Step 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)
mkdir -p lib
curl -o middleware.ts https://prebaked.io/integrations/files/vercel/middleware.ts
curl -o lib/prebaked-edge.ts https://prebaked.io/integrations/files/vercel/prebaked-edge.ts

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

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.

Step 2: Set the environment variables

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

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.

Step 3: Deploy and check

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

Then check which side answered:

curl -sI -A "GPTBot" https://www.<your-domain>/ | grep -i x-prebaked
  • x-prebaked: hit: Prebaked answered from its cache.
  • x-prebaked: stale: Prebaked answered from an older cached copy and refreshes it in the background.
  • x-prebaked: rendered: Prebaked rendered the page for this request.
  • x-prebaked: origin: Prebaked fetched your page itself without rendering it, for example when the render took too long.
  • No output: your site answered directly. The integration is not active yet, the user agent did not match, or the fallback served your page.

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

Test the installation

The curl commands in step 3 show the difference: as Googlebot you get the full HTML, as a visitor your normal page. The first request for a page can take a few seconds while Prebaked renders it; later requests come from the cache. Then run the free checker on the same page.

Markdown requests

Turning it on per domain, choosing pages and testing: Agent-ready responses.

Requests that ask for Markdown go to Prebaked whatever the user agent: a path ending in .md (any case), or an Accept header that prefers text/markdown over text/html (*/* alone never does). They are sent with X-Prebaked-Formats: markdown and the visitor's Accept. When Markdown is off or unavailable for the page (X-Prebaked-Markdown in the answer), or Prebaked fails or is slow, the request goes on to your site unchanged, so your own .md files keep working; a crawler that asked by Accept only gets the normal prerendered HTML. Test mode shadow leaves Markdown requests untouched; ai routes them for every user agent. Check:

curl -sI https://www.<your-domain>/pricing.md
curl -sI -H 'Accept: text/markdown' https://www.<your-domain>/pricing

Test mode

Test Prebaked while your current prerender setup keeps answering crawlers. You do not need your current service's URL or token:

vercel env add PREBAKED_MODE            # shadow, then ai, then all
  • shadow: the middleware returns nothing, so every request continues to your site untouched and your current prerender setup keeps answering crawlers. Prebaked gets a background copy (event.waitUntil), renders and caches the page; its answer is discarded.
  • ai: Prebaked answers AI crawlers (GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-User, PerplexityBot, ...); every other request continues to your site untouched.
  • all (default): Prebaked answers every crawler.

Redeploy after each change. Roll back by setting the previous mode.

Add-on for an existing prerender middleware

If your current prerender service runs as Vercel or Next.js middleware (event is the second argument of your middleware function), keep it and do not install this integration on the same route. Paste this function into your existing script once:

// Prebaked shadow add-on: sends a background copy of each crawler page request to Prebaked.
// Your response is not changed or delayed.
const PREBAKED_BOTS =
  /GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-User|Claude-SearchBot|CCBot|PerplexityBot|Perplexity-User|meta-externalagent|Bytespider|Googlebot|Applebot|bingbot|facebookexternalhit|TelegramBot|Twitterbot|LinkedInBot|Slackbot-LinkExpanding|Discordbot|WhatsApp/i;
const PREBAKED_STATIC = /\.(?:js|css|xml|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf|otf|eot|pdf|txt|json|map|mp4|zip)$/i;
function prebakedShadow(request, token, waitUntil) {
  const ua = request.headers.get('user-agent') || '';
  if (!token || request.method !== 'GET' || request.headers.has('x-prerender')) return;
  if (!PREBAKED_BOTS.test(ua) || PREBAKED_STATIC.test(new URL(request.url).pathname)) return;
  const copy = fetch('https://service.prebaked.io/' + request.url, {
    headers: { 'x-prerender-token': token, 'x-prebaked-mode': 'shadow', 'user-agent': ua },
  });
  waitUntil(copy.then((res) => res.body?.cancel(), () => undefined));
}

Then add this line at the start of your request handler:

prebakedShadow(request, process.env.PREBAKED_TOKEN, (p) => event.waitUntil(p));

Your current script keeps answering crawlers; Prebaked only gets the background copy. When you are ready for ai or all, replace your script with this integration. Details: Test before you switch.

Common errors

What you see Cause Fix
Crawlers still get your empty page PREBAKED_SERVICE_URL or PREBAKED_TOKEN is not set, so every request continues to your site Add both variables and redeploy
Crawlers get your normal page, Prebaked logs a 401 Wrong or old token Copy the current token from the Setup page and set PREBAKED_TOKEN again
Crawlers get your normal page, Prebaked logs a 403 The domain is not verified yet Verify the domain in the dashboard
The middleware does not run The file is not in the project root (or src/), or on Next.js 16 it is not named proxy.ts Check the file name and place from step 1
Your own middleware no longer runs for crawlers The Prebaked response is returned first This is expected: crawlers get the rendered page, everyone else goes through your middleware

More help: Crawlers still see an empty page and 401 and 403 errors.

Fallback and security

If Prebaked cannot be reached, answers an error or takes over 5 seconds, the request continues to your site. Prebaked gets the page URL, the crawler's user agent, your token and the visitor IP, not the visitor's cookies.

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

Removing it

Delete middleware.ts (or proxy.ts) and lib/prebaked-edge.ts, or the Prebaked call in your own middleware, remove the PREBAKED_* environment variables and redeploy.

FAQ

Do I need this if my Next.js pages are server-rendered?

No. Pages that Next.js renders on the server or at build time already send full HTML to crawlers. Prebaked helps with pages that render only in the browser.

Can I keep my existing middleware?

Yes. Call fetchPrerendered first and return its response when there is one, as shown in step 1. Everything else goes on to your middleware.

What happens if Prebaked is down?

The request continues to your site. The middleware waits at most 5 seconds for Prebaked and also falls back on errors such as 401, 403 and 5xx.