11

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

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Shakib Hasan
  • 231
  • 1
  • 1
  • 8

3 Answers3

12

I found an answer, in next js 13 beta, 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;
Shakib Hasan
  • 231
  • 1
  • 1
  • 8
3

Docs for Options

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

this is 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 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 htink after next 13.2)
// pages/api/auth/[...nextauth].ts before

import { authOptions } from 'folderLocationOfauthOptions'
import NextAuth from 'next-auth'


export default NextAuth(authOptions)
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • 1
    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? – mtro Apr 11 '23 at 15:05
  • @mtro this is exactly what I'm trying to understand at the moment as well. Any luck? – Laky Jun 21 '23 at 17:10
  • @Laky we are not migrating away `[...nextauth].js`. updated the answer – Yilmaz Jun 21 '23 at 20:32
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).

xCoBaLTz
  • 11
  • 2