Next.js Discord

Discord Forum

Data Isn't Caching in server fetches

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I am currently fetching data in my server like so; however, this doesn't seem to cache globally and is using my youtube token quota up super fast. Every time I open the page on incognito again it re-fetches and uses the token. Any suggestions would be helpful. Deployed on vercel.

Edit: Maybe it’s a vercel thing because I don’t see anything inherently wrong with how I’m caching and validating data.

'use server'

const fetchVideo = async (url: string) => {

    try {
        const response = await fetch(url, { next: { revalidate: 7200 } });

        if (!response.ok) {
            console.error(response.statusText);
            return null;
        }

        const data = await response.json();

        return data;
    } catch (error) {
        console.error(error);
        return null;
    }
};

export const fetchCombinedVideos = async () => {
    const apiKey = process.env.YT_API_KEY;
    const headeddChannel = process.env.YT_HEADEDD_ID;
    const headedCSGOChannel = process.env.YT_HEADEDCSGO_ID;

    const urls = [
        `https://www.googleapis.com/youtube/v3/search?key=${apiKey}&channelId=${headeddChannel}&part=snippet&order=date&maxResults=6`,
        `https://www.googleapis.com/youtube/v3/search?key=${apiKey}&channelId=${headedCSGOChannel}&part=snippet&order=date&maxResults=6`
    ];

    const [headeddVideos, headedCSGOVideos] = await Promise.all(
        urls.map((url, index) => fetchVideo(url))
    );

    if (!headeddVideos || !headedCSGOVideos) {
        return [];
    }

    const combinedVideos = [...headeddVideos.items, ...headedCSGOVideos.items];

    combinedVideos.sort((a, b) => new Date(b.snippet.publishedAt).getTime() - new Date(a.snippet.publishedAt).getTime());

    return combinedVideos;
};

0 Replies