Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get User ID from session in next-auth client

I'm using next-auth with Prisma and Graphql, I followed these instructions to set up the adapter and my models accordingly: https://next-auth.js.org/adapters/prisma Authentication works but when I inspect session object from here : const { data: session, status } = useSession() I don't see ID enter image description here

The reason I need the ID is to make further GraphQL queries. I'm using email value for now to fetch the User by email, but having ID available would be a better option.

like image 460
Ivditi Gabeskiria Avatar asked Sep 07 '25 12:09

Ivditi Gabeskiria


2 Answers

Here's the quickest solution to your question:

src/pages/api/auth/[...nextAuth].js

export default NextAuth({
  ...
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.sub;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }
      return token;
    },
  },
  session: {
    strategy: 'jwt',
  },
  ...
});
like image 176
Frahim Avatar answered Sep 11 '25 02:09

Frahim


I just referred to the NextAuth docs (this page) and finally got it working the right way

callbacks: {
  jwt({ token, account, user }) {
    if (account) {
      token.accessToken = account.access_token
      token.id = user?.id
    }
    return token
  }
  session({ session, token }) {
      // I skipped the line below coz it gave me a TypeError
      // session.accessToken = token.accessToken;
      session.user.id = token.id;

      return session;
    },
}

If you use TypeScript, add this to a new file called next-auth.d.ts

import NextAuth from 'next-auth';

declare module 'next-auth' {
  interface Session {
    user: {
      id: string;
    } & DefaultSession['user'];
  }
}
like image 35
Usman Sabuwala Avatar answered Sep 11 '25 01:09

Usman Sabuwala



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!