Data caching when fetch request uses cookies
Answered
American Sable posted this in #help-forum
American SableOP
From what I understand (from https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching), if your fetch request uses cookies, data will not be cached. So if I need to pass, say, a session cookie or an access token from a server component for every API request, data will never be cached?
Example:
Example:
import { cookies } from 'next/headers';
export default async function ServerComponent() {
// always cache miss
const res = await fetch(url, {
headers: { cookie: cookies().toString() }
});
...
}Answered by DirtyCajunRice | AppDir
you can cache fetch. just set revalidate. the page will be dynamic.
3 Replies
@American Sable From what I understand (from https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching), if your fetch request uses cookies, data will not be cached. So if I need to pass, say, a session cookie or an access token from a server component for every API request, data will never be cached?
Example:
typescript
import { cookies } from 'next/headers';
export default async function ServerComponent() {
// always cache miss
const res = await fetch(url, {
headers: { cookie: cookies().toString() }
});
...
}
you can cache fetch. just set revalidate. the page will be dynamic.
Answer
American SableOP
Can you point me to an example? I thought revalidate means to purge the cache
Oh ok, I see. So you mean like this. Just tried it, it works.
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#time-based-revalidation
fetch('https://...', { next: { revalidate: 3600 } })https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#time-based-revalidation