The request object
The request object req is the first argument of every handler. Express gathers into it everything the client sent: the method, address, parameters, headers and body. You do not create it — it arrives ready.
Main properties
// src/app.js
app.get('/debug', (req, res) => {
console.log(req.method); // 'GET'
console.log(req.path); // '/debug'
console.log(req.url); // '/debug?x=1'
console.log(req.query); // { x: '1' }
res.send('Check the terminal');
});Open http://localhost:3000/debug?x=1: the browser shows "Check the terminal", and four lines appear in the server terminal.
| Property | Contents |
|---|---|
req.method | HTTP method: GET, POST and others |
req.path | The path without the query string |
req.url | The path together with the query string |
req.params | Route parameters |
req.query | The parsed query string |
req.body | The request body, if parsing is enabled |
req.headers | All headers, names in lower case |
req.ip | The client IP address |
req.hostname | The host name from the Host header |
Headers
Headers are service lines of a request: the browser language, the data type, a login token. The easiest way to read them is req.get(), which ignores the case of the name:
// src/app.js
app.get('/hello', (req, res) => {
const language = req.get('Accept-Language') ?? 'not set';
res.send(`Browser language: ${language}`);
});The page shows a line like "Browser language: en-US,en;q=0.9".
The request body
Form data or JSON arrives in the request body. Express does not read it by itself: until parsing is enabled, req.body is undefined. Parsing is enabled with built-in middleware — there is a separate lesson about it. After that the handler receives a ready object:
// src/app.js
app.post('/posts', (req, res) => {
const title = req.body?.title;
res.send(`Received title: ${title}`);
});The ?. operator protects against an error if no body arrived at all.
Your own data on the request
The req object lives while one request is being handled. Middleware often writes its own fields onto it, for example the logged-in user req.user, and handlers further down the chain read them. This is how the authentication lesson will work.
Common mistake
In Express 5 the req.query property is read-only: a line like req.query.page = 1 does not change it. If you need a default value, store it in a variable:
// src/app.js
app.get('/posts', (req, res) => {
const page = Number(req.query.page ?? 1);
res.send(`Page ${page}`);
});