The Request Object (req)

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.

Core Properties

PropertyDescriptionExample
req.paramsURL segments (:id)/user/:id
req.queryQuery strings (?q=)/search?q=node
req.bodyParsed body dataPOST payloads
req.headersHTTP HeadersAuthorization, Content-Type
req.ipRemote IP segment127.0.0.1
req.pathRequest URL path/users/list

Accessing URL Parameters

// Route: /api/users/:id
app.get('/api/users/:id', (req, res) => {
  console.log(req.params.id);
  res.send('User ID is ' + req.params.id);
});

Checking Headers

You can check if a request contains specific authorization or metadata.

app.get('/admin', (req, res) => {
  const adminKey = req.get('x-admin-key'); // Get header
  if (adminKey === 'SECRET') {
    res.send('Welcome Admin');
  } else {
    res.status(403).send('Forbidden');
  }
});
Important: req.body will be undefined unless you use a body-parsing middleware like express.json().