Request & Response Objects in Express.js (req & res)
In Express.js, the req (request) and res (response) objects are the foundation of handling HTTP communication.
Every time a client sends a request to the server, Express provides these two objects to process the request and send back a response.
Understanding how req and res work is essential for building APIs, handling user input, and sending data back to the client.
req object contains incoming request data, while the res object is used to send responses back to the client.
What is the Request Object (req)?
The req object represents the HTTP request sent by the client.
It contains all the details about the request such as parameters, query strings, headers, and body data.
Common Properties of req
req.params– Route parameters (e.g.,/users/:id)req.query– Query string data (e.g.,?name=Rahul)req.body– Data sent in the request body (POST/PUT)req.headers– Request headersreq.method– HTTP method (GET, POST, etc.)req.url– Requested URL
What is the Response Object (res)?
The res object is used to send a response back to the client.
It allows you to return data, status codes, and headers.
Common Methods of res
res.send()– Send a text or HTML responseres.json()– Send JSON datares.status()– Set HTTP status coderes.redirect()– Redirect to another URLres.end()– End the response
Basic Example
In this example:
- The route handles a POST request to
/data reqcontains incoming request datares.json()sends a JSON response to the client
{ "message": "Success" }
Working with req.params
Example:
URL: /user/101 → Response: 101
Working with req.query
URL: /search?name=Rahul → Response: Rahul
Working with req.body
To access request body data, you need middleware like express.json().
Setting Status Codes
Sending Different Responses
Send Text
Send JSON
Send HTML
Real-World Use Cases
- Building REST APIs
- Handling form submissions
- Processing user input
- Returning JSON responses to frontend apps
Best Practices
- Always validate request data
- Use proper status codes
- Handle errors gracefully
- Avoid sending multiple responses
Common Mistakes
- Not using
express.json()for body parsing - Sending response multiple times
- Ignoring validation of input data
Conclusion
The req and res objects are the backbone of any Express.js application.
They allow you to receive data from the client and send responses effectively.
Mastering these objects is essential for building APIs, handling user interactions, and creating scalable backend applications.
req handles incoming data, and res sends responses back to the client in Express.js.

