March 06, 2024
If you are using the app router in Next.js you can set cookies in the server action or route handler.
Many people are trying to set a cookie in the server component, which is not possible.
If setting a cookie in the server action or route handler doesn't work for you, maybe you can try with the middleware.
Create a middleware.ts
file in the root folder, or inside src
if you are using the src
directory.
Learn more about the middleware in Next.js in the official documentation.
import { NextResponse } from 'next/server'
export function middleware() {
const response = NextResponse.next()
response.cookies.set('your-cookie', 'your-cookie-value', {
httpOnly: true,
path: '/',
secure: true,
})
return response
}
The cookie should be visible in the browser now.
import { cookies } from 'next/headers';
export default async function SomePage() {
// read a cookie
const yourCookie = cookies().get('your-cookie');
.
.
}
If you are trying to implement a CSRF protection, and don't want to worry about the generation or validation of the CSRF token, there is an npm package that works in the edge runtime - edge-csrf.