notes.dt.in.th

When using NextAuth.js to manage authentication in a Next.js app, by default, the current user ID is not included in the session data. To access the user ID, some extra configuration is required.

Important: This note assumes a JWT session, not a database-backed session.

declare module 'next-auth' {
  export interface Session {
    userId?: string
  }
}

export const authOptions: NextAuthOptions = {
  // ...
  callbacks: {
    async session({ session, token }) {
      session.userId = token.sub
      return session
    },
  },
}