Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 787
Shakib Hasan Avatar asked Nov 27 '25 06:11

Shakib Hasan


2 Answers

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;
like image 198
Shakib Hasan Avatar answered Nov 29 '25 00:11

Shakib Hasan


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)
like image 43
Yilmaz Avatar answered Nov 29 '25 00:11

Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!