How do I use next auth getServerSession in next js 13 beta server component in app directory
Asked Answered
T

4

20

I'm using next auth v4 with next js 13 beta with server component, and everything works fine. But I have a situation where I will need to know the logged user id, since I'm using next auth, I have access to the session, I can use useSession() but then I will need to make the component a client component, So I want to use it on the server, I can use getServerSession in API since I have access to req & res object, but in next js beta with new app dir, I can't do it. Please let me know if you know how to fix the issue. Thank you

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

const Test = async () => {
    const user_id = 1; // How do I get user id from session, user_id is available in session

    // I don't have access req & res object in server component.
    const data = await getServerSession(request, response, authOptions);

    console.log(data);

});
    return (
        <></>
    );
};

export default Test;

Didn't find enough information

Tupler answered 10/2, 2023 at 16:4 Comment(0)
T
26

I found an answer, in next js 13, you wont need to use request & response object, just use the authOptions, it will work

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

const Test = async () => {

    const data = await getServerSession(authOptions);

    console.log(data);

});
    return (
        <></>
    );
};

export default Test;
Tupler answered 10/2, 2023 at 16:11 Comment(7)
Mind sharing your authOptions?Anaphylaxis
[gist.github.com/shakibhasan09/… thisTupler
I am having the same issue. Does that link still work? I am getting 404.Caliban
[gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b2fb]Tupler
Another 404 - would you mind sharing your authOptions in the post?Abdul
@DavidConlisk, sure gist.github.com/shakibhasan09/c37eb67910a992f881e722313531b2fbTupler
This displays a message in the server console. Not sure if it's a warning: ``getServerSession` is used in a React Server Component.`Carew
L
8

Docs for Options

import { NextAuthOptions } from 'next-auth'
import { getServerSession } from 'next-auth'

this is the NextAuthOptions type

export interface AuthOptions {
  providers: Provider[];
  secret?: string;
  session?: Partial<SessionOptions>;
  jwt?: Partial<JWTOptions>;
  pages?: Partial<PagesOptions>;
  callbacks?: Partial<CallbacksOptions>;
  events?: Partial<EventCallbacks>;
  adapter?: Adapter;
  debug?: boolean;
  logger?: Partial<LoggerInstance>;
  theme?: Theme;
  useSecureCookies?: boolean;
  cookies?: Partial<CookiesOptions>;
}

this is how you get the session

const session = await getServerSession(authOptions)

Based on AuthOptions interface

const authOption: NextAuthOptions = {
  // Since you tagged prisma
  adapter: PrismaAdapter(yourDbConfig),
  session: {
    strategy: 'jwt',
  },
  // https://next-auth.js.org/configuration/pages
  pages: {
    signIn: '/login',
  },
  providers: [
    GoogleProvider({
      clientId: clientId,
      clientSecret: clientSecret,
    }),
  ],
  callbacks: {
    async session({ token, session }) {
      if (token) {
        // set session here
      }
      return session
    },
    async jwt({ token, user }) {
      const dbUser = getUserByTokenEmail
           //add logic here
    },
  },
}

this is how we use authOptions to set up next-auth

// app/auth/[...nextauth].ts (I think after next 13.2)
// pages/api/auth/[...nextauth].ts before
    
import { authOptions } from 'folderLocationOfauthOptions'
import NextAuth from 'next-auth'
    
export default NextAuth(authOptions)
Labuan answered 2/4, 2023 at 2:22 Comment(6)
Oh, thank you, very detailed. Although, having just started all this, the file structure is causing me some headache. If we're to be migrating away from /pages/api/auth/[...nextauth].js, where are all these config and functions supposed to go?Circumlocution
@Circumlocution this is exactly what I'm trying to understand at the moment as well. Any luck?Philipphilipa
@Philipphilipa we are not migrating away [...nextauth].js. updated the answerLabuan
@Labuan I actually tried the same configuration you placed here, with NextJS 13 app router. I have no luck .. keeps getting unauthenticated.Angelitaangell
@TommyLeong have you configured correctly? Did you wrap the app with the auth providerLabuan
Yes I did, I also tried passing in the session to SessionProvider. I'll setup a post and come back with link for better clarity.Angelitaangell
R
4

If you're using app directory in Next 13, and initiating next-auth from Route handlers like this :

src/app/api/auth/[...nextauth]/route.js

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ]
})

export { handler as GET, handler as POST }

then you can just using getServerSession in server components without passing anything

src/app/layout.js

import { getServerSession } from 'next-auth'

...

export default async function Layout ({ children }) {
  const data = await getServerSession()

  return (
    <h5>Data: {JSON.stringify(data)}</h5>
  )
}

Redemption answered 27/1 at 4:51 Comment(4)
Hi @priyabagus, interesting way of getting serversession from rootlayout. Im also with NextJs 13, app router... with your technique here, im still getting { user: { name: undefined, email: undefined, image: undefined } }Angelitaangell
@TommyLeong Have you tried logging in?Redemption
Yes I did. In fact at this moment, when I enable PrismaAdapter it will always keep me as unauthenticated.Angelitaangell
This is one of the easiest ways to do auth on the server-rendered components and pagesHerron
G
1

If you are trying to do the same this with the app router, its the same flow except the authOptions will be added to app/api/auth/[...nextauth]/route.(ts/js).

Gills answered 12/7, 2023 at 18:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.