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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up