admin管理员组文章数量:1321260
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>;
};
版权声明:本文标题:reactjs - Unable to setgetdelete cookies in Next.js 15 route handlers using the Cookies API? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742094998a2420492.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论