如何在服务器端使用NextResponse设置cookie?

fdbelqdn  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(183)

我正在尝试使用Next Response从服务器端设置cookie:

import { NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';
import { config } from '@/config/config';
const GET = async () => {
    const expiration = Math.floor(Date.now() / 1000) + 300; // 5 minutes from now
    const token = jwt.sign({ exp: expiration }, config.JWT_SECRET);
    return NextResponse.json({ token }); // How do I set cookie?
};

export { GET };

有人能告诉我如何从服务器端使用NextResponse设置cookie吗?

tct7dpnv

tct7dpnv1#

此Cookie示例是只读的。要设置cookie,您需要使用Set-Cookie头返回一个新的Response。

import { cookies } from 'next/headers'
 
export async function GET(request: Request) {
  const cookieStore = cookies()
  const token = cookieStore.get('token')
 
  return new Response('Hello, Next.js!', {
    status: 200,
    headers: { 'Set-Cookie': `token=${token}`},
  })
}

这个例子来自nextjs文档,所以在你的用例中应该是:

import { cookies } from 'next/headers';
//...
export async function GET(request) {
  const expiration = Math.floor(Date.now() / 1000) + 300; // 5 minutes from now
  const token = jwt.sign({ exp: expiration }, config.JWT_SECRET);

  // update cookieStore
  const cookieStore = cookies();
  cookieStore.set('token', token, {
    //...
  });

  return new Response(JSON.stringify({ token }), {
    status: 200,
    headers: { 'Set-Cookie': `token=${token}`},
  });
}

相关问题