I have recently implemented NextAuth v4 and encountered an issue after authenticating with Spotify. Despite successfully retrieving user information from Spotify, I seem to be missing access to the user's profile picture. Here is the data I receive from Spotify:
{
name: '***',
email: '***',
sub: '***',
accessToken: '***',
refreshToken: '***',
username: '***',
accessTokenExpires: ***,
iat: ***,
exp: ***,
jti: '***'
}
Below is the code snippet in /pages/api/auth/[...nextauth].js
:
import NextAuth from 'next-auth/next'
import SpotifyProvider from 'next-auth/providers/spotify'
import spotifyApi, { LOGIN_URL } from '../../../lib/spotify'
async function refreshAccessToken(token) {
try {
spotifyApi.setAccessToken(token.accessToken)
spotifyApi.setRefreshToken(token.refreshToken)
const { body: refreshedToken } = await spotifyApi.refreshAccessToken()
console.log(`REFRESH TOKEN IS: ${refreshedToken}...`)
return {
...token,
accessToken: refreshedToken.access_token,
accessTokenExpires: Date.now + refreshedToken.expires_in + 1000,
refreshToken: refreshedToken.refresh_token ?? token.refreshToken,
}
} catch (error) {
console.log(error)
return {
...token,
error: 'RefreshAccessTokenError',
}
}
}
export default NextAuth({
providers: [
SpotifyProvider({
clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
clientSecret: process.env.NEXT_PUBLIC_CLIENT_SECRET,
authorization: LOGIN_URL,
}),
],
secret: process.env.JWT_SECRET,
pages: {
signIn: '/login',
},
callbacks: {
async jwt({ token, account, user }) {
if (account && user) {
return {
...token,
accessToken: account.access_token,
refreshToken: account.refresh_token,
username: account.providerAccountId,
accessTokenExpires: account.expires_at * 1000,
}
}
if (Date.now() < token.accessTokenExpires) {
console.log('EXISTING ACCESS TOKEN IS VALID')
return token
}
console.log('ACCESS TOKEN HAS EXPIRED, REFRESHING...')
return await refreshAccessToken(token)
},
async session({ session, token }) {
session.user.accessToken = token.accessToken
session.user.refreshToken = token.refreshToken
session.user.username = token.username
console.log('Async session callback', token)
return session
},
},
})
Is there anything specific that needs to be done in order to retrieve the user's profile picture from Spotify, or does Spotify not provide this information? My research did not yield any answers regarding this particular issue.
Thank you, DillonB07