如何在Next.js 13.4.2中在API路由中设置cookie?

huangapple go评论54阅读模式
英文:

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

如何在Next.js 13.4.2中在API路由中设置cookie?

如果用户登录,我想要设置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*

如何在Next.js 13.4.2中在API路由中设置cookie?

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(&lt;JSON body&gt;, {
        status: 200,
        headers: { &quot;Set-Cookie&quot;: `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: &quot;Set cookie successfully&quot; }
  );

  response.cookies.set({
    name: &quot;jwt&quot;,
    value: jwt,
    maxAge: 60*60*24,
    httpOnly: true,
    sameSite: strict,
  });
}

huangapple
  • 本文由 发表于 2023年5月29日 19:17:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定