'how to get the provider access token in next-auth

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?



Solution 1:[1]

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)

Solution 2:[2]

You can access this using the getSession method, which can be used server-side (i.e. in next.js methods like getServerSideProps and client side (i.e. in your normal react components).

See: https://next-auth.js.org/getting-started/client#getsession

Solution 3:[3]

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.

Solution 4:[4]

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;
    },
  },

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mandeep Singh
Solution 2 ndom91
Solution 3
Solution 4 Saheb Mohammadi