Extract HTTP request headers from NodeJS connect requests

This tutorial will guide you through different methods to extract HTTP request headers in a Node.js application using the Connect middleware or the Express framework.

In Node.js, when working with Connect or Express, you often need to access HTTP request headers for various purposes such as authentication, logging, or processing requests based on specific header values.

Using req.get(headerName) in Express 4.x

If you are using Express 4.x, you can use the req.get(headerName) method to retrieve the value of a specific HTTP header. This method is part of the Express 4.x API. Here’s an example:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  // Get the 'user-agent' header value
  const userAgent = req.get('user-agent');
  console.log('User-Agent:', userAgent);

  // Continue processing the request
  next();
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Viewing All Headers in JSON Format

To see a list of all HTTP request headers in JSON format, you can use the following code:

app.use((req, res, next) => {
  // Log all headers in JSON format
  console.log(JSON.stringify(req.headers));

  // Continue processing the request
  next();
});

The output will be a JSON object containing all the headers. For example:

{
  "host": "localhost:8081",
  "connection": "keep-alive",
  "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
  "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
  "accept-encoding": "gzip, deflate, sdch",
  "accept-language": "en-US,en;q=0.8,et;q=0.6"
}

Accessing Specific Headers

You can access specific headers directly using the req.headers object. For example:

app.use((req, res, next) => {
  // Get the 'host' header value
  const host = req.headers['host'];
  console.log('Host:', host);

  // Get the 'user-agent' header value
  const userAgent = req.headers['user-agent'];
  console.log('User-Agent:', userAgent);

  // Continue processing the request
  next();
});

Logging Headers

Logging headers is a common use case. You can use a logger to output headers in a structured format. Here’s an example using a logger:

const logger = require('your-logger-library');

app.use((req, res, next) => {
  // Log headers using a logger
  logger.info({ headers: req.headers });

  // Continue processing the request
  next();
});

The output will be logged in the format:

{
  "headers": {
    "authorization": "Basic bmluYWQ6bmluYWQ=",
    "content-type": "application/json",
    "user-agent": "PostmanRuntime/7.26.8",
    "accept": "*/*",
    "postman-token": "36e0d84a-55be-4661-bb1e-1f04d9499574",
    "host": "localhost:9012",
    "accept-encoding": "gzip, deflate, br",
    "connection": "keep-alive",
    "content-length": "198"
  }
}

Using Express for Bearer Token

If you are working with bearer tokens in the authorization header, you can extract the token as follows:

app.use((req, res, next) => {
  // Get the Bearer token from the 'authorization' header
  const bearerToken = req.headers['authorization'].split(' ')[1];
  console.log('Bearer Token:', bearerToken);

  // Continue processing the request
  next();
});

This example assumes that the authorization header is in the format ‘Bearer tokenString’.

By following these examples, you can easily extract and work with HTTP request headers in your Node.js Connect or Express application.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top