Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
timeout
✓ import timeout from 'connect-timeout'
✗ import { timeout } from 'connect-timeout'
The connect-timeout library exports its main middleware function as a default export, even when used with ES Modules through transpilation or bundlers. CommonJS `require` is `const timeout = require('connect-timeout')`.
timeout factory function
✓ const timeout = require('connect-timeout')
This package is primarily designed for CommonJS environments common in older Node.js/Express applications. While it can be used with ESM, this `require` pattern is the most common and direct usage.
Middleware usage
✓ app.use(timeout('5s'))
The function call `timeout('5s')` returns the actual middleware function to be used with `app.use()` or `router.use()`.
This quickstart demonstrates how to apply `connect-timeout` to an Express route, implement a `haltOnTimedout` helper middleware to prevent further processing, and catch timeout errors. It simulates a slow asynchronous task to trigger the timeout and shows how to check `req.timedout` before responding.
import express from 'express';
import timeout from 'connect-timeout';
const app = express();
// A function to simulate a long-running async operation
function simulateAsyncTask(durationMs) {
return new Promise(resolve => {
setTimeout(() => {
console.log(`Async task finished after ${durationMs}ms.`);
resolve();
}, durationMs);
});
}
// Helper middleware to check if request has timed out and halt further processing
function haltOnTimedout(req, res, next) {
if (!req.timedout) {
next();
} else {
console.warn(`Request to ${req.originalUrl} timed out.`);
// Optionally send a custom response here, or let the error handler catch it
if (!res.headersSent) {
res.status(503).send('Service Unavailable: Request timed out.');
}
}
}
// Route with a 3-second timeout
app.get('/slow-task', timeout('3s'), haltOnTimedout, async (req, res, next) => {
try {
const randomDelay = Math.random() * 5000 + 1000; // 1 to 6 seconds
console.log(`Starting slow task for ${randomDelay}ms.`);
await simulateAsyncTask(randomDelay);
// Check if the request has already timed out before sending a response
if (req.timedout) {
console.log('Request timed out before sending success response.');
return; // Do not send response if already timed out
}
res.status(200).send('Task completed successfully!');
} catch (error) {
next(error);
}
});
// Error handling middleware for timeout errors
app.use((err, req, res, next) => {
if (err.timeout) {
console.error('Request timeout error caught by error handler:', err.message);
// The `haltOnTimedout` middleware above already handles the response,
// but this ensures any other timeout scenarios are caught.
if (!res.headersSent) {
res.status(503).send('Service Unavailable: Caught by error handler.');
}
} else {
console.error('General error:', err.message);
if (!res.headersSent) {
res.status(500).send('Internal Server Error.');
}
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
console.log('Try accessing http://localhost:3000/slow-task');
});
Errors
Common errors & fixes
Error: Can't set headers after they are sent to the client.
The timeout middleware sent a 503 response, but the original request handler or a subsequent middleware also tried to send a response.
fixEnsure that all middleware and route handlers check `req.timedout` before attempting to send a response. Implement a `haltOnTimedout` middleware immediately after any potentially slow middleware.
TypeError: app.use() requires a middleware function but got a undefined
The `timeout` function was called without an argument or with an invalid time string, leading it to return `undefined` instead of a middleware function.
fixProvide a valid time string (e.g., `'5s'`, `'1000ms'`) or a number (in milliseconds) as the first argument to `timeout()`: `app.use(timeout('5s'))`. ConnectTimeoutError: Service Unavailable
This is the error object passed to `next()` when a request times out and the `respond` option is `true` (which is the default). It signifies that the `connect-timeout` middleware has detected a timeout.
fixImplement an error-handling middleware (`app.use((err, req, res, next) => { ... })`) that specifically checks for `err.timeout === true` and `err.status === 503` to provide a custom response or log the event. Audit
Dependencies
msrequiredUsed for parsing time strings (e.g., '5s', '2h') into milliseconds.
http-errorsrequiredUsed for creating HTTP-specific error objects, specifically for the 503 timeout error.
on-headersrequiredUtility to execute a callback when response headers are about to be sent. Ensures proper cleanup and handling.