How to redirect in NextJS if not logged using nextAuth
Asked Answered
S

5

17

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

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

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

Service answered 26/7, 2021 at 9:43 Comment(0)
D
33

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 }
  }
}
Dijon answered 26/7, 2021 at 18:16 Comment(0)
G
9

Feb 2023: With the new app/ directory feature coming with NextJS13, the auth middleware from NextAuth isn't working (at least for me).

I figured out a way to protect frontend sites easily and fast. But be aware that it is bad practice to protect only your frontend pages! Your API should be secured too!

Here's the code:

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>
      </>
    )
  }
}
Grad answered 25/2, 2023 at 11:47 Comment(3)
Make sure the middleware.ts file is on the same directory level as your app folder and pages folderYesima
wow, this works. how tragic.Pirandello
This works and it's the approach I'm currently using but the issue is that you get server side errors because the redirect includes a HEAD request and that causes next auth to throw an UnknownAction error. Mostly just annoying since the rest of the flow works as intended.Connoisseur
Y
4

NextAuth can handle redirection to a sign-in page if the user is not logged in. Take a look at the documentation

Here are the steps

  1. Create a file called middleware.ts on the same directory level as your pages folder or your app folder if you are using next js 13
  2. You can export a config object inside middleware.ts that has a matcher property assigned to an array of the routes you want to protect. In the example below I am protecting all routes that start with /admin. But you can add as many as you want since it is an array.

middleware.ts

 export { default } from "next-auth/middleware";

 export const config = {
  matcher: ["/admin/:path*"],
};
Yesima answered 26/3, 2023 at 8:3 Comment(1)
This does not work in Next 13 and app directory. I do not have a solution.,=Ivan
H
1

Recommended to use middleware approach now: https://next-auth.js.org/tutorials/securing-pages-and-api-routes#server-side

Holm answered 7/1, 2023 at 12:36 Comment(0)
S
1

Aug 2023 Update: The method getSession() has been replaced by getServerSession(). Here is an example of how to protect Server-side rendered pages:

import { getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"
import { useSession } from "next-auth/react"

export default function Page() {
  const { data: session } = useSession()

  if (typeof window === "undefined") return null

  if (session) {
    return (
      <>
        <h1>Protected Page</h1>
        <p>You can view this page because you are signed in.</p>
      </>
    )
  }
  return <p>Access Denied</p>
}

export async function getServerSideProps(context) {
  return {
    props: {
      session: await getServerSession(
        context.req,
        context.res,
        authOptions
      ),
    },
  }
}

You can find more info here.

Staffordshire answered 19/8, 2023 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.