Next.js Course
Next.js
/
Intermediate

Headers & Cookies

Definition

Reading, setting, and deleting HTTP Headers and Cookies within Next.js Middleware and Route Handlers.

Explain Like I'm New

Headers are invisible metadata attached to every request (like 'Language: English'). Cookies are tiny text files the server forces the browser to hold onto (like 'AuthToken: 123'). Next.js gives you powerful tools to manipulate both.

Real World Example

Reading the `Accept-Language` header to figure out if the user is in France, and automatically redirecting them to the `/fr` version of the website.

Common Use Cases

  • •Authentication
  • •Internationalization
  • •A/B Testing routing

Interactive Example

import { NextResponse } from 'next/server';

export function middleware(request) {
  // 1. Read an incoming header
  const language = request.headers.get('accept-language');
  
  // 2. Read an incoming cookie
  const theme = request.cookies.get('theme');
  
  // 3. Create the response object early so we can modify it
  const response = NextResponse.next();
  
  // 4. Set a new cookie to send BACK to the browser
  response.cookies.set('visited', 'true', {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
  });
  
  // 5. Append a new header to send DOWNSTREAM to our Next.js pages
  response.headers.set('x-user-language', language);
  
  return response;
}

Interview Questions

basic

  • Can a Client Component (browser) read an HTTP-Only cookie?

intermediate

  • How do you set a new cookie inside Next.js Middleware?

Flash Cards

Question

Read HTTP-Only?

Click to reveal answer
Answer

No. That is the entire point of 'HTTP-Only' cookies. They are highly secure because Javascript (`document.cookie`) cannot access them. Only the Server can read them during an HTTP request.

Question

Set a cookie?

Click to reveal answer
Answer

You create a `NextResponse`, use `response.cookies.set('name', 'value')`, and then return that response.