在 nextjs getServerSideProps 中获取服务器端 cookie

编程入门 行业动态 更新时间:2024-10-09 23:19:25

在 nextjs getServerSideProps 中获取<a href=https://www.elefans.com/category/jswz/34/1771251.html style=服务器端 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

本文发布于:2024-05-13 14:18:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器端   nextjs   getServerSideProps   cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!