Skip to content

Beginner · How the web and backends work · topic 5 of 54 · 20 min

HTTP headers and cookies

Explanation

Headers are extra details sent with every request and response, written as name: value pairs. They say what kind of data the body holds, who is logged in, how long to cache a page and much more. Header names do not care about capital letters, so Content-Type and content-type are the same header.

What headers are

A header is one line of extra information in an HTTP message, like Content-Type: application/json. The part before the colon is the name; the part after is the value. Both requests and responses have headers.

Think of it like this: A courier parcel has the item inside and a label outside. The label says who it is for, who sent it, "Fragile" and "Cash on delivery". Headers are that label. The body is the item inside the box.

Headers you will see every day

HeaderSent byWhat it says
Content-TypeBothThe type of the body, like application/json or text/html
AcceptClientWhich types the client can read, like application/json
AuthorizationClientProof of who you are, like Bearer eyJhbGci...
Cache-ControlServerHow long a copy can be kept, like max-age=3600
Set-CookieServerAsks the browser to save a small value, like a session id
CookieClientSends saved cookies back, like theme=dark; lang=hi
User-AgentClientWhich browser or app sent the request
output
GET /api/profile HTTP/1.1
Host: api.example.in
Accept: application/json
Authorization: Bearer abc123
Cookie: theme=dark; lang=hi
User-Agent: Mozilla/5.0 (Linux; Android 14)
A request with five headers and no body.

Names are case-insensitive

Case-insensitive means capital and small letters count as the same. Content-Type, content-type and CONTENT-TYPE are one header. Node.js gives you all request header names in small letters, so you read req.headers["content-type"].

javascript
const headers = { 'Content-Type': 'application/json', 'X-Request-Id': 'a1b2' };

function getHeader(headers, name) {
  const wanted = name.toLowerCase();
  for (const key of Object.keys(headers)) {
    if (key.toLowerCase() === wanted) return headers[key];
  }
  return null;
}

console.log(getHeader(headers, 'content-type')); // application/json
console.log(getHeader(headers, 'accept'));       // null
Compare names in small letters so any spelling of the name works.

Cookies

A cookie is a small named value that the browser saves for a website. The server sends Set-Cookie: session=xyz in a response. After that, the browser adds Cookie: session=xyz to every request to that site. This is how a website remembers that you are logged in.

javascript
const cookieHeader = 'theme=dark; lang=hi; cart=3';
const pairs = cookieHeader.split('; ');
console.log(pairs); // [ 'theme=dark', 'lang=hi', 'cart=3' ]
console.log(pairs[1].split('=')); // [ 'lang', 'hi' ]
A Cookie header is pairs joined by "; ". Split it to read each one.
Tip: A Content-Type value can have extra parts, like application/json; charset=utf-8. Check it with startsWith("application/json") instead of ===.
Careful: Never log or print the Authorization header or session cookies. Anyone who reads the logs could use them to log in as your users. Also never trust User-Agent for security: any client can send any value.

Watch the lesson

HTTP headers and cookies · 1/6

Headers = label Body = item

Headers are like the label on a courier parcel. The body is the item inside; the headers describe it.

Prefer a video by a teacher? Find free videos on “http headers and cookies explained for beginners” on YouTube ↗

In real life: Switching an app to Hindi

A news site lets you pick Hindi. The server answers with Set-Cookie: lang=hi. From then on, every request from your browser carries Cookie: lang=hi, and the backend reads it to send Hindi headlines. Your browser also sends Accept-Language: hi-IN, en, which a backend can use the very first time, before any cookie is set.

javascript
function pickLanguage(request) {
  const cookie = request.headers.cookie || '';
  if (cookie.includes('lang=hi')) return 'hi';
  return 'en';
}
console.log(pickLanguage({ headers: { cookie: 'theme=dark; lang=hi' } })); // hi
console.log(pickLanguage({ headers: {} }));                                 // en
The backend picks the page language from a cookie header.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function getHeader(headers, name) that finds a header in the headers object without caring about capital letters, and returns its value, or null when it is not there.

Task 2 · Code · Javascript

Write a function parseCookies(header) that turns a Cookie header like "theme=dark; lang=hi" into an object { theme: "dark", lang: "hi" }. An empty string gives {}. Trim spaces around names and values. A value may contain "=" itself (token=abc=xyz gives { token: "abc=xyz" }).

Task 3 · Code · Javascript

Write a function isJson(headers) that returns true when the Content-Type header (in any case) starts with "application/json", and false otherwise, including when there is no Content-Type.

Quick quiz

Question 1

1.Which header tells the server that the body is JSON?

Question 2

2.Are "Content-Type" and "content-type" the same header?

Question 3

3.How does the server ask the browser to save a cookie?

Question 4

4.Why should you never log the Authorization header?

Question 5

5.What does Cache-Control: max-age=3600 mean?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: HTTP status codes