Back to roadmaps nodejs Course

CORS and Cookie Management

When developing web services, you will inevitably encounter security policies such as Cross-Origin Resource Sharing (CORS) and require mechanisms like Cookies to track state between request invocations.


1. Configuring CORS Headers

Web browsers enforce the Same-Origin Policy. If your frontend app runs on http://localhost:5173 and requests resources from your Node.js backend on http://localhost:3000, the browser will block the response unless the backend explicitly permits the request origin.

To configure CORS, you must reply to the initial preflight options request and append specific HTTP headers:

import http from "http";

const server = http.createServer((req, res) => {
  // Set CORS headers
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.setHeader("Access-Control-Allow-Credentials", "true"); // Allows sending cookies across domains

  // Handle preflight OPTIONS request
  if (req.method === "OPTIONS") {
    res.writeHead(204); // No Content
    res.end();
    return;
  }

  // Handle actual API requests
  if (req.method === "GET" && req.url === "/api/data") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: "Secure cross-origin data payload" }));
  }
});

server.listen(3000);

2. Managing HTTP Cookies

Cookies are tiny keys of string data sent by the server via the Set-Cookie header and stored by the browser. The browser automatically appends these cookies to subsequent requests in the Cookie header.

Setting a Cookie

You can configure attributes like HttpOnly (prevents JavaScript access to block XSS attacks) and Max-Age (sets cookie expiration):

res.writeHead(200, {
  "Content-Type": "text/plain",
  "Set-Cookie": [
    "session_id=abc123xyz; HttpOnly; Path=/; Max-Age=3600; Secure; SameSite=Lax"
  ]
});
res.end("Cookie has been successfully set");

3. Parsing Incoming Cookies

Since cookies are sent to the server in a single raw string, we must parse them into a structured key-value object:

import http from "http";

function parseCookies(cookieHeader) {
  const list = {};
  if (!cookieHeader) return list;

  cookieHeader.split(";").forEach((cookie) => {
    const parts = cookie.split("=");
    const key = parts.shift().trim();
    const value = decodeURI(parts.join("="));
    list[key] = value;
  });

  return list;
}

const server = http.createServer((req, res) => {
  const rawCookies = req.headers["cookie"];
  const cookies = parseCookies(rawCookies);
  
  console.log("Parsed client cookies:", cookies);
  
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end(`Welcome back, session key: ${cookies["session_id"]}`);
});

server.listen(3000);
Published on Last updated: