netlify-caching
netlify/context-and-tools
Functions, Edge Functions 및 프록시에서 생성된 동적 및 정적 응답을 Netlify의 CDN에 캐시합니다. 함수 응답에 캐싱 또는 캐시 제어 헤더를 추가하거나, 캐시 TTL 또는 stale-while-revalidate를 조정하거나, 내구성 캐시를 설정하거나, 쿼리/헤더/쿠키/국가/언어에 따라 캐시 키를 변경하거나, 사이트 또는 캐시 태그별로 캐시를 삭제하거나 무효화하거나, 프로그래밍 방식의 Cache API (caches.open/match/put) 또는 @netlify/cache 헬퍼(fetchWithCache/cacheHeaders/getCacheStatus)를 사용하거나, 처리 비용이 많이 드는 API의 속도를 높이고자 할 때 사용합니다.
...모든 것을 확장하십시오netlify-caching 소개
이 스킬은 Functions, Edge Functions 및 프록시를 통해 Netlify의 CDN에 동적 및 정적 응답을 캐싱하는 방법에 대한 실용적인 참고 자료입니다. 이 스킬은 동적 응답이 기본적으로 캐싱되지 않는 문제와 다양한 캐시 제어 헤더가 미묘하게 다르게 동작하는 문제를 해결합니다: 이 스킬은 에이전트에게 ‘Netlify-CDN-Cache-Control’을 참조하도록 지시하며, 이것이 ‘CDN-Cache-Control’ 및 표준 ‘Cache-Control’과 어떻게 관련되는지 설명하고, 지시어(public/private/no-store, s-maxage, max-age, stale-while-revalidate, durable)와 그 기본값을 나열합니다.
실제 환경에서 자주 발생하는 함정 사례들을 집중적으로 다룹니다: GET 요청만 캐시되며, Netlify 개발 환경은 CDN 캐시를 에뮬레이션하지 않으므로 배포된 URL에서 Cache-Status 헤더를 통해 캐싱 여부를 확인해야 하고, Netlify-Vary로 범위를 지정하지 않는 한 전체 쿼리 문자열이 캐시 키가 되며, 정적 자산은 최대 1년까지 최신 상태를 유지하며, 어떤 페이지에서든 basic-auth가 적용되면 사이트 전체의 캐싱이 비활성화되며, durable은 서버리스 환경에서만 지원됩니다. 또한 Netlify-Vary를 통한 캐시 키 변형(쿼리, 헤더, 언어, 국가, 쿠키 기준)과 Netlify-Cache-Tag 및 Netlify-Cache-ID를 통한 캐시 태깅 및 옵트아웃, 배포된 함수에서 purgeCache를 사용한 온디맨드 삭제, 태그별 삭제, Lambda 호환 함수를 통한 삭제, 또는 직접 HTTP 삭제 API를 통한 삭제 등에 대해 설명하고 있습니다.
이 스킬의 대상 사용자는 CDN 성능을 조정하거나, ISR(인라인 캐시 재설정) 및 온디맨드 재검증을 추가하거나, 응답이 캐시되거나 캐시되지 않는 원인을 디버깅하는 웹 및 풀스택 개발자입니다. 이 스킬은 보안에 신경을 쓰고 있습니다. 함수 외부에서 캐시를 삭제할 때 개인 액세스 토큰은 환경 변수에서 읽어야 하며 절대 하드코딩해서는 안 된다고 명시하고 있으며, 민감한 콘텐츠에 대해 자동 캐시 무효화를 해제하지 말 것을 경고하므로 안전합니다.
자주 묻는 질문
동적 함수 응답이 캐시되지 않는 이유는 무엇인가요?
동적 응답은 기본적으로 캐시되지 않으며, 오직 GET 요청만 캐시됩니다. 응답에 Netlify-CDN-Cache-Control을 설정하고, GET 경로를 통해 캐시 가능한 데이터를 노출시켜야 캐시가 활성화됩니다.
로컬에서 테스트할 때 캐시 미스가 발생하는 이유는 무엇인가요?
netlify dev는 CDN 캐시를 에뮬레이션하지 않으므로, 로컬에서는 매번 캐시 미스가 발생하는 것이 정상입니다. 배포된 Deploy Preview 또는 프로덕션 URL에서 Cache-Status 헤더를 확인하여 캐싱 상태를 검증하십시오.
모든 쿼리 문자열이 별도의 캐시 항목을 생성하지 않도록 하려면 어떻게 해야 하나요?
Netlify-Vary가 없으면 전체 쿼리 문자열이 캐시 키가 되므로, utm_*와 같은 매개변수는 각각 별도의 항목을 생성합니다. Netlify-Vary: query=...를 사용하여 응답을 실제로 변경하는 매개변수만 열거하십시오.
캐시를 삭제하거나 무효화하려면 어떻게 해야 합니까?
배포된 함수에서 purgeCache를 사용하세요(사이트 ID는 자동으로 전달됨). 선택적으로 태그를 지정하거나 배포 별칭/도메인을 대상으로 지정할 수 있습니다. CI 또는 로컬 스크립트에서는 환경 변수에서 읽은 개인 액세스 토큰과 사이트 ID를 전달하거나, 직접 HTTP 퍼지 API를 호출하세요.
캐싱을 완전히 비활성화하는 함정이 있나요?
네. 어떤 페이지에서든 basic-auth가 적용되면 사이트 전체의 캐싱이 비활성화되며, durable은 Edge Function 응답에 영향을 미치지 않고, 레거시 온디맨드 빌더(ODB)는 이러한 헤더를 지원하지 않습니다. 이 스킬은 새로운 코드에서 ODB 사용을 권장하지 않습니다.
Cache-control header to reach for
Dynamic responses (Functions, Edge Functions, proxies) are NOT cached by default — you must opt in. Set Netlify-CDN-Cache-Control on the response:
import type { Context } from "@netlify/functions";export default async (req: Request, context: Context) => { return new Response("Hello world", { headers: { 'Netlify-CDN-Cache-Control': 'public, durable, max-age=60, stale-while-revalidate=120' } });};
Header choice (most specific wins; CDN-Cache-Control/Cache-Control always pass downstream):
Netlify-CDN-Cache-Control— Netlify CDN only. Reach for this.CDN-Cache-Control— all CDNs that support it.Cache-Control— any CDN or the browser.
Legacy path to avoid: On-demand Builders do not support these headers or Netlify-Vary — they use a TTL pattern and key on URL path only. Don't reach for ODBs in new code.
Footguns (read first)
- Only
GETis cached. POST/PUT/etc. are never cached regardless of headers — expose cacheable data on a GET route (inputs in the URL or query string). netlify devdoes not emulate the CDN cache. A local cache miss every time is expected. Verify caching on a deployed URL (Deploy Preview or production) via itsCache-Statusheader.- Without
Netlify-Vary: query=..., the full query string is the cache key — every distinct query string (utm_*,fbclid, …) is a separate cache entry. Enumerate only the params that change the response. - Static assets are fresh for up to a year — a shorter
max-ageis ignored. They change only on a new deploy or manual purge. - basic-auth on ANY page disables caching for the ENTIRE site.
durableis serverless-only — it has no effect on Edge Function responses.- Never opt sensitive content out of automatic invalidation — it can stay publicly cached after deploys/firewall changes.
Directives
publiccache it /privatebrowser-only, not Netlify's shared cache /no-storedon't cache.s-maxage=Nseconds in Netlify's shared cache (overridesmax-agethere).max-age=Nseconds in any cache.stale-while-revalidate=Nserve stale for N seconds after expiry while revalidating in background.durable(serverless only) store in Netlify's durable cache so other edge nodes reuse it instead of re-invoking the function.
Defaults when no header is set — static: Netlify-CDN-Cache-Control: public, s-maxage=31536000, must-revalidate; dynamic: Cache-Control: public, max-age=0, must-revalidate.
Cache key variation — Netlify-Vary
Comma-delimited instructions on the response; pipe-delimited value lists:
Netlify-Vary: query=item_id|page, country=es+de|us, cookie=ab_test|is_logged_inquery=a|bsubset, or barequeryfor all params. Keys case-sensitive; param order irrelevant.header=Device-Type|App-Version— custom + most standard headers.language=en|es+pt—+groups; checked againstAccept-Languagewith quality weighting.country=us|es+pt— GeoIP, ISO 3166-1 two-letter codes;+groups.cookie=ab_test|is_logged_in— target specific keys, not the wholeCookieheader.
Cannot vary by header on: Accept*, Cache-Control, Connection, Content-Length, Cookie, Host, If-*, Range, Referer, Upgrade, User-Agent. For language/cookie/format use Vary: Accept-Language/Vary: Cookie or the specific Netlify-Vary instruction.
Consistency rule: a URL must return the same Netlify-Vary on every response — the first cached response's instructions win and later ones are ignored. Netlify-Vary + standard Vary are both respected (use Vary for format/encoding, and to pass instructions to an upstream CDN like Cloudflare).
Cache tags & opt-out
Tag responses for taggable purging:
Netlify-Cache-Tag: tag1,tag2,tag3Netlify-Cache-Tag(Netlify CDN) wins overCache-Tag(passed downstream). Some providers stripCache-Tag— set both when proxying through them.- Constraints: case-insensitive, UTF-8 only, ≤1024 chars/tag, ≤500 tags/response.
Opt a response out of automatic atomic-deploy invalidation with Netlify-Cache-ID (comma-separated; auto-registered as cache tags for purging; separate 500-ID limit):
Netlify-Cache-ID: cms-proxy,product,imageAfter opting out, purge on-demand after relevant changes (e.g. redirect/proxy or function changes behind a Netlify-Cache-ID).
On-demand invalidation (purge)
Purge from a deployed function with purgeCache (site ID is passed automatically):
import { purgeCache } from "@netlify/functions";export default async () => { await purgeCache(); // no args = purge everything for the site return new Response("Purged!", { status: 202 });};
Purge by tag, optionally targeting a deploy/subdomain:
import { purgeCache } from "@netlify/functions";export default async (req: Request) => { const cacheTag = new URL(req.url).searchParams.get("tag"); if (!cacheTag) return; await purgeCache({ tags: [cacheTag], deployAlias: "deploy-preview-11", domain: "early-access.company.com", }); return new Response("Purged!", { status: 202 });};
Ambient credentials only work inside a deployed function. From CI, local scripts, or the build, pass token (a personal access token read from an env var — never hardcoded) and siteID.
Lambda-compatible functions use the legacy module.exports.handler = async (event, context) => {…} signature and must pass context.clientContext.custom.purge_api_token:
import { purgeCache } from "@netlify/functions";module.exports.handler = async (event, context) => { const token = context.clientContext.custom.purge_api_token; await purgeCache({ tags: ["tag1", "tag2"], token }); return { body: "Purged!", statusCode: 202 };};
Direct API (from outside a function) — POST https://api.netlify.com/api/v1/purge with Authorization: Bearer <personal_access_token> and Content-Type: application/json:
curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <personal_access_token>" \ --data '{"site_slug": "mysitename", "cache_tags": ["news"], "deploy_alias": "deploy-preview-11", "domain": "early-access.company.com"}' \ 'https://api.netlify.com/api/v1/purge'
- Purge by site:
site_idorsite_slug. By tag:cache_tags+ site. Omittingcache_tagspurges the whole site; an emptycache_tagslist purges NOTHING. - Identifier mapping: in the UI (Project configuration > General > Project details), Project ID =
site_id, Project name =site_slug. See https://docs.netlify.com/api-and-cli-guides/api-guides/get-started-with-api#get-site. - Rate limit: each tag or site can be purged only twice per 5s — exceeding returns
429.
Cache API (caches global)
Programmatic read/write of HTTP responses from Functions/Edge Functions. Use for caching individual components of a route or arbitrary fetches, alongside header-based route caching.
Scope rule: caches.open() anywhere, but match/put/delete only inside the request handler — doing them at module/global scope throws.
import type { Config, Context } from "@netlify/functions";const cache = await caches.open("my-cache"); // ok in global scopeexport default async (req: Request, context: Context) => { const request = new Request("https://example.com/expensive-api"); const cached = await cache.match(request); if (cached) return cached; const fresh = await fetch(request); if (fresh.ok) { cache.put(request, fresh.clone()).catch((error) => { console.error("Failed to add to the cache:", error); }); } return fresh;};export const config: Config = { path: "/cache-api-example" };
CacheStorage subset:
caches.match(request)→Responsefrom any cache, orundefined.caches.open(name)→Cache. Distinct names fragment the cache and lower hit ratio — use few, meaningful names.
Cache methods (all require caches.open()):
cache.match(request)→Response|undefined.cache.put(request, response)→ adds a response.cache.add(request)/cache.addAll(requests)→ fetch + store.cache.delete(request)→true.keys()is not implemented — no way to list contents.
Consistency: reads/writes strongly consistent; deletes eventually consistent (a deleted entry may still return briefly).
Cannot cache: partial responses (206), Vary: *, or non-GET methods. Responses need a cache-control header with max-age/s-maxage ≥ 1s, public (not private/no-cache/no-store), and a 2xx status — otherwise storage errors. For responses you don't control, rewrite headers with fetchWithCache.
Limits per invocation: 100 lookups, 20 insertions/deletions. Exceeding: further lookups return nothing; writes/deletes no-op. Limits are shared across edge functions in a request but separate between serverless and edge functions. Cache data is per-region (not replicated), auto-invalidated on redeploy and on max-age/s-maxage expiry.
@netlify/cache module
Install to get helpers, time constants (MINUTE/HOUR/DAY), and a caches export for local dev:
npm install @netlify/cacheLocal-dev workaround: the caches global isn't part of Node.js. Netlify provides it in its Functions/Edge runtimes (live and under netlify dev), but if you run your framework's own dev server the global is undefined and throws — import it instead:
import { caches } from "@netlify/cache";const cache = await caches.open("my-cache");
Requires Netlify CLI 20.0.3+; nothing persists locally (lookups return nothing, writes/deletes don't mutate). No functional change from the global.
cacheHeaders(settings) → header object
import { cacheHeaders, DAY } from "@netlify/cache";const headers = { "x-custom-header": "some value", ...cacheHeaders({ ttl: 2 * DAY, // s-maxage swr: HOUR, // stale-while-revalidate durable: true, tags: ["product", "sale"], overrideDeployRevalidation: ["tag"], // opt out of atomic-deploy invalidation vary: { cookie: ["ab_test_name", "ab_test_bucket"], query: ["item_id", "page"], // or true for all country: ["us", ["es", "pt"]], // nested = OR language: ["en"], header: ["Device-Type"], }, }),};
For only generic (non-Netlify) headers, use the cdn-cache-control npm module instead.
fetchWithCache(resource, options?, cacheSettings?)
Drop-in fetch that returns a cached response or fetches, stores, and returns. cacheSettings override conflicting response headers; with swr, background revalidation is handled automatically.
import { fetchWithCache, DAY } from "@netlify/cache";const response = await fetchWithCache("https://example.com/expensive-api", { ttl: 2 * DAY, tags: ["product", "sale"], vary: { cookie: ["ab_test_name"], query: ["item_id", "page"] },});
getCacheStatus(response | headers | headerString)
Returns { hit, caches: { durable: { hit, stale, stored, ttl }, edge: { hit, stale } } }.
const { hit, edge, durable } = getCacheStatus(response);
needsRevalidation(response) → boolean
Only needed when calling cache.match/cache.put directly (not with fetchWithCache+swr). True when a Cache-API response is stale within its SWR window — return it, then revalidate in context.waitUntil and cache.put the fresh copy:
if (cached) { if (needsRevalidation(cached)) { context.waitUntil( fetch(request).then((fresh) => { const response = new Response(fresh.body, { headers: { ...Object.fromEntries(fresh.headers), ...cacheHeaders({ ttl: MINUTE, swr: HOUR }) }, }); return cache.put(request, response); }) ); } return cached;}
Durable cache
Add durable (serverless only) so edge nodes lacking a local copy check the shared durable cache before invoking the function — fewer invocations, better cache-miss latency. Eventually consistent, so multiple regions may still invoke the function a few times per version. Co-located with the site's functions region. Works with Netlify-Vary, SWR, and on-demand invalidation. Next.js: Next Runtime 5.5.0+ uses the durable cache automatically.
Debugging with Cache-Status
Netlify sets Cache-Status (RFC 9211) on all responses. Check it on a deployed URL. Look for values starting "Netlify Edge" or "Netlify Durable":
"Netlify Edge"; fwd=miss— nothing cached."Netlify Edge"; hit— served from cache."Netlify Edge"; hit; fwd=stale— stale served while revalidating (SWR).- Durable stored on miss:
"Netlify Durable"; fwd=uri-miss; stored=true; ttl=3600. - Durable hit:
"Netlify Durable"; hit; ttl=1234.
ttl negative = seconds since expiry. Each request may hit a different cache instance — without production traffic or durable, expect several empty caches before a hit; repeat requests to warm one.
Netlify house rules (caching)
These are org conventions, not docs facts — merged into the rendered skill byctx-gen and never generated. Owned by the skills maintainer.
- Only
GETresponses are cached by the CDN.POST/PUT/etc. are nevercached regardless of headers — expose cacheable data on aGETroute(put the inputs in the URL or query string). - Without
Netlify-Vary: query=..., the full query string is the cache key —every distinct query string (utm_*,fbclid, ...) is a separate cacheentry. Enumerate only the params that actually change the response. netlify devdoes not emulate the CDN cache — a cache miss every timelocally is expected, not a bug. Verify caching behavior on a deployed URL(Deploy Preview or production) via itsCache-Statusheader.purgeCache()has ambient credentials only inside a deployed function.From CI, local scripts, or the build, passtoken(a personal accesstoken read from an env var, never hardcoded) andsiteID.
모든 파일
0개 파일netlify-caching 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/netlify/context-and-tools/blob/main/skills/netlify-caching/SKILL.md # Copy SKILL.md to your .claude/skills/ directory
복사





집
