tezvyn:

Express Request and Response Objects (req, res)

AI-drafted, machine-checkedSource: expressjs.combeginner
Express Request and Response Objects (req, res)

Think of Express's `req` and `res` as an incoming letter and your reply. `req` contains the client's request details, like headers and data, while `res` is your toolkit for sending a response. They are the core of every route handler.

WHY IT EXISTS: Web servers need a standardized way to handle incoming HTTP requests and formulate outgoing HTTP responses. Express abstracts the raw, complex Node.js HTTP objects into simpler, more powerful req and res objects, making web development faster and less error-prone.

THE MENTAL MODEL: Think of a restaurant order. The req object is the waiter's notepad containing the customer's entire order: what table they're at (req.ip), what they asked for by name (req.params), any special requests (req.query), and any dietary info they provided (req.body). The res object is the kitchen's toolkit for preparing and sending out the food. You use it to set the status (res.status(200) for "Order up!") and send the final dish (res.json({ food: 'burger' })).

HOW IT WORKS: In every Express route handler, like app.get('/', (req, res) => { ... }), Express automatically passes these two objects. The req object is enhanced with useful properties for parsing request data. For example, req.params holds route parameters (like :id), req.query holds URL query strings (like ?sort=asc), and req.body holds the payload of POST requests (after using middleware like express.json()). The res object provides high-level methods to craft the response. Methods like res.send(), res.json(), res.redirect(), and res.status() chain together to build and dispatch the HTTP response to the client.

WHEN TO USE IT: You use req and res in every single route and middleware function you write in Express. It's the fundamental contract for handling web traffic. Use req to get user input, check authentication headers, or read URL parameters. Use res to send back HTML pages, JSON API data, redirect users, or set cookies.

WHEN NOT TO USE IT: The most common footgun is trying to send more than one response for a single request. Once you call a response-ending method like res.send(), res.json(), or res.end(), the HTTP connection is closed on the server side. Attempting to send another response will result in a 'Cannot set headers after they are sent to the client' error.

ONE CANONICAL EXAMPLE: A simple API endpoint to fetch a user by ID. app.get('/users/:id', (req, res) => { const userId = req.params.id; const user = findUserById(userId); if (user) { res.status(200).json(user); } else { res.status(404).send('User not found'); } }); This shows reading from req.params and using res.status() with either res.json() or res.send() to conditionally respond.

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.