The issue of NextAuth in connection with Spotify failing to display the user's profile picture

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

Answer №1

It seems having a profile picture is necessary in order to retrieve the image!

In cases where you lack a profile picture, Spotify simply provides a response of null.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

Styling with Styled Components in Next.js 9+ to Prevent FOUC (Flash of Unstyled Content)

After researching solutions and ideas from various sources, such as SA and Reddit, I have been unable to resolve an issue that causes the HTML to load without any styling before being injected into the DOM on both production and local environments. Below ...

Error caused by jQuery AJAX call: Receiving a 304 response code causes a problem

I am facing an issue with a script on my localhost that sends a GET request to the same domain. The response I am getting is a 304, which seems to be causing JQuery to treat it as an error. $(document).ready(function(){ $.ajax({ type: 'GE ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...

Problems arising from jQuery Mobile, NPM, and WebPack

After spending a considerable amount of time researching and experimenting, I am confident that I could piece something together to make it work. However, I would rather gain an understanding of the root cause of my issue. It is widely acknowledged that j ...

`initMap` does not exist as a function

Hey everyone, I need some help: I recently integrated the Google Maps API into my AngularJs project and encountered an error in the console: Uncaught message: "initMap is not a function" name: "InvalidValueError" This occurs when the Google Map API is ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Customizing text appearance with innerHTML in JavaScript: A guide to styling

Below is the code I have for a header: <div id="title-text"> The Cuttlefisher Paradise </div> <div id="choices"> <ul> <li id="home"><a href="#">Home</a></li> <li id="contact">&l ...

Ensuring the safety of PHP JSON output results on a web server

I am currently developing an app using phonegap that submits and retrieves data from a MySQL database hosted on a server (website). I have successfully implemented the data submission and retrieval features in the app. The data is fetched through AJAX fro ...

How can I trigger an Iframe JavaScript function from within my webpage?

I have an Iframe within my page, with the following JavaScript code: function getTotSeats(){ window.WebAppInterface.showToast(document.forms[0].txtSeat_no.value); return document.forms[0].txtSeat_no.value; } I would like to call the above Jav ...

Discovering the children of the target DOM element in React

Imagine you have an HTML unordered list that you want to turn into a React element: <ul id="mylist"> <li><a href="">Something</a></li> <li><a href="">Another thing</a></li> <li><a ...

Adjust the transparency of a navigation bar independently from the transparency of the text within the navigation bar

Seeking assistance on adjusting the opacity of this navbar without affecting the text within it. Any tips on changing the text color as well? <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#" ...

I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed. Within this component, I'm utilizing the UsersList.vue compo ...

How to implement caching using XMLHttpRequest?

As someone who has primarily relied on jQuery's AjAX method, I am relatively new to using XMLHttpRequests. However, due to performance concerns in a web worker environment, I now find myself having to resort to the classic XMLHttpRequest. Currently, ...

Restrict the quantity of items retrieved from an AJAX response

An AJAX call has returned a response consisting of a list of <a> elements: <a href="/1/">One</a> <a href="/2/">Two</a> <a href="/3/">Three</a> I am looking to select only the first n a elements from this response ...

Unlock the lightbox and send the user to the parent page

Is there a way to simultaneously launch a lightbox popup and redirect the parent page? I have an AJAX script that retrieves HTML content as a response. My goal is to display this content in a lightbox popup while also directing the parent window to a des ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Encountering the error message "OAUTH_CALLBACK_ERROR invalid_client" while trying to authenticate with a custom provider through Next

I am experimenting with NextAuth to authenticate using a custom oauth2 provider (Whoop). However, after the login process is completed on the Whoop servers and I'm redirected back to my application, NextAuth throws the following error: [next-auth][err ...

Navigate to the top of the page using Vue Router when moving to a new

Currently, in my Vue application, whenever I click on a <router-link>, it directs me to the new page but at the same scroll position as the previous one. This happens because the link only replaces the component. I am curious to know if there is a s ...