Setting Cookies In Next.js 14 (App Router)

March 06, 2024

setting cookies in next.js 14 app router

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.

Set a cookie in 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 =
  response.cookies.set('your-cookie', 'your-cookie-value', {
    httpOnly: true,
    path: '/',
    secure: true,
  return response

The cookie should be visible in the browser now.

Read a cookie in the server component

import { cookies } from 'next/headers';

export default async function SomePage() {
  // read a cookie
  const yourCookie = cookies().get('your-cookie');

Additional Info

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.