DEV Community

Cover image for How to use Spotify API with Next.js

How to use Spotify API with Next.js

Jatin Sharma on May 12, 2022

On my website, there is a stats page, which showcases many things such as my Dev.to blog stats and the GitHub repository count and the Spotify stat...
Collapse
 
robbiecren07 profile image
Robbie Crenshaw

When you went to production, did you have issues with the API getting a 500? It works fine on localhost. I even went through the steps for the refresh token again using the production domain and added the production website/callback in Spotify developer console. Did you have to make any code modifications for it to work in production? I'm deployed on Vercel using Nextjs.

Collapse
 
j471n profile image
Jatin Sharma • Edited

I am using the same code for production as well. I am just using swr package to fetch the data. And i didn't face any issues.

Feel free to go through the code. And if you wanna discuss this matter in details DM me on twitter

Collapse
 
xoboid profile image
xoboid

I found the app router stuff complicated and ended up using good old useState and useEffect

Collapse
 
robbiecren07 profile image
Robbie Crenshaw

I think I figured it out, I originally tweaked the code a little bit to use Nextjs Edge API Routes and I guess that is what was causing the issue.

Thread Thread
 
j471n profile image
Jatin Sharma

Thanks great 👍

Collapse
 
jaredycw profile image
Jared Yeung • Edited

Hello, It's very clear.
Your example was done in Page router (/Page/... js /ts)
However, do you know how to do it in App router?
I don't know why in localhost, it displayed

This page isn’t working If the problem continues, contact the site owner.
HTTP ERROR 405

Collapse
 
j471n profile image
Jatin Sharma

Hello,

I haven't use this in app router, however I am using API routes and then fetching the data on the client side.

But in next.js app router they have client components and server components, data fetching will be based on that.

You can follow the swr guide which should help you to get through this problem.

Collapse
 
jaredycw profile image
Jared Yeung

Thanks so much, I will try this in app router, it seems difficult in NextJS 13.4.

Thread Thread
 
j471n profile image
Jatin Sharma

They have changed a lot of things, so it's little complicated but not impossible. I think if you use client side rendering and use swr it should work.

Thread Thread
 
jaredycw profile image
Jared Yeung

Thanks Jatin, I just figured it out in App router.

Thread Thread
 
j471n profile image
Jatin Sharma

That's amazing, if you could share the code here... That will be helpful for the other readers ✌🏻

Thread Thread
 
jaredycw profile image
Jared Yeung • Edited

Beside App Router issue,
I found out that .env.local file (in my case) is not worked, the env code is needed to add into the next.config.js file (/root) once you have pasted all the key in .env.local.file (I dont know it's common in this issue, coz Im new in NextJS.)

const nextConfig = {

      reactStrictMode: true,
        env: {
            SPOTIFY_REFRESH_TOKEN: process.env.SPOTIFY_REFRESH_TOKEN,
        SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET,
        SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID,

          }

}

module.exports = nextConfig

Enter fullscreen mode Exit fullscreen mode

For lib/spotify.js file, It's the same, no need to change.

Only the API file is different, it's needed to create route.
Eg. the path and file is changed from "pages/api/stats/tracks.js (page router) to "app/api/tracks/router.js"(app router)
...
changed from "pages/api/stats/artists.js (page router) to "app/api/artists/router.js"(app router)

For the api/track.ts file script,


import { topTracks } from '@/app/lib/spotify';

 // In order to fix HTTP method / async,  changed from "export default async function handler(req, res)" to "export async function GET() "


export async function GET() {
  const response = await topTracks();
  const { items } = await response.json();

  const tracks = items.slice(0, 10).map((track) => ({
    artist: track.artists.map((_artist) => _artist.name).join(', '),
    songUrl: track.external_urls.spotify,
    coverImage: track.album.images[1],
    title: track.name
  }));

  return new Response(JSON.stringify({ tracks }), {
    status: 200,
    headers: {
      'content-type': 'application/json',
      'cache-control': 'public, s-maxage=86400, stale-while-revalidate=43200'
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

localhost:3000/api/stats/tracks

lastly, use swr to fetch the api file

**tested in nextjs 13, using typescript

Thread Thread
 
j471n profile image
Jatin Sharma

Thanks mate.

Collapse
 
vulcanwm profile image
Medea

thanks for this tutorial!
just found it right now and it really helps!

Collapse
 
j471n profile image
Jatin Sharma

I am glad it helped.