Search code examples
reactjsnext.jsserver-side-renderingnext-authnext.js13

getServerSession on next js 13 with api routes on app directory


Im using next-auth and trying to get serverSession on server component, im using Next.js 13 beta with App directory and the API directory is also on the App directory so according to next-auth docs this is how I can get the serverSession

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

export default async function Page() {
  const session = await getServerSession(authOptions)
  return <pre>{JSON.stringify(session, null, 2)}</pre>
}

but the AuthOptions is not available because according to next-auth docs again this is how my api route should looks like with next.js 13 beta

import NextAuth from "next-auth"

const handler = NextAuth({
  ...
})

export { handler as GET, handler as POST }

so there is no authOptions to import like the request

how can I do that

Thanks


Solution

  • You can simply export authOptions and handlers following this way:

    export const authOptions = {
       //...
    };
    
    const handler = NextAuth(authOptions);
    
    export { handler as GET, handler as POST };