Next.js Discord

Discord Forum

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

Answered
Chinese perch posted this in #help-forum
Open in Discord
Chinese perchOP
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?
Answered by B33fb0n3
you can't use the cache, when you have an Authorization header inside your request. You automatically opt out of the caching mechanism. However: when you wrap it with a [unstable_cache](https://nextjs.org/docs/app/api-reference/functions/unstable_cache) and pass the accesstoken as parameter, you will be able to use the cache, because only the result will be cached
View full answer

5 Replies

@Chinese perch I have a GET route handler that makes a fetch request to an external API like this: ts 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?
you can't use the cache, when you have an Authorization header inside your request. You automatically opt out of the caching mechanism. However: when you wrap it with a [unstable_cache](https://nextjs.org/docs/app/api-reference/functions/unstable_cache) and pass the accesstoken as parameter, you will be able to use the cache, because only the result will be cached
Answer
Chinese perchOP
@B33fb0n3 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,
});
@Chinese perch solved?