Working with cookies
This page explains how to work with cookies in Next.js route handlers.
Understanding cookies
Cookies are small pieces of data that a server sends to a user’s web browser. The browser stores these cookies and sends them back to the same server with future requests.
Cookies serve three main purposes:
- Session management: Handling user logins, shopping carts, and other stateful information
- Personalization: Storing user preferences, themes, and settings
- Tracking: Recording and analyzing user behavior
Setting and reading cookies
Next.js provides two approaches to work with cookies in route handlers:
Method 1: Using response headers and request object
Setting cookies with response headers:
import { type NextRequest } from "next/server";
export async function GET(request: NextRequest) { return new Response("<h1>Profile API data</h1>", { headers: { "Content-Type": "text/html", "Set-Cookie": "theme=dark", }, });}
Reading cookies from the request:
import { type NextRequest } from "next/server";
export async function GET(request: NextRequest) { const theme = request.cookies.get("theme"); console.log(theme); // { name: 'theme', value: 'dark' }
// Process based on cookie value return new Response("Cookie processed");}
Method 2: Using the cookies function
Next.js provides a built-in cookies()
function for more convenient cookie management:
Setting cookies:
import { cookies } from "next/headers";
export async function GET() { const cookieStore = cookies(); cookieStore.set("resultsPerPage", "20");
return new Response("Cookie set");}
Reading cookies:
import { cookies } from "next/headers";
export async function GET() { const cookieStore = cookies(); const resultsPerPage = cookieStore.get("resultsPerPage"); console.log(resultsPerPage); // { name: 'resultsPerPage', value: '20' }
return new Response("Cookie read");}
Cookie options
When setting cookies, you can specify additional options:
// Using response headersreturn new Response("Success", { headers: { "Set-Cookie": "theme=dark; Path=/; HttpOnly; Max-Age=3600", },});
// Using cookies functioncookieStore.set({ name: "theme", value: "dark", path: "/", httpOnly: true, maxAge: 3600,});
Common cookie options include:
Path
: Specifies the URL path where the cookie is validHttpOnly
: Makes the cookie inaccessible to JavaScriptSecure
: Only sends the cookie over HTTPSMax-Age
: Sets the cookie’s expiration time in secondsSameSite
: Controls when cookies are sent with cross-site requests
Additional cookie methods
The cookies()
function provides several useful methods:
// Check if a cookie existsconst hasCookie = cookieStore.has("theme");
// Delete a cookiecookieStore.delete("theme");
// Get all cookiesconst allCookies = cookieStore.getAll();
Good to know
- Cookies are sent with every request to your server, increasing request size
- Keep cookie data minimal for better performance
- Use HttpOnly for cookies that don’t need to be accessed by JavaScript
- Set appropriate expiration times for cookies
- Consider security implications when storing sensitive information in cookies