I’m using Nextjs ^13.4 with GraphQL Yoga & Apollo/client and Prisma.
I’m trying to get the current user’s session in GraphQL Pothos, by forwarding the response of getServerSession()
but its always null
.
If I call getServerSession()
within a RSC, then I can see the session details.
1. apps/web/app/api/auth/[…nextauth]/options.ts
export const authOptions: AuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
authorization: {
params: {
scope: GOOGLE_SCOPES
}
}
})
],
adapter: PrismaAdapter(prisma),
secret: process.env.SECRET,
session: {
strategy: 'database',
maxAge: 24 * 60 * 60
},
jwt: {
secret: process.env.SECRET,
maxAge: 60 * 60 * 24 * 30
},
callbacks: {
async session({ session, user, token }) {
if (user !== null) {
session.user = user
}
return session
},
async jwt({ token, user }) {
return token
}
}
}
2. apps/web/app/api/graphql/route.ts
import { createYoga, schema } from '@nali/backend'
import { createContext } from './context'
const { handleRequest } = createYoga({
schema,
// While using Next.js file convention for routing, we need to configure Yoga to use the correct endpoint
graphqlEndpoint: '/api/graphql',
healthCheckEndpoint: '/healthz',
context: async ({ request }) => {
return createContext(request)
},
// Yoga needs to know how to create a valid Next response
fetchAPI: { Request, Response }
})
export { handleRequest as GET, handleRequest as POST }
3 apps/web/app/api/graphql/context.ts
import { authOptions } from '../auth/[...nextauth]/options'
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
export async function createContext(req: any) {
const session = await getServerSession(authOptions)
console.log('====== createContext(): =======: ', session)
// if the user is not logged in, return an empty object
if (!session || typeof session === 'undefined') return {}
const { user, expires } = session
return { user, expires }
}
4 packages/backend/src/infrastructure/graphql/types/user.ts
builder.queryField('users', t =>
t.prismaConnection(
{
type: 'User',
cursor: 'id',
resolve: async (query, _parent, _args, _ctx, _info) => {
console.log('Here: ', _ctx.user) // always null
return await userRepo.getUsers()
}
}
)
)
``