#How to make Nextjs/Vercel cache 'fetch' results based only on URL?

7 messages · Page 1 of 1 (latest)

candid aurora
#

I have a GET route handler that makes a fetch request to an external API like this:

fetch(url, {
    headers: { Authorization: `Bearer ${accessToken}` },
    next: {
        revalidate: ONE_WEEK_IN_SECONDS,
    },
});

Since accessToken changes every hour I'm assuming I'll get a cache miss for the same URL after an hour? If so how can I get cached results in this case?

viral patrolBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

bitter sequoia
candid aurora
#

@bitter sequoia Thanks for the suggestion. I looked into the docs for unstable_cache, will this code work as expected and cache the result of fetchGenres() for one week?

async function fetchGenres() {
    const url = '';
    const accessToken = await getAccessToken();
    const res = await fetch(url, {
        headers: { Authorization: `Bearer ${accessToken}` },
    });
    const data = await res.json();
    return data.genres;
}

const ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7;

const getCachedGenres = unstable_cache(async () => fetchGenres(), ['cached-genres'], {
    revalidate: ONE_WEEK_IN_SECONDS,
});
bitter sequoia
bitter sequoia
#

@candid aurora solved?

viral patrolBOT