英文:
how to set cookie in nextjs 13.4.2 in api route
问题
如何在Next.js 13.4.2中设置cookie
我已经尝试使用NextResponse和cookies-next,但它没有在我的浏览器中设置cookie。
我的流程是:
-
用户登录
-
验证用户
-
在HttpOnly的cookie中保存JWT
app/api/signin/route.ts
如果用户登录,我想要设置cookie并将JWT令牌保存在cookie存储中。
英文:
how to set cookie in nextjs 13.4.2
i have try with NextResponse and cookies-next, but its not set the cookie in my browser.
my flow is
-
user sigin
-
validate user
-
save jwt in cookie http only
*app/api/signin/route.ts*
i want to set cookie if the user signin and save the jwt token in cookie storage
答案1
得分: 2
你可以尝试在NextResponse中使用"Set-Cookie"头部。
export async function GET(req: NextRequest) {
// 在这里执行操作
return new NextResponse(<JSON body>, {
status: 200,
headers: { "Set-Cookie": `jwt=${jwt}; sameSite=strict; httpOnly=true; maxAge=60*60*24` },
});
}
带有"Set-Cookie"头的响应将设置Cookie。
否则,如果你想要使用NextResponse方法设置Cookie,首先创建响应,然后使用set()方法。
export async function GET(req: NextRequest) {
const response = NextResponse.json(
{data},
{ status: 200, statusText: "Set cookie successfully" }
);
response.cookies.set({
name: "jwt",
value: jwt,
maxAge: 60*60*24,
httpOnly: true,
sameSite: "strict",
});
}
英文:
You can try using the "Set-Cookie" headers in the NextResponse.
export async function GET(req: NextRequest) {
// do stuff here
return new NextResponse(<JSON body>, {
status: 200,
headers: { "Set-Cookie": `jwt=${jwt}; sameSite=strict; httpOnly=true; maxAge=60*60*24` },
});
}
Responses with Set-Cookie
headers will set the cookies.
Otherwise, if you would like to set the cookies using the NextReponse methods, create the response first then use set()
export async function GET(req: NextRequest) {
const response = NextResponse.json(
{data},
{ status: 200, statusText: "Set cookie successfully" }
);
response.cookies.set({
name: "jwt",
value: jwt,
maxAge: 60*60*24,
httpOnly: true,
sameSite: strict,
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论