reactjsnext.jscookies

Unable to set/get/delete cookies in Next.js 15 route handlers using the Cookies API?


I am trying to set, delete, and get all cookies on my website using the cookies API from Next.js 15 in the route handler, but it doesn't seem to be working.

route.ts

// app/api/logout/route.ts
import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';

export async function POST() {
  const cookieStore = await cookies();
  cookieStore.delete('token');

  return NextResponse?.json({ status: 'success' });
}

Server component ( page )

// app/upload-documents/page.tsx
const UploadDocumentsPage = async () => {
  const res = await fetch('http://localhost:3000/api/logout', { method: 'POST'})

  return <PageContainer>Content UploadDocumentsPage</PageContainer>;
};

export default UploadDocumentsPage;


Solution

  • The cookies work in server action, so I recommend to make below server action for cookies.

    // app/server-actions.ts
    "use server";
    import { cookies } from "next/headers";
    
    export const delCookie = async (name: string) => {
      cookies().delete(name);
    }
    

    Call this server action function in your component.

    // app/upload-documents/page.tsx
    const UploadDocumentsPage = async () => {
      const res = await delCookie("token");
    
      return <PageContainer>Content UploadDocumentsPage</PageContainer>;
    };