Next.js Discord

Discord Forum

Using absolute URLs.

Answered
zeusgmj posted this in #help-forum
Open in Discord
Hey, I have mentioned my doubt in #Fetching a custom API endpoint defined under the api folder on UI side. (https://discord.com/channels/752553802359505017/1194067555313270835/1194067555313270835). I wanted to know whether it's a good practice to use absolute URL for my use case. I fetch the data from Spotify in the route.js and then send only the necessary info or a custom response if there's no data on making a GET request to the endpoint.

The response that I receive on making a request to the endpoint is:
interface Track {
  name: string;
  artists: { name: string; link: string }[]; // Array of artist objects
  album: {
    name: string;
    link: string;
  };
  albumArt: string;
  duration: number;
  progress: number;
  isPlaying: boolean;
  link: string;
  currentlyPlayingType: string;
  uri: string;
  bgColor: string;
  textColor1: {
    hex: string,
    rgb: string[]
  };
  textColor2: {
    hex: string,
    rgb: string[]
  };
  additonalColors: string[];
  barColor: string;
}


Sorry if this isn't clear enough 😅

4 Replies

Answer
@joulev <https://nextjs-faq.com/fetch-api-in-rsc>
Oh I see. so in this case in my route.js I have it like this
import { getCurrentlyPlaying } from '../../../utils/spotify';
import { NextResponse } from 'next/server';
import { formatCurrentlyPlaying } from '../../../utils/spotify';

export async function GET(_) {

    let response = await getCurrentlyPlaying();

    if (response.status === 204 || response.status > 400) {
        return NextResponse.json(
            { isPlaying: false, noTrackData: true },
        );
    }

    if (response.currently_playing_type === 'track') {
        response = await formatCurrentlyPlaying(response);
        return NextResponse.json(
            response,
            {
                status: response.status, statusText: response.statusText, headers:
                {
                    'Content-Type': 'application/json',
                    'Cache-Control': 's-maxage=1, stale-while-revalidate'
                }
            }
        );
    } else {
        return NextResponse.json(
            { isPlaying: false, noTrackData: true },
        );
    }
}

Do I just use getCurrentlyPlaying() in the server component and render it?
Alright. Cool
Thanks!