How to Use Cookies in Middleware in Next.js
In Next.js middleware, you can access cookies from the
Request object using request.cookies.get('cookieName') and set cookies in the Response headers using response.cookies.set(). This allows you to read, modify, or create cookies during the middleware execution before the request reaches your pages or API routes.Syntax
In Next.js middleware, cookies are accessed from the request.cookies object and set using the response.cookies API. You use request.cookies.get('cookieName') to read a cookie and response.cookies.set('cookieName', 'value', options) to set one.
The options can include path, httpOnly, maxAge, and secure to control cookie behavior.
javascript
import { NextResponse } from 'next/server'; export function middleware(request) { // Read a cookie const cookieValue = request.cookies.get('myCookie')?.value; // Create a response const response = NextResponse.next(); // Set a cookie response.cookies.set('myCookie', 'newValue', { path: '/', httpOnly: true, maxAge: 60 * 60 * 24, // 1 day in seconds }); return response; }
Example
This example middleware reads a cookie named userToken. If it doesn't exist, it sets a new cookie with a token value. This shows how to read and write cookies to manage user sessions or preferences.
javascript
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('userToken')?.value; const response = NextResponse.next(); if (!token) { // Set a new cookie if not present response.cookies.set('userToken', 'abc123token', { path: '/', httpOnly: true, maxAge: 60 * 60 * 24 * 7, // 7 days secure: process.env.NODE_ENV === 'production', }); } return response; }
Output
Middleware runs on every request; if 'userToken' cookie is missing, it sets it with value 'abc123token'.
Common Pitfalls
- Trying to modify
request.cookiesdirectly instead of setting cookies on the response. - Not returning the modified
NextResponseobject after setting cookies. - Forgetting to set the
pathoption, which can cause cookies to be unavailable on some routes. - Not using
httpOnlyorsecureflags properly, which can lead to security issues.
javascript
/* Wrong way: Modifying request.cookies directly (does nothing) */ export function middleware(request) { request.cookies.set('test', 'value'); // This won't work return NextResponse.next(); } /* Right way: Set cookie on response */ import { NextResponse } from 'next/server'; export function middleware(request) { const response = NextResponse.next(); response.cookies.set('test', 'value', { path: '/' }); return response; }
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Read cookie | const val = request.cookies.get('name')?.value; | Gets the value of a cookie named 'name'. |
| Set cookie | response.cookies.set('name', 'value', { path: '/' }); | Sets a cookie with name and value, available on all paths. |
| Delete cookie | response.cookies.delete('name'); | Removes the cookie named 'name'. |
| Cookie options | { path: '/', httpOnly: true, maxAge: 3600 } | Options to control cookie scope, security, and lifetime. |
Key Takeaways
Use request.cookies.get() to read cookies in Next.js middleware.
Set cookies on the response object using response.cookies.set() with proper options.
Always return the modified NextResponse to apply cookie changes.
Set cookie options like path, httpOnly, and secure for correct behavior and security.
Avoid trying to modify request.cookies directly; it is read-only.