Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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.

PropertyContents
req.methodHTTP method: GET, POST and others
req.pathThe path without the query string
req.urlThe path together with the query string
req.paramsRoute parameters
req.queryThe parsed query string
req.bodyThe request body, if parsing is enabled
req.headersAll headers, names in lower case
req.ipThe client IP address
req.hostnameThe 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}`);
});

Thanks for reading!

Donate to the site — we work hard for you.