Set cache control headers for functions
Learn how to set headers to cache your function's responses.Table of Contents
By default, the Edge Network and browser will not cache, unless you set the following headers in your function as needed: Cache-Control
,CDN-Cache-Control
, and Vercel-CDN-Cache-Contol
. You can set these headers to:
- Set the cache depending on location
- Set the same cache duration everywhere
- Set caching for Vercel's Edge Cache
- Set caching for all CDNs
Setting the cache in functions takes priority over config files.
app/api/cache-control-headers/route.ts
export async function GET() {
return new Response('Cache Control example', {
status: 200,
headers: {
'Cache-Control': 'max-age=10',
'CDN-Cache-Control': 'max-age=60',
'Vercel-CDN-Cache-Control': 'max-age=3600',
},
});
}
Vercel uses the following priority when you specify multiple cache control headers:
Vercel-CDN-Cache-Control
CDN-Cache-Control
Cache-Control
This sets the same maximum cache duration for Vercel, CDNs, and the client:
app/api/cache-control-headers/route.ts
export async function GET() {
return new Response('Cache Control example', {
status: 200,
headers: {
'Cache-Control': 'max-age=3600',
},
});
}
This sets the maximum cache duration for Vercel's Edge Cache only.
app/api/cache-control-headers/route.ts
export async function GET() {
return new Response('Cache Control example', {
status: 200,
headers: {
'Vercel-CDN-Cache-Control': 'max-age=3600',
},
});
}
This sets the cache duration on Vercel and also on other CDNs
app/api/cache-control-headers/route.ts
export async function GET() {
return new Response('Cache Control example', {
status: 200,
headers: {
'CDN-Cache-Control': 'max-age=60',
},
});
}
Last updated on May 5, 2024
Was this helpful?