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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay