how to get the provider access token in next-auth

Viewed 11714

Hi I am new to nextjs and for authentication I am using next-auth. The users can log in using Google and when they are logged in and authenticated I want to get the access_token given by provider in this case Google. Although I can get that inside signIn callback function but is there a way to globally access that?

4 Answers

you can create the callbacks key in the nextAuth config as below to access your userId and access_token, as well.

callbacks: {
    async session({ session, token, user }) {
      session.user.id = token.id;
      session.accessToken = token.accessToken;
      return session;
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      if (user) {
        token.id = user.id;
      }
      if (account) {
        token.accessToken = account.access_token;
      }
      return token;
    },
  },

Please refer to this post which i think will help.

Please be aware of next-auth version, in V4 you can access the access token by: account.access_token, before V4 it will be account.accessToken.

Also this link will help wih callbacks in next0auth V4.

for Credentials login

use callbacks like this

callbacks: {
    jwt: async ({ token, user }) => {
        user && (token.user = user)
        return token
    },
    session: async ({ session, token }) => {
        session.user = token.user
        return session
    }
}

then in page import

import { getSession ,useSession, signIn, signOut } from "next-auth/react";

and use this for get token

const { data: token, status } = useSession()
console.log(token)

for get sessin use this

const { data: session, status } = useSession()
console.log(session)
Related