If you're learning Express.js, you've probably seen code like this:
app.get("/users", (req, res) => {
// ...
});
At first, req and res might look like just two parameters.
But they are actually two of the most important objects you'll work with in Express.js.
req
↓
Request from the client
res
↓
Response sent back to the client
Whenever a browser, frontend application, mobile app, or another server calls your Express API, Express gives you access to these two objects.
Understanding them properly is essential before moving into more advanced Express.js concepts such as middleware, authentication, validation, controllers, and database operations.
In this article, we'll learn:
- What
reqandresare - How the request-response cycle works
- Common
reqproperties req.paramsreq.queryreq.bodyreq.headersreq.methodreq.url- Common response methods
res.send()res.json()res.status()res.sendStatus()res.end()res.redirect()res.set()- How to combine request and response methods
- Common mistakes
Let's start with the request-response cycle.
What Is a Request?
A request is sent by a client to a server.
The client could be:
- A web browser
- React application
- Next.js application
- Mobile application
- Postman
- Another backend server
For example, a frontend application might request:
GET /api/users
The request can contain information such as:
HTTP method
URL
Route parameters
Query parameters
Headers
Request body
Express provides this information through the req object.
What Is a Response?
After receiving the request, the server processes it and sends a response back to the client.
For example:
{
"message": "Users fetched successfully"
}
Express provides the res object to help you create and send that response.
So the basic flow is:
Client
|
| HTTP Request
↓
Express Server
|
| Process request
↓
Express Route Handler
|
| HTTP Response
↓
Client
In Express:
app.get("/api/users", (req, res) => {
// req → information coming from client
// res → send information back to client
});
Understanding req and res
Consider this simple route:
app.get("/hello", (req, res) => {
console.log(req);
res.send("Hello World");
});
Here:
req
represents the incoming HTTP request.
And:
res
represents the outgoing HTTP response.
You don't create these objects yourself.
Express creates them and passes them to your route handler.
Request Object (req)
The request object contains information about the incoming request.
Some commonly used properties are:
req.params
req.query
req.body
req.headers
req.method
req.url
req.path
req.ip
Let's understand each one.
1. req.params
req.params is used to access route parameters.
Suppose we have:
app.get("/api/users/:id", (req, res) => {
console.log(req.params);
});
Now request:
GET /api/users/10
The result is:
{
id: "10"
}
We can access the ID using:
req.params.id
which gives:
"10"
Remember that route parameters are usually strings.
If you need a number:
const userId = Number(req.params.id);
Multiple Route Parameters
You can have multiple parameters.
app.get(
"/api/users/:userId/posts/:postId",
(req, res) => {
console.log(req.params);
}
);
Request:
GET /api/users/10/posts/50
Then:
req.params
contains:
{
"userId": "10",
"postId": "50"
}
You can access them individually:
req.params.userId
and:
req.params.postId
2. req.query
req.query is used to access query parameters.
Consider:
GET /api/users?name=John&age=25
The query parameters are:
name=John
age=25
Express makes them available through:
req.query
Example:
app.get("/api/users", (req, res) => {
console.log(req.query);
res.json(req.query);
});
Request:
GET /api/users?name=John&age=25
Response:
{
"name": "John",
"age": "25"
}
Again, notice that query parameter values are generally strings.
Route Parameters vs Query Parameters
This is one of the most important differences to understand.
Route parameter
/api/users/10
Used when identifying a specific resource.
req.params.id
Query parameter
/api/users?page=2&limit=10
Usually used for filtering, searching, sorting, pagination, etc.
req.query.page
req.query.limit
For example:
GET /api/products?category=mobile&sort=price
You could access:
req.query.category
req.query.sort
A simple rule:
/:id
↓
req.params
?key=value
↓
req.query
3. req.body
req.body contains data sent in the request body.
It's commonly used with:
POST
PUT
PATCH
For example:
POST /api/users
with:
{
"name": "John",
"email": "john@example.com"
}
In Express:
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
res.json(req.body);
});
The result is:
{
name: "John",
email: "john@example.com"
}
Why Do We Need express.json()?
This is very important.
If your client sends JSON:
{
"name": "John"
}
Express needs middleware to parse that JSON request body.
Add:
app.use(express.json());
For example:
const express = require("express");
const app = express();
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
res.json({
message: "User received",
data: req.body
});
});
Without the appropriate body-parsing middleware, req.body may be undefined for JSON requests.
4. req.headers
HTTP requests contain headers.
Headers provide additional information about the request.
For example:
Content-Type: application/json
Authorization: Bearer token
Accept: application/json
Express provides them through:
req.headers
Example:
app.get("/api/users", (req, res) => {
console.log(req.headers);
res.json({
message: "Headers received"
});
});
You can access a specific header:
req.headers.authorization
or:
req.headers["authorization"]
For example:
Authorization: Bearer abc123
Then:
console.log(req.headers.authorization);
could produce:
Bearer abc123
req.get()
Express also provides:
req.get()
to retrieve a request header.
For example:
const contentType = req.get("Content-Type");
console.log(contentType);
You can also get:
const authorization = req.get("Authorization");
This can be convenient when you only need one specific header.
5. req.method
req.method tells you which HTTP method was used.
For example:
app.use((req, res, next) => {
console.log(req.method);
next();
});
If the client sends:
GET /api/users
you get:
GET
For:
POST /api/users
you get:
POST
Similarly:
PUT
PATCH
DELETE
will return their respective method names.
6. req.url
req.url gives you the request URL.
Example:
app.get("/api/users", (req, res) => {
console.log(req.url);
res.send("Success");
});
Request:
GET /api/users?name=John
The URL can include the query string.
For example:
/api/users?name=John
7. req.path
req.path gives you the URL path without the query string.
For:
/api/users?name=John
you get:
/api/users
Example:
app.get("/api/users", (req, res) => {
console.log(req.path);
res.send("Success");
});
This can be useful when you need only the path.
8. req.ip
Express also provides the client's IP address through:
req.ip
Example:
app.get("/", (req, res) => {
console.log(req.ip);
res.send("Hello");
});
This can be useful for things like:
- Logging
- Monitoring
- Rate limiting
- Security-related checks
However, when your application is behind a proxy or load balancer, you need to configure Express's proxy settings correctly before relying on client IP information.
Request Object Summary
Here are some commonly used request properties:
req.params
↓
Route parameters
req.query
↓
Query parameters
req.body
↓
Request body
req.headers
↓
Request headers
req.method
↓
HTTP method
req.url
↓
Request URL
req.path
↓
URL path
req.ip
↓
Client IP
Now let's look at the response object.
Response Object (res)
The res object is used to send information back to the client.
Some commonly used methods are:
res.send()
res.json()
res.status()
res.sendStatus()
res.end()
res.redirect()
res.set()
Let's understand them one by one.
1. res.send()
res.send() sends a response to the client.
Example:
app.get("/hello", (req, res) => {
res.send("Hello World");
});
Response:
Hello World
It's commonly used for:
- Strings
- HTML
- Buffers
- Simple responses
For example:
res.send("User created successfully");
Sending HTML with res.send()
You can also send HTML:
app.get("/welcome", (req, res) => {
res.send(`
<h1>Welcome</h1>
<p>Welcome to Express.js</p>
`);
});
The browser can render the HTML response.
2. res.json()
res.json() sends a JSON response.
This is probably one of the most frequently used methods when building REST APIs.
Example:
app.get("/api/users", (req, res) => {
res.json({
message: "Users fetched successfully"
});
});
Response:
{
"message": "Users fetched successfully"
}
You can send arrays too:
app.get("/api/users", (req, res) => {
res.json([
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Jane"
}
]);
});
res.send() vs res.json()
This is a common beginner question.
res.send()
res.send("Hello World");
Good for simple responses and various response types.
res.json()
res.json({
message: "Hello World"
});
Specifically intended for JSON responses.
For REST APIs, you'll generally use:
res.json()
quite often.
3. res.status()
res.status() sets the HTTP status code.
For example:
res.status(200);
But setting the status alone doesn't send the response.
You normally chain another method:
res.status(200).json({
message: "Success"
});
For a bad request:
res.status(400).json({
message: "Invalid request"
});
For not found:
res.status(404).json({
message: "User not found"
});
For server errors:
res.status(500).json({
message: "Internal server error"
});
Common Status Codes
Some status codes you'll frequently use in Express APIs are:
200
↓
OK
201
↓
Created
204
↓
No Content
400
↓
Bad Request
401
↓
Unauthorized
403
↓
Forbidden
404
↓
Not Found
409
↓
Conflict
500
↓
Internal Server Error
For example, after successfully creating a user:
res.status(201).json({
message: "User created successfully"
});
4. res.sendStatus()
res.sendStatus() sets the status code and sends a standard response body.
For example:
res.sendStatus(404);
This sends:
404 Not Found
You can use:
res.sendStatus(200);
or:
res.sendStatus(401);
However, for most REST APIs, you'll often want to return a custom JSON response:
res.status(404).json({
message: "User not found"
});
This gives the frontend more useful information.
res.status() vs res.sendStatus()
Compare:
res.status(404).json({
message: "User not found"
});
with:
res.sendStatus(404);
The first lets you control the response body.
The second sends the status with Express's standard text response.
For APIs, the first approach is usually more useful.
5. res.end()
res.end() ends the response.
Example:
app.get("/test", (req, res) => {
res.end();
});
This sends an empty response.
You can also provide data:
res.end("Done");
However, for normal JSON APIs, you'll usually prefer:
res.json()
or:
res.send()
rather than manually ending the response.
6. res.redirect()
res.redirect() tells the client to navigate to another URL.
For example:
app.get("/old-page", (req, res) => {
res.redirect("/new-page");
});
If a browser requests:
/old-page
Express responds with a redirect to:
/new-page
You can also redirect to an external URL:
app.get("/google", (req, res) => {
res.redirect("https://www.google.com");
});
Redirects are more common in traditional web applications than in JSON APIs.
7. res.set()
res.set() is used to set response headers.
For example:
app.get("/api/users", (req, res) => {
res.set("X-App-Version", "1.0");
res.json({
message: "Users fetched successfully"
});
});
You can also set multiple headers:
res.set({
"X-App-Version": "1.0",
"X-API-Version": "v1"
});
Headers can be useful for metadata and application-specific behavior.
8. res.type()
Express also provides:
res.type()
to set the Content-Type response header.
For example:
res.type("text");
res.send("Hello");
Or:
res.type("html");
res.send("<h1>Hello</h1>");
For JSON responses, res.json() is generally simpler.
Combining Response Methods
One of the most useful Express patterns is method chaining.
For example:
res
.status(201)
.json({
message: "User created successfully"
});
Instead of:
res.status(201);
res.json({
message: "User created successfully"
});
Both can work, but chaining is concise and common in Express code.
Request + Response Together
Let's combine everything we've learned.
Suppose we create:
GET /api/users/:id
The route can use:
app.get("/api/users/:id", (req, res) => {
const userId = Number(req.params.id);
console.log("User ID:", userId);
res.status(200).json({
message: "User fetched successfully",
userId
});
});
Request:
GET /api/users/10
Response:
{
"message": "User fetched successfully",
"userId": 10
}
Here:
req.params
↓
Get information from request
res.status()
↓
Set HTTP status
res.json()
↓
Send JSON response
Combining Params, Query, and Body
Imagine a product API:
PATCH /api/products/10?notify=true
Body:
{
"price": 999
}
We can access all three:
app.patch("/api/products/:id", (req, res) => {
const productId = req.params.id;
const shouldNotify = req.query.notify;
const updateData = req.body;
console.log(productId);
console.log(shouldNotify);
console.log(updateData);
res.json({
productId,
shouldNotify,
updateData
});
});
The values are:
req.params.id
↓
"10"
req.query.notify
↓
"true"
req.body
↓
{
price: 999
}
This example shows how different parts of an HTTP request can work together.
A Practical User API
Let's build a small example.
const express = require("express");
const app = express();
app.use(express.json());
const users = [
{
id: 1,
name: "John",
email: "john@example.com"
},
{
id: 2,
name: "Jane",
email: "jane@example.com"
}
];
app.get("/api/users/:id", (req, res) => {
const userId = Number(req.params.id);
const user = users.find(
(user) => user.id === userId
);
if (!user) {
return res.status(404).json({
message: "User not found"
});
}
res.status(200).json({
user
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Request:
GET /api/users/1
Express receives the request.
Then:
req.params.id
gives:
"1"
We convert it:
Number(req.params.id)
Then search the data.
Finally:
res.status(200).json({
user
});
sends the response.
Understanding the Complete Flow
The complete process looks like this:
Client
|
|
HTTP Request
|
↓
Express Route Handler
|
|
┌────────┴────────┐
↓ ↓
req res
| |
| |
Read request Create response
| |
┌─────┼─────┐ ┌────┼─────┐
↓ ↓ ↓ ↓ ↓ ↓
params query body status json send
This is the basic foundation of Express API development.
req Is Read, res Is Write
A simple mental model can make this much easier.
Think of:
req
as:
"What did the client send me?"
And:
res
as:
"What do I want to send back to the client?"
For example:
app.post("/api/users", (req, res) => {
const userData = req.body;
// Process userData...
res.status(201).json({
message: "User created"
});
});
Here:
req.body
↓
What client sent
res.status().json()
↓
What server sends back
Request and Response in CRUD APIs
Now let's connect this with the CRUD APIs we've already discussed.
GET
app.get("/api/users/:id", (req, res) => {
const id = req.params.id;
res.json({
id
});
});
POST
app.post("/api/users", (req, res) => {
const user = req.body;
res.status(201).json({
user
});
});
PUT
app.put("/api/users/:id", (req, res) => {
const id = req.params.id;
const user = req.body;
res.json({
id,
user
});
});
PATCH
app.patch("/api/users/:id", (req, res) => {
const id = req.params.id;
const updates = req.body;
res.json({
id,
updates
});
});
DELETE
app.delete("/api/users/:id", (req, res) => {
const id = req.params.id;
res.json({
message: `User ${id} deleted`
});
});
Notice how req and res are used in almost every API route.
A Common Mistake: Sending Multiple Responses
One important Express rule is:
A route should send only one response.
Avoid:
app.get("/api/users/:id", (req, res) => {
const user = null;
if (!user) {
res.status(404).json({
message: "User not found"
});
}
res.json({
user
});
});
The problem is that after sending the 404 response, the code continues and tries to send another response.
Instead:
if (!user) {
return res.status(404).json({
message: "User not found"
});
}
The return prevents the second response.
Another Common Mistake: Forgetting express.json()
If you have:
app.post("/api/users", (req, res) => {
console.log(req.body);
});
but forgot:
app.use(express.json());
then JSON request bodies may not be parsed as expected.
Always configure the middleware before the routes:
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
});
Another Common Mistake: Confusing params and query
These are different:
/api/users/10
and:
/api/users?id=10
For:
/api/users/10
use:
req.params.id
For:
/api/users?id=10
use:
req.query.id
Don't mix them up.
Another Common Mistake: Forgetting That Request Values Are Strings
Consider:
GET /api/users/10
Then:
req.params.id
is generally:
"10"
not:
10
So this can cause problems:
if (req.params.id === 10) {
// Won't match
}
Instead:
const id = Number(req.params.id);
if (id === 10) {
// Works
}
The same idea applies to query parameters.
Request Headers vs Body
Another common confusion is between headers and body.
Consider:
POST /api/users
Content-Type: application/json
Authorization: Bearer token
Body:
{
"name": "John",
"email": "john@example.com"
}
Then:
req.headers
contains things like:
Content-Type
Authorization
while:
req.body
contains:
{
"name": "John",
"email": "john@example.com"
}
A simple distinction:
Headers
↓
Information about the request
Body
↓
Data being sent
Practical Example: Login API
Here's a common real-world example.
app.post("/api/login", (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({
message: "Email and password are required"
});
}
// Authentication logic...
res.status(200).json({
message: "Login successful"
});
});
Here:
req.body
contains:
{
"email": "john@example.com",
"password": "password"
}
and:
res.status(200).json()
sends the result back to the client.
Practical Example: Search API
Suppose we have:
GET /api/products?search=laptop&page=2
We can write:
app.get("/api/products", (req, res) => {
const { search, page } = req.query;
res.json({
search,
page
});
});
Response:
{
"search": "laptop",
"page": "2"
}
Here query parameters are useful for filtering and pagination.
Practical Example: Authorization Header
Suppose the frontend sends:
Authorization: Bearer abc123
We can read it:
app.get("/api/profile", (req, res) => {
const authorization = req.get("Authorization");
console.log(authorization);
res.json({
message: "Profile request received"
});
});
In a real application, authentication middleware would usually handle token verification before the request reaches the controller.
Useful req Properties to Remember
As a beginner, don't try to memorize every property.
Focus on these first:
req.params
req.query
req.body
req.headers
req.method
req.url
These will cover a large portion of your day-to-day Express.js API development.
Useful res Methods to Remember
Start with these:
res.status()
res.json()
res.send()
res.sendStatus()
res.redirect()
The most common combination in REST APIs is:
res.status(200).json({
message: "Success"
});
or:
res.status(201).json({
message: "Created successfully"
});
Quick Cheat Sheet
REQUEST
────────────────────────────
req.params
→ Route parameters
req.query
→ Query parameters
req.body
→ Request body
req.headers
→ Request headers
req.method
→ HTTP method
req.url
→ Request URL
req.path
→ URL path
req.ip
→ Client IP
RESPONSE
────────────────────────────
res.send()
→ Send response
res.json()
→ Send JSON
res.status()
→ Set status code
res.sendStatus()
→ Send status + default body
res.end()
→ End response
res.redirect()
→ Redirect client
res.set()
→ Set response headers
Final Thoughts
The req and res objects are at the heart of Express.js API development.
Whenever a client calls your API:
Client
↓
HTTP Request
↓
Express
↓
req
↓
Your API logic
↓
res
↓
HTTP Response
↓
Client
The req object helps you understand what the client sent:
req.params
req.query
req.body
req.headers
The res object helps you decide what the server sends back:
res.status()
res.json()
res.send()
Once these concepts become familiar, Express.js routes become much easier to understand.
For example:
app.patch("/api/users/:id", (req, res) => {
const userId = req.params.id;
const updates = req.body;
// Update user...
res.status(200).json({
message: "User updated successfully",
userId,
updates
});
});
Even though this looks simple, it demonstrates the core Express.js pattern:
req
↓
Read client information
↓
Process the request
↓
res
↓
Send the result
This request-response pattern is something you'll use repeatedly as you build Express.js applications and REST APIs.