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;
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;
Share Improve this question asked Jan 17 at 15:36 Nawin PoolsawadNawin Poolsawad 2595 silver badges15 bronze badges 2- What is your error message? – Ahmet Firat Keler Commented Jan 18 at 8:36
- @AhmetFiratKeler no error message, got response with status success but no change on Cookies. but I just got information about cookie must set/delete by calling from client component only. I have try it and it true. But the problem is I have to call /api/logout immediately after got 401 and it's server-side. TT – Nawin Poolsawad Commented Jan 18 at 14:44
1 Answer
Reset to default 1The 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>;
};