// Time limit for the official prerender-node middleware (or any connect-style middleware). // prerender-node has no timeout of its own. Wrap it, and if Prebaked has not started answering // within `timeoutMs` (default 10 s), the request goes on to your normal page instead: // // const prerender = require('prerender-node'); // const { withTimeout } = require('./prerender-timeout.cjs'); // app.use(withTimeout(prerender.set('prerenderToken', process.env.PREBAKED_TOKEN))); // // Works with Express, Connect and a plain Node `http` server (call it as `(req, res, next)`). // prerender-node itself stays unmodified. When the time is up, everything prerender-node does for // that request afterwards (writeHead, end, next) is ignored, so the response is never written twice. // One file, no dependencies, CommonJS: `require()` it, or `import { withTimeout } from` it in ESM. 'use strict'; const DEFAULT_TIMEOUT_MS = 10_000; /** * @param {(req: any, res: any, next: (err?: unknown) => void) => void} middleware * @param {{ timeoutMs?: number }} [options] * @returns {(req: any, res: any, next: (err?: unknown) => void) => void} */ function withTimeout(middleware, options) { const timeoutMs = (options && options.timeoutMs) || DEFAULT_TIMEOUT_MS; return function prerenderWithTimeout(req, res, next) { // Who answers this request: 'middleware' (it wrote the response), 'next' (it passed it on) // or 'timeout' (we passed it on). The first one wins; later calls are ignored. let winner = null; const timer = setTimeout(() => { if (winner) return; winner = 'timeout'; next(); }, timeoutMs); const claim = (who) => { if (winner && winner !== who) return false; winner = who; clearTimeout(timer); return true; }; // The middleware writes through this object; everything else reads the real response. const guarded = Object.create(res); guarded.writeHead = function writeHead(...args) { if (!claim('middleware')) return guarded; res.writeHead(...args); return guarded; }; guarded.end = function end(...args) { if (!claim('middleware')) return guarded; res.end(...args); return guarded; }; try { middleware(req, guarded, (err) => { if (claim('next')) next(err); }); } catch (err) { if (claim('next')) next(err); } }; } module.exports = { withTimeout, DEFAULT_TIMEOUT_MS };