服务器端 cookie"/>
在 nextjs getServerSideProps 中获取服务器端 cookie
我正在尝试为我的 Next.js 网站进行身份验证。
我在
/api/users/signin
中创建了一个登录端点,在验证用户之后,我在其中生成了一个 JWT 令牌并使用以下内容保存它:
res.setHeader("Set-Cookie", `token=${token}; HttpOnly; Secure`);
现在我想做的是:我尝试使用 getServerSideProps 从
/pages/login
访问这个令牌。
我怎样才能做到这一点 ?我什至可以访问从 /api/users/signin
设置到 /pages/login
的 cookies 吗?
export async function getServerSideProps(context: any) {
console.log(context.req.headers.cookie);
const response = await checkAuth(context.req.headers);
return {
props: {
response,
},
};
}
如果我错了,什么是正确的方法? 注意:我检查了
/api/users/signin
并且 cookie 设置完美并且 api 端点没有问题。
回答如下:
我建议使用 中间件。您可以在与
middleware.ts
目录相同的级别创建一个 pages
文件,并在要使用 matcher
运行中间件的路径中检查给定的 cookie。例如,如果你想在只有 token
存在的情况下显示一个管理页面,你的中间件可能看起来像这样:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
// this will check if there is a value for the cookie named token
// if it exists it will load the page
if (request.cookies.get('token')?.value) return NextResponse.next();
// if the cookie does not exist, you can redirect anywhere you want
return NextResponse.redirect(new URL('/<change-this-to-whatever>', request.url));
}
// this will make sure that the middleware only runs on /pages/admin
// you can change it whatever you want
export const config = {
matcher: '/admin',
};
更多推荐
在 nextjs getServerSideProps 中获取服务器端 cookie
发布评论