Open In App

Express JS Response Timeout

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In web development, it is very crucial to get timely responses to client requests. However, in some cases, servers might encounter prolonged processing times or server is not responding for a long duration. This type of timeout is called response timeout. Express JS offers a mechanism to handle response timeouts, which prevents indefinitely pending requests and improving server reliability.

Steps to create Express Application:

Step 1: Create a folder for your project via following command.

mkdir server

Step 2: Initialize server through following command.

npm init -y

Step 3: Install required module.

npm i express

Approach

A basic example of a timeout means that you created a route but did not pass any data to the client, like you have not set up the res.send(). In that case, the client is not receiving any data, so for the client, it would be like the server is not sending it will load the browser response is not received.

In this particular approach, we are not going to send data to the client side; we have implemented only an endpoint to get requests, and we have implemented a middleware that will automatically send status code 408 when the request has timed out.

Syntax:

app.get("*",(req,res)=>{})

Example: Implementation of above approach.

Javascript




// Index.js
const express = require('express');
const app = express();
const port = 3000;
 
app.use((req, res, next) => {
    res.setTimeout(2000, ()=>{
        console.log('Request has timed out.');
            res.sendStatus(408);
        });
    next();
});
 
app.get('/', (req, res) => {
     
});
 
app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});


Output:

Screenshot-2023-11-20-005624


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads