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

Loading Code Playground...

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.