如果未使用 nextAuth 登录,如何在 NextJS 中重定向 [英] How to redirect in NextJS if not logged using nextAuth

查看:13
本文介绍了如果未使用 nextAuth 登录,如何在 NextJS 中重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用 nextAuth 进行身份验证,我想为未登录的客户端限制某些页面.

I am using nextAuth for the authentication in my Project and I would like to restrict certain pages for the clients that are not logged in.

我尝试在 getServerSideProps 函数中调用 useSession() 挂钩,但在那里调用该挂钩时出错.

I tried calling the useSession() hook in the getServerSideProps function but I got an error for calling the hook there.

是否可以使用 nextAuth 在服务器端进行重定向?

Is it possible to do a redirect on the server side using nextAuth?

推荐答案

getServerSideProps 中不能使用 useSession 钩子.您需要使用 getSession.你可以阅读更多这里.如果会话不存在,您可以在 getServerSideProps 中重定向.这是一个例子:

You can't use the useSession hook in getServerSideProps. You need to use getSession. You can read more here. You can redirect in getServerSideProps if the session doesn't exist. Here's an example:

export async function getServerSideProps(context) {
  const session = await getSession(context)

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }

  return {
    props: { session }
  }
}

这篇关于如果未使用 nextAuth 登录,如何在 NextJS 中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆