DEV Community

jacob30
jacob30

Posted on

NextAuth TwitterProvider UserId on Session

If you follow the NextAuth instructions for the TwitterProvider you won't immediately get the UserId on the Session Provider, when you use the useSession() hook. The below code worked for me.

import NextAuth from 'next-auth';
import TwitterProvider from 'next-auth/providers/twitter';

import { addSignedInUserToDb } from '@/app/auth-client';

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    TwitterProvider({
      clientId: process.env.TWITTER_CLIENT_ID,
      clientSecret: process.env.TWITTER_CLIENT_SECRET,
    }),
  ],
  session: {},
  secret: process.env.SECRET as string,
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      user.x_id = profile.data.id;
      // this is where i add the userId to db
      await addSignedInUserToDb(user);
      return true;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
    async session({ session, user, token }) {
      session.user.x_id = token.data.id;
      return session;
    },
    async jwt({ token, user, account, profile }) {
      return { ...token, ...user, ...account, ...profile };
    },
  },
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)