Working with Headers

Read request headers with req.get and set response headers with res.set.

Syntaxres.set('X-Custom', 'value')

HTTP headers carry metadata such as content type, authorization and caching hints.

  • Read one with req.get('Header-Name') or from req.headers.
  • Set one with res.set('Header-Name', value).
  • res.type() is a shortcut for the Content-Type header.

Example

Example · javascript
app.get('/download', (req, res) => {
  const auth = req.get('Authorization');
  res.set('X-Powered-By', 'SoundsCode');
  res.set('Content-Type', 'text/plain');
  res.send('Auth header was: ' + auth);
});

When to use it

  • A caching strategy sets Cache-Control and ETag headers on static API responses so clients skip the round-trip when data has not changed.
  • A developer reads the Authorization header from incoming requests to extract and verify the Bearer token.
  • A custom response header X-Api-Version is set on every response so API consumers can see which version is serving their requests.

More examples

Setting custom response headers

Uses res.set() to add a custom API version header and a cache policy before sending the JSON response.

Example · js
app.get('/api/data', (req, res) => {
  res.set('X-Api-Version', '1.0');
  res.set('Cache-Control', 'public, max-age=300');
  res.json({ data: [] });
});

Reading request headers

Reads the Authorization header directly from req.headers and strips the 'Bearer ' prefix.

Example · js
app.get('/auth', (req, res) => {
  const auth = req.headers['authorization'] || '';
  const token = auth.replace('Bearer ', '');
  if (!token) return res.status(401).json({ error: 'Missing token' });
  res.json({ tokenLength: token.length });
});

Setting multiple headers with res.set

Passes an object to res.set() to apply multiple security and tracing headers to every response in one call.

Example · js
app.use((req, res, next) => {
  res.set({
    'X-Content-Type-Options': 'nosniff',
    'X-Frame-Options': 'DENY',
    'X-Request-Id': req.id || '-',
  });
  next();
});

Discussion

  • Be the first to comment on this lesson.