Next.js Discord

Discord Forum

getServerSession incomplete compare to getSession

Answered
Brouillard posted this in #help-forum
Open in Discord
Avatar
I added the role key to my session, it work well with getSession, but doesn't get included when I'm calling getServerSession.
Here is my auth.ts :
import type {
  GetServerSidePropsContext,
  NextApiRequest,
  NextApiResponse,
} from "next"
import type { NextAuthOptions } from "next-auth"
import { getServerSession } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import EmailProvider from "next-auth/providers/email"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export const config = {
  pages: {
    signIn: "/login",
    signOut: "/auth/signout",
  },
  adapter: PrismaAdapter(prisma),
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {},
      async authorize(credentials: any): Promise<any> {
        const user = JSON.parse(credentials.user)
      },
    }),
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: Number(process.env.EMAIL_SERVER_PORT),
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD,
        },
      },
      from: process.env.EMAIL_FROM,
    }),
  ],
  callbacks: {
    jwt: async ({ token, user }) => {
      console.log('callback jwt', { token, user })
      user && (token.user = user)
      return token
    },
    session: async ({ session, token }) => {
      if (token?.user && session?.user) {
        session.user.role = token.user.role
      }
      console.log('callback session', { session, token })
      return session
    }
  },
  secret: process.env.NEXTAUTH_SECRET,
} satisfies NextAuthOptions

// Use it in server contexts
export function auth(
  ...args:
    | [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
    | [NextApiRequest, NextApiResponse]
    | []
) {
  return getServerSession(...args, config)
}
Answered by Brouillard
I found the solution, I was importing getServerSession from "next-auth" instead of importing my custom one :
import { auth as getServerSession } from "@/app/api/auth/[...nextauth]/auth"
View full answer

1 Reply

Avatar
I found the solution, I was importing getServerSession from "next-auth" instead of importing my custom one :
import { auth as getServerSession } from "@/app/api/auth/[...nextauth]/auth"
Answer