Introduction

Now that we understand different ways to use middleware, let’s learn how to access request headers. This knowledge will be essential for our authentication middleware in the next section.

What are headers?

Headers are pieces of information sent with every HTTP request and response. They contain metadata about the request, like:

  • What type of data is being sent
  • What type of response the client expects
  • Authentication information
  • Browser information

Where to find headers in browser devtools

  1. Go to the Network tab in devtools
  2. Make a request to your API
  3. Click on the request in the Network tab
  4. Look at the Headers section - you’ll see:
    • Request Headers - Headers sent by the browser
    • Response Headers - Headers sent by the server

Common request headers you’ll see

  • User-Agent - Browser and operating system info
  • Accept - What type of response the client wants (JSON, HTML, etc.)
  • Content-Type - Type of data being sent
  • Authorization - Authentication tokens
  • Origin - Where the request came from (important for CORS)

How to access headers in your code

You can access all request headers using req.headers. This is an object containing all the headers sent by the client.

app.get("/example", (req, res) => {
  // Access headers
  const userAgent = req.headers["user-agent"];
  const authorization = req.headers.authorization;
  const contentType = req.headers["content-type"];

  console.log("User Agent:", userAgent);
  console.log("Authorization:", authorization);
  console.log("contentType:", contentType);
});

Important: Headers are always strings, and Express converts all header names to lowercase in req.headers. So use req.headers.authorization (lowercase), not req.headers.Authorization.



Repo link

Tags: