0
0
ExpressDebug / FixBeginner · 4 min read

How to Fix Timeout Error in Express: Simple Solutions

A timeout error in Express usually happens when a request takes too long to complete. Fix it by increasing the timeout limit using server.setTimeout() or by ensuring your route handlers respond promptly without blocking.
🔍

Why This Happens

Timeout errors occur when the server takes too long to respond to a client request. This can happen if your route handler has slow operations or never sends a response. Express has a default timeout, and if your code blocks or delays response, the client will get a timeout error.

javascript
import express from 'express';

const app = express();

app.get('/slow', (req, res) => {
  // Simulate a long task without response
  setTimeout(() => {
    // No response sent here
  }, 10000);
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
Error: timeout of 120000ms exceeded (or client sees a timeout error after waiting)
🔧

The Fix

To fix timeout errors, make sure your route handlers always send a response. If your tasks take longer, increase the server timeout using server.setTimeout(). Also, avoid blocking code by using asynchronous operations properly.

javascript
import express from 'express';

const app = express();
const server = app.listen(3000, () => console.log('Server running on port 3000'));

// Increase timeout to 10 minutes (600000 ms)
server.setTimeout(600000);

app.get('/slow', async (req, res) => {
  // Simulate a long async task
  await new Promise(resolve => setTimeout(resolve, 900000));
  res.send('Task completed after delay');
});
Output
Client receives: Task completed after delay
🛡️

Prevention

To avoid timeout errors in the future, always send a response in every route handler. Use asynchronous code to prevent blocking the event loop. Set reasonable timeout limits based on your app's needs. Use middleware like timeout from connect-timeout to handle long requests gracefully.

⚠️

Related Errors

Other errors similar to timeout include:

  • ECONNRESET: Connection was closed unexpectedly, often due to client disconnect.
  • Request aborted: Client cancels the request before server responds.
  • Payload too large: Request body exceeds server limits causing failure.

Fixes usually involve proper error handling and setting limits in Express.

Key Takeaways

Always send a response in every Express route handler to avoid timeouts.
Increase server timeout with server.setTimeout() for long-running requests.
Use asynchronous code to prevent blocking the server event loop.
Consider middleware like connect-timeout to manage request timeouts gracefully.
Monitor and handle related errors like ECONNRESET and aborted requests.