Trying to get current track in spotify using route handlers of app directory
Answered
Northern Wheatear posted this in #help-forum
Northern WheatearOP
Hi, I was trying to create a route handler to get my current track playing on spotify. And this is working well while running the dev server and a send requests to that api I created from postman.
This is how it works currently...
1. I have the my refresh token with me stored in an env
2. I will request for my access token using spotify's api (which works) with fetch and setting revalidate as 3600 (1hr)
3. I then request the current playing api from spotify with the access token received in the previous request with fetch and setting revalidate as 0
4. Then i will send back the data with the relevant track details that I need from the previous response
So the problem is.... As I've mentioned earlier it works well with postman(dev server). While fetching this from my frontend using SWR the cache that I have set for 1 hr for the api token doesn't hit and new apitoken is being fetched with each request from the frontend. The next interesting case is both these requests are cached forever while running it in production, both from frontend and postman. What is going on here... I will post my api code here
This is how it works currently...
1. I have the my refresh token with me stored in an env
2. I will request for my access token using spotify's api (which works) with fetch and setting revalidate as 3600 (1hr)
3. I then request the current playing api from spotify with the access token received in the previous request with fetch and setting revalidate as 0
4. Then i will send back the data with the relevant track details that I need from the previous response
So the problem is.... As I've mentioned earlier it works well with postman(dev server). While fetching this from my frontend using SWR the cache that I have set for 1 hr for the api token doesn't hit and new apitoken is being fetched with each request from the frontend. The next interesting case is both these requests are cached forever while running it in production, both from frontend and postman. What is going on here... I will post my api code here
Answered by Ray
export const dynamic = 'force-dynamic';
export async function GET() {
const accessToken = await getAccessToken();
if (accessToken) {
const track = await getCurrentTrack(accessToken);
console.log(accessToken);
return NextResponse.json({
name: track.item.name,
artists: track.item.artists.map((artist: any) => {
return { name: artist.name, href: artist.external_urls.spotify };
}),
href: track.item.external_urls.spotify,
image: track.item.album.images[0],
});
} else {
return NextResponse.json(
{ error: 'Error fetching access token' },
{ status: 500 }
);
}
}GET endpoint is static by default
6 Replies
Northern WheatearOP
import { NextResponse } from 'next/server';
async function getAccessToken() {
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
const urlencoded = new URLSearchParams();
urlencoded.append('client_id', process.env.SPOTIFY_CLIENT_ID);
urlencoded.append('client_secret', process.env.SPOTIFY_CLIENT_SECRET);
urlencoded.append('grant_type', 'refresh_token');
urlencoded.append('refresh_token', process.env.SPOTIFY_REFRESH_TOKEN);
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
next: { revalidate: 3600 },
};
try {
const response = await fetch(
'https://accounts.spotify.com/api/token',
requestOptions
);
const data = await response.json();
return data.access_token;
} catch (err) {
console.error(err);
return null;
}
}
async function getCurrentTrack(accessToken: string) {
const myHeaders = new Headers();
myHeaders.append('Authorization', `Bearer ${accessToken}}`);
const requestOptions = {
method: 'GET',
headers: myHeaders,
next: { revalidate: 0 },
};
try {
const response = await fetch(
'https://api.spotify.com/v1/me/player/currently-playing',
requestOptions
);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
return null;
}
}export async function GET() {
const accessToken = await getAccessToken();
if (accessToken) {
const track = await getCurrentTrack(accessToken);
console.log(accessToken);
return NextResponse.json({
name: track.item.name,
artists: track.item.artists.map((artist: any) => {
return { name: artist.name, href: artist.external_urls.spotify };
}),
href: track.item.external_urls.spotify,
image: track.item.album.images[0],
});
} else {
return NextResponse.json(
{ error: 'Error fetching access token' },
{ status: 500 }
);
}
}@Northern Wheatear
import { NextResponse } from 'next/server';
async function getAccessToken() {
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
const urlencoded = new URLSearchParams();
urlencoded.append('client_id', process.env.SPOTIFY_CLIENT_ID);
urlencoded.append('client_secret', process.env.SPOTIFY_CLIENT_SECRET);
urlencoded.append('grant_type', 'refresh_token');
urlencoded.append('refresh_token', process.env.SPOTIFY_REFRESH_TOKEN);
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
next: { revalidate: 3600 },
};
try {
const response = await fetch(
'https://accounts.spotify.com/api/token',
requestOptions
);
const data = await response.json();
return data.access_token;
} catch (err) {
console.error(err);
return null;
}
}
async function getCurrentTrack(accessToken: string) {
const myHeaders = new Headers();
myHeaders.append('Authorization', `Bearer ${accessToken}}`);
const requestOptions = {
method: 'GET',
headers: myHeaders,
next: { revalidate: 0 },
};
try {
const response = await fetch(
'https://api.spotify.com/v1/me/player/currently-playing',
requestOptions
);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
return null;
}
}
export const dynamic = 'force-dynamic';
export async function GET() {
const accessToken = await getAccessToken();
if (accessToken) {
const track = await getCurrentTrack(accessToken);
console.log(accessToken);
return NextResponse.json({
name: track.item.name,
artists: track.item.artists.map((artist: any) => {
return { name: artist.name, href: artist.external_urls.spotify };
}),
href: track.item.external_urls.spotify,
image: track.item.album.images[0],
});
} else {
return NextResponse.json(
{ error: 'Error fetching access token' },
{ status: 500 }
);
}
}GET endpoint is static by default
Answer
Northern WheatearOP
@Giant Chinchilla sorry for the late reply... Yes I was able to solve this using the method Ray mentioned... GET endpoint was getting cached