Search code examples
reactjsnext-auth

How to redirect back to protected page after Nextauth successful login?


I am using NextAuth for auth

const options = {
  providers: [
    EmailProvider({...}),
  ],
  pages: {
    signIn: SIGN_IN_URL,
    verifyRequest: AUTH_URL,
  },
  callbacks: {
    async session(session) {
      return { ...session }
    },
    async signIn({ user }) {
      const result = ...
      if (result) {
        return true
      } else {
        return false
      }
    },
  },
}

I have a protected page /dashboard

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

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

  return {
    props: {},
  }
}

If an unauthorised user tries to access the page they get redirected to the sign in page http://localhost:3000/auth/signin After successful login it redirects back to /.

But how do I set NextAuth up to redirect back to the originating page (in this case /dashboard) after successful log in?


Solution

  • Specify a callbackUrl in the query string. It should be a url encoded path like %2Fdashboard, for example in your snippet:

    export const getServerSideProps = async (context) => {
      const session = await getSession(context)
    
      if (!session) {
        return {
          redirect: {
            permanent: false,
            destination: "/api/auth/signin?callbackUrl=%2Fdashboard",
          },
        }
      }
    
      return {
        props: {},
      }
    }
    

    Going to /api/auth/signin will use the custom signin page you specified in your nextauth config. To see this working in production, check out the official nextauth example.