Skip to content

Cookie

Description

The Cookie request header is an HTTP header field used by web clients (such as browsers) to send stored cookies to a web server. Cookies are small pieces of data stored on a user's device by a website to maintain session state, track user preferences, and manage authentication.

When a client makes a request to a server, the Cookie header includes any relevant cookies previously set by the server. These cookies enable functionality such as maintaining user sessions, personalizing content, and tracking analytics.

Cookies are often set using the Set-Cookie response header, and they persist across multiple requests, allowing web applications to retain user data over time.

Syntax

The Cookie header follows this syntax:

Cookie: <cookie-name>=<cookie-value>[; <cookie-name>=<cookie-value>]...

Multiple cookies can be included in a single Cookie header, separated by semicolons.

Examples

Basic Usage in HTTP Requests

When a user visits a website, the server may set a cookie using the Set-Cookie header. On subsequent requests, the browser sends the cookie back to the server using the Cookie header:

GET /dashboard HTTP/1.1
Host: www.example.com
Cookie: sessionId=abc123; theme=dark

This informs the server of the user's session and theme preference.

Server-Side Handling

A server can read cookies from incoming requests to authenticate users or personalize responses. Below is an example of handling cookies in JavaScript (Node.js with Express):

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());

app.get('/', (req, res) => {
    console.log('Cookies:', req.cookies);
    res.send('Cookies received');
});

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

Setting Cookies in a Response

A server can send cookies to the client using the Set-Cookie header:

app.get('/login', (req, res) => {
    res.cookie('sessionId', 'abc123', { httpOnly: true, secure: true });
    res.send('Session cookie set');
});

Checking Cookies in Client-Side JavaScript

Client-side scripts can read cookies using document.cookie, though this is limited to non-HttpOnly cookies:

console.log(document.cookie); // Outputs: "sessionId=abc123; theme=dark"

Summary

The Cookie request header plays a crucial role in maintaining stateful interactions on the web. It allows servers to recognize returning users, store session information, and personalize experiences. However, cookies also raise privacy concerns, which is why modern browsers provide security measures like SameSite attributes and cookie partitioning to limit tracking and enhance user security.