Search code examples
javascriptreactjsnext.jsnext.js13next-auth

How to use next-auth server side in nextjs 14


Can I use next-auth in Next.js 14 app router to get user session and show page responses with SSR? If yes, how can I do it?


Solution

  • Here is how you can get user session on the server side:

    Install the next-auth package

    npm install next-auth
    

    Create the file /app/api/auth/[…nextauth]/route.ts

    import { authenticate } from "@/services/authService"
    import NextAuth from "next-auth"
    import type { AuthOptions } from "next-auth"
    import CredentialsProvider from "next-auth/providers/credentials"
    
    export const authOptions: AuthOptions = {
      providers: [
        CredentialsProvider({
          name: 'Credentials',
          credentials: {
            email: { label: "Email", type: "text" },
            password: { label: "Password", type: "password" }
          },
          async authorize (credentials, req) {
            if (typeof credentials !== "undefined") {
              const res = await authenticate(credentials.email, credentials.password)
              if (typeof res !== "undefined") {
                return { ...res.user, apiToken: res.token }
              } else {
                return null
              }
            } else {
              return null
            }
          }
        })
      ],
      session: { strategy: "jwt" }
    }
    
    const handler = NextAuth(authOptions)
    
    export { handler as GET, handler as POST }
    
    

    Now you can access the session on server side like this:

    import { getServerSession } from "next-auth/next"
    import type { NextRequest } from "next/server"
    import { authOptions } from "@/app/api/auth/[...nextauth]/route"
    
    export default async function Protected (req: NextRequest): Promise<any> {
      const session = await getServerSession(authOptions)
    
      return (
        <div className='grid grid-cols-2 text-white p-4'>
          <div>
            {
              session !== null
                ? <h1 className='leading-loose text-[15rem] font-extrabold text-accent'>
                    Hi {session?.user.name}!
                  </h1>
                : <a className='btn btn-primary' href='/api/auth/signin'>Sign in</a>
            }
          </div>
        </div>
      )
    }
    

    Reference article (yes, the articles says Next 13 but the auth will be implemented in same way in Next 14).

    Check the docs here.