api-timeout-express
@rtorcato/api-timeout-express is the Express adapter for
api-timeout. It fails a request with 503 if the response
isn't sent within a deadline.
Install
pnpm add @rtorcato/api-timeout @rtorcato/api-timeout-express express
express is a peer dependency (^4.18 || ^5) — you bring your own version.
Usage
import { timeoutMiddleware } from '@rtorcato/api-timeout-express'
// Any request not answered within 5s gets a 503 error envelope.
app.use(timeoutMiddleware({ ms: 5000 }))
On timeout it responds 503 with the standard error envelope
{ error: 'ServiceUnavailableError', code: 'service_unavailable', message } from
api-errors. If the handler responds first, the timer is
cleared and nothing extra is sent.
warning
The middleware sends the 503 and stops. A slow handler that later tries to write
will hit Express's "headers already sent" — guard late writes with
res.headersSent in long-running handlers.
Related
- api-timeout — framework-agnostic core (
withTimeout, notes) - api-timeout-hono — the Hono adapter