如果未使用 nextAuth 登录,如何在 NextJS 中重定向

Ben*_*nni 16 redirect next.js next-auth

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

我尝试useSession()getServerSideProps()函数中调用挂钩,但是在调用该挂钩时出现错误。

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

San*_*rle 31

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

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

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

  return {
    props: { session }
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

2023 年 2 月:随着NextJS13 附带新的app/ 目录功能,NextAuth 的身份验证中间件不起作用(至少对我来说)。

我找到了一种轻松快速地保护前端站点的方法。但请注意,仅保护您的前端页面是不好的做法!您的 API 也应该受到保护!

这是代码:

import { getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
import { redirect } from 'next/navigation';

export default async function Page() {
  const session = await getServerSession(authOptions)
  if(session == null){
    return redirect("api/auth/signin")
  } else {
    return (
      <>
      <h1 className=" text-2xl">Very secure Page</h1>  
      <pre>{JSON.stringify(session, null, 2)}</pre>
      </>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 确保“middleware.ts”文件与您的应用程序文件夹和页面文件夹位于同一目录级别 (4认同)