Prebaked
Integration

Express (prerender-node)

Last reviewed

Use the official, unmodified prerender-node middleware on your Express or Node.js app and point it at Prebaked. Search engines, AI crawlers and link preview bots get the rendered page; visitors get your app. Only the service URL and the token change, so this also works if you already use prerender-node with another service.

How it works

prerender-node checks each request. For a crawler it fetches https://service.prebaked.io/<page URL> with your token and returns that HTML. Every other request goes on to your static files and app routes. Static files and requests carrying X-Prerender (Prebaked's own page fetches) are skipped.

Prerequisites

  • A Prebaked account with your domain added and verified.
  • Your domain token from the domain's Setup page.
  • An Express, Connect or plain Node http server that serves your site, and npm.

Step 1: Install

npm install prerender-node

Step 2: Add the middleware before your static files and SPA routes

const express = require('express');
const prerender = require('prerender-node');

const app = express();

app.use(
  prerender
    .set('prerenderServiceUrl', 'https://service.prebaked.io/')
    .set('prerenderToken', process.env.PREBAKED_TOKEN),
);

app.use(express.static('dist'));
app.get('/{*path}', (req, res) => res.sendFile('index.html', { root: 'dist' }));

Instead of set(...) you can use the environment variables the middleware already reads:

PRERENDER_SERVICE_URL=https://service.prebaked.io/
PRERENDER_TOKEN=<your token>

Use https://: Prebaked refuses plain http:// calls with 403. Mount the middleware on the app root (app.use(prerender)), not inside a sub-router, so the full path is sent.

Step 3: Serve your own page if Prebaked fails

By default prerender-node passes every Prebaked answer to the crawler, including 401/403 (wrong token, domain not verified yet) and 5xx, and answers 500 if Prebaked cannot be reached. Add the documented afterRender hook so crawlers only ever see your page's own status:

prerender.set('afterRender', (err, req, prerenderRes) => {
  const status = prerenderRes?.statusCode ?? 0;
  const pageStatus = (status >= 200 && status < 400) || status === 404 || status === 410;
  if (err || !pageStatus) return { cancelRender: true };
});

With it, an unreachable Prebaked, 400, 401, 403 and 5xx serve your normal page. 200, redirects, 404 and 410 are the rendered page's own status and still reach the crawler.

Step 4: Add a time limit

prerender-node has no timeout of its own: if Prebaked is slow, the crawler waits. Download prerender-timeout.cjs (one file, no dependencies) next to your server file and wrap the middleware. If Prebaked has not answered within 10 seconds, the crawler gets your normal page. prerender-node itself stays unmodified, and its late answer is dropped, so the response is never written twice.

curl -O https://prebaked.io/integrations/files/express/prerender-timeout.cjs
const { withTimeout } = require('./prerender-timeout.cjs');

app.use(withTimeout(prerender));                        // default 10 seconds
// The default is 10 s. Don't go much lower: the first request on a new connection to the service can take a few seconds.

Use it together with the afterRender hook from step 3: the hook covers errors, the wrapper covers slow answers. In an ES module use import { withTimeout } from './prerender-timeout.cjs';.

Plain Node server (no Express)

withTimeout returns a connect-style (req, res, next) function, so it also works with a plain Node http server: call it for every request and serve your own page in next. A complete server.mjs for a built single-page app (for example a Vite dist/ folder), with the fallback hook, the extra crawlers from step 5 and the time limit:

// Plain Node server (no Express) for a built single-page app, e.g. a Vite `dist/` folder.
// Crawlers get the page rendered by Prebaked through the official prerender-node middleware,
// with a 10 s time limit (prerender-timeout.cjs); everyone else gets the files in `dist/`.
//
//   npm install prerender-node
//   PREBAKED_TOKEN=<your token> node server.mjs
//
// Needs prerender-timeout.cjs next to this file. Optional env: PORT (3000), DIST_DIR (dist).
import { createReadStream, statSync } from 'node:fs';
import { createServer } from 'node:http';
import { extname, join, normalize, resolve, sep } from 'node:path';
import prerender from 'prerender-node';
import { withTimeout } from './prerender-timeout.cjs';

const DIST = resolve(process.env.DIST_DIR ?? 'dist');
const PORT = Number(process.env.PORT ?? 3000);
const TYPES = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.webp': 'image/webp',
  '.ico': 'image/x-icon',
  '.woff2': 'font/woff2',
  '.txt': 'text/plain; charset=utf-8',
  '.xml': 'application/xml',
};

prerender
  .set('prerenderServiceUrl', process.env.PREBAKED_SERVICE_URL ?? 'https://service.prebaked.io/')
  .set('prerenderToken', process.env.PREBAKED_TOKEN)
  // Prebaked errors serve your own page; only the rendered page's own status reaches crawlers.
  .set('afterRender', (err, req, prerenderRes) => {
    const status = prerenderRes?.statusCode ?? 0;
    const pageStatus = (status >= 200 && status < 400) || status === 404 || status === 410;
    if (err || !pageStatus) return { cancelRender: true };
  })
  .addUserAgents(['OAI-SearchBot', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'meta-externalagent']);

const prebaked = withTimeout(prerender, { timeoutMs: 10_000 });

/** A file inside DIST, or null. */
function fileFor(urlPath) {
  let path;
  try {
    path = normalize(join(DIST, decodeURIComponent(urlPath)));
  } catch {
    return null;
  }
  if (path !== DIST && !path.startsWith(DIST + sep)) return null;
  try {
    return statSync(path).isFile() ? path : null;
  } catch {
    return null;
  }
}

/** Static files from DIST; every other path gets index.html (SPA routes). */
function serveDist(req, res) {
  const urlPath = new URL(req.url, 'http://localhost').pathname;
  const file = fileFor(urlPath) ?? join(DIST, 'index.html');
  res.writeHead(200, { 'Content-Type': TYPES[extname(file)] ?? 'application/octet-stream' });
  if (req.method === 'HEAD') return res.end();
  createReadStream(file).pipe(res);
}

createServer((req, res) => {
  prebaked(req, res, (err) => {
    if (err) console.error(err);
    serveDist(req, res);
  });
}).listen(PORT, () => console.log(`http://localhost:${PORT}`));
npm install prerender-node
PREBAKED_TOKEN=<your token> node server.mjs

Step 5: Add the AI crawlers missing from prerender-node 3.8.3

prerender-node 3.8.3 (the current npm release) does not recognise these crawlers that Prebaked supports, so they would get your empty SPA shell. Add them:

prerender.addUserAgents(['OAI-SearchBot', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'meta-externalagent']);

This list is checked against Prebaked's bot list by test/recommended-setup.test.ts.

Step 6: Set the host behind a proxy or CDN

The page URL sent to Prebaked is built from X-Forwarded-Proto and X-Forwarded-Host (or Host). If your proxy does not set them, fix the values:

prerender.set('protocol', 'https').set('host', 'www.<your-domain>');

Test the installation

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

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 request appears in the Prebaked dashboard request log.

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.

prerender-node cannot ask for Markdown, so add prebaked-markdown.cjs (one file, no dependencies) next to your server file and mount it before prerender-node (and before prebakedMode in test mode):

curl -O https://prebaked.io/integrations/files/express/prebaked-markdown.cjs
const { prebakedMarkdown } = require('./prebaked-markdown.cjs');

app.use(prebakedMarkdown({ token: process.env.PREBAKED_TOKEN }));   // reads PREBAKED_MODE
app.use(prerender);

In an ES module use import { prebakedMarkdown } from './prebaked-markdown.cjs';. TypeScript apps can copy prebaked-markdown.ts instead. When it falls back for a .md path it sets X-Prerender: 1 on the request, so prerender-node leaves the path to your app. 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 service keeps answering crawlers. Prebaked does not need your current service's URL or token. Download prebaked-mode.cjs (one file, no dependencies) next to your server file and mount it before your existing prerender-node, which stays pointed at your current service:

curl -O https://prebaked.io/integrations/files/express/prebaked-mode.cjs
const { prebakedMode } = require('./prebaked-mode.cjs');

app.use(prebakedMode({ token: process.env.PREBAKED_TOKEN }));   // reads PREBAKED_MODE
app.use(
  prerender
    .set('prerenderServiceUrl', process.env.PRERENDER_SERVICE_URL) // your current service, unchanged
    .set('prerenderToken', process.env.PRERENDER_TOKEN),
);
PREBAKED_MODE=shadow    # then ai, then all
PREBAKED_TOKEN=<your token>

In an ES module (for example server.mjs) use import { prebakedMode } from './prebaked-mode.cjs';. TypeScript apps can copy prebaked-mode.ts instead; both files behave the same.

  • shadow: your current prerender-node answers every crawler. Prebaked gets a background copy, renders and caches the page; its answer is discarded and never delays the response.
  • ai: Prebaked answers AI crawlers (GPTBot, OAI-SearchBot, ChatGPT-User, ClaudeBot, Claude-User, PerplexityBot, ...); the other crawlers go on to your current prerender-node.
  • all (default): Prebaked answers every crawler.

If Prebaked fails, answers an error or takes over 5 seconds, the request goes on to your current prerender-node unchanged. Restart the app after each change. Roll back by setting the previous mode. When you cancel the old service, point prerender-node at Prebaked (step 2) and remove prebakedMode.

Common errors

What you see Cause Fix
Crawlers get a 401 or 403 error page Wrong token or unverified domain, and the afterRender hook from step 3 is missing Fix the token or verify the domain, and add the hook
403 for every request The service URL uses http:// Use https://service.prebaked.io/
Crawlers wait a long time for a page prerender-node has no time limit of its own Wrap it in withTimeout (step 4)
ClaudeBot or OAI-SearchBot still get the empty shell prerender-node 3.8.3 does not know them Add them with addUserAgents (step 5)
Prebaked gets the wrong page URL The middleware is mounted in a sub-router, or the proxy does not set X-Forwarded-Host Mount it on the app root and set protocol and host (step 6)

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

Fallback and security

Without the hook from step 3, prerender-node passes every Prebaked answer to the crawler, including errors, and it has no timeout of its own. With the hook, an unreachable Prebaked, 400, 401, 403 and 5xx serve your normal page, while 200, redirects, 404 and 410 reach the crawler. With the withTimeout wrapper from step 4, an answer slower than 10 seconds also serves your normal page. The token travels only over https://.

Removing it

Remove the app.use(prerender...) line and its settings, then run npm uninstall prerender-node and restart the app.

FAQ

I already use prerender-node with another service. What changes?

Only the service URL and the token. Your middleware and its settings stay. See switching for the full steps.

Does prerender-node time out if Prebaked is slow?

prerender-node has no timeout of its own. Wrap it in withTimeout from step 4: after 10 seconds (or your own limit) the crawler gets your normal page. The afterRender hook from step 3 handles errors.

Does this work without Express?

Yes. prerender-node and withTimeout are connect-style (req, res, next) functions, so a plain Node http server can call them for every request. See the plain Node server example.

Which crawlers get the rendered page?

The crawlers prerender-node knows, plus the ones you add in step 5. The full Prebaked list is on the crawlers page.