-
Notifications
You must be signed in to change notification settings - Fork 313
Expand file tree
/
Copy pathcache-headers-fix.patch
More file actions
182 lines (182 loc) · 8.08 KB
/
Copy pathcache-headers-fix.patch
File metadata and controls
182 lines (182 loc) · 8.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
diff --git a/next.config.cache-headers.test.ts b/next.config.cache-headers.test.ts
new file mode 100644
index 0000000..0a039dd
--- /dev/null
+++ b/next.config.cache-headers.test.ts
@@ -0,0 +1,130 @@
+/**
+ * Regression tests for the Cache-Control header rules in `next.config.ts` (#326).
+ *
+ * Next applies *every* matching header rule in array order and a later rule wins
+ * for the same key, so an unscoped catch-all `source` on the HTML
+ * `max-age=0, must-revalidate` rule silently clobbered the long-lived
+ * `Cache-Control` set for `/_next/static/**` (immutable) and `/static/**` (7 days).
+ *
+ * These tests compile the real rules with Next's own route builder + matcher (no
+ * re-implementation of Next semantics) and assert that exactly one
+ * `Cache-Control` rule matches any given path.
+ */
+import { describe, expect, it } from 'vitest';
+import { buildCustomRoute } from 'next/dist/lib/build-custom-route';
+import { getRouteMatcher } from 'next/dist/shared/lib/router/utils/route-matcher';
+import nextConfig from './next.config';
+
+type HeaderRule = { source: string; headers: { key: string; value: string }[] };
+
+const IMMUTABLE = 'public, max-age=31536000, immutable';
+const WEEK = 'public, max-age=604800, stale-while-revalidate=86400';
+const REVALIDATE = 'public, max-age=0, must-revalidate';
+
+async function getHeaderRules(): Promise<HeaderRule[]> {
+ const rules = await nextConfig.headers!();
+ return rules as unknown as HeaderRule[];
+}
+
+/** Compile a rule the way Next does, and return a pathname matcher. */
+function matcherFor(source: string) {
+ const route = buildCustomRoute('header', { source, headers: [] });
+ const re = new RegExp(route.regex, 'i');
+ return getRouteMatcher({ re, groups: {} });
+}
+
+/** Which rules would set Cache-Control for `pathname`, in array order. */
+async function cacheControlRulesFor(pathname: string): Promise<string[]> {
+ const rules = await getHeaderRules();
+ return rules
+ .filter((rule) => matcherFor(rule.source)(pathname) !== false)
+ .filter((rule) => rule.headers.some((header) => header.key === 'Cache-Control'))
+ .map((rule) => rule.headers.find((header) => header.key === 'Cache-Control')!.value);
+}
+
+async function effectiveCacheControl(pathname: string): Promise<string | undefined> {
+ const matches = await cacheControlRulesFor(pathname);
+ return matches[matches.length - 1];
+}
+
+const PAGES = [
+ '/',
+ '/dashboard',
+ '/courses/react',
+ '/instructor/classes',
+ '/profile',
+ '/api/health',
+];
+const NEXT_ASSETS = [
+ '/_next/static/chunks/main-app-a1b2c3.js',
+ '/_next/static/css/4e5f6a7b.css',
+ '/_next/static/media/logo.abc123.svg',
+];
+const PUBLIC_ASSETS = ['/static/img/logo.png', '/static/fonts/inter.woff2'];
+
+describe('next.config headers() – Cache-Control scoping (#326)', () => {
+ it('does not let the HTML rule overlap static asset routes', async () => {
+ const paths = [...PAGES, ...NEXT_ASSETS, ...PUBLIC_ASSETS, '/favicon.ico', '/_next/image'];
+
+ for (const pathname of paths) {
+ const matches = await cacheControlRulesFor(pathname);
+ expect(
+ matches.length,
+ `${pathname} matched ${matches.length} Cache-Control rules`,
+ ).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it.each(NEXT_ASSETS)('keeps hashed assets immutable: %s', async (pathname) => {
+ await expect(effectiveCacheControl(pathname)).resolves.toBe(IMMUTABLE);
+ });
+
+ it.each(PUBLIC_ASSETS)('keeps public assets cached for 7 days: %s', async (pathname) => {
+ await expect(effectiveCacheControl(pathname)).resolves.toBe(WEEK);
+ });
+
+ it.each(PAGES)('revalidates HTML pages: %s', async (pathname) => {
+ await expect(effectiveCacheControl(pathname)).resolves.toBe(REVALIDATE);
+ });
+
+ it('scopes the HTML rule instead of using a bare catch-all source', async () => {
+ const rules = await getHeaderRules();
+ const htmlRule = rules.find((rule) =>
+ rule.headers.some((header) => header.value === REVALIDATE),
+ );
+
+ expect(htmlRule, 'no rule sets the HTML revalidation header').toBeDefined();
+ // A catch-all like '/(.*)' or '/:path*' matches every URL, including assets.
+ expect(htmlRule!.source).not.toBe('/:path*');
+ expect(htmlRule!.source).not.toBe('/(.*)');
+ expect(matcherFor(htmlRule!.source)('/_next/static/chunks/main-abc123.js')).toBe(false);
+ expect(matcherFor(htmlRule!.source)('/static/img/logo.png')).toBe(false);
+ });
+
+ it('still revalidates routes that merely share a prefix with the excluded ones', async () => {
+ // Guards against an over-broad exclusion such as `(?!static)` or `(?!_next)`.
+ await expect(effectiveCacheControl('/static-assets/app.js')).resolves.toBe(REVALIDATE);
+ await expect(effectiveCacheControl('/_nextjs/config')).resolves.toBe(REVALIDATE);
+ await expect(effectiveCacheControl('/statistics')).resolves.toBe(REVALIDATE);
+ });
+
+ it('leaves Next-owned /_next routes to Next defaults', async () => {
+ // /_next/image and /_next/data get their Cache-Control from Next itself;
+ // overriding it with must-revalidate would defeat the image CDN cache.
+ await expect(effectiveCacheControl('/_next/image')).resolves.toBeUndefined();
+ await expect(effectiveCacheControl('/_next/data/abc123/index.json')).resolves.toBeUndefined();
+ });
+
+ it('still applies the site-wide security headers to assets and pages alike', async () => {
+ const rules = await getHeaderRules();
+ const security = rules[0];
+
+ expect(security.source).toBe('/(.*)');
+ expect(security.headers.map((header) => header.key)).toContain('X-Frame-Options');
+ expect(matcherFor(security.source)('/_next/static/chunks/main-abc123.js')).not.toBe(false);
+ expect(matcherFor(security.source)('/dashboard')).not.toBe(false);
+ // The broad rule must never carry Cache-Control, otherwise it competes with
+ // the specific rules above again.
+ expect(security.headers.some((header) => header.key === 'Cache-Control')).toBe(false);
+ });
+});
diff --git a/next.config.ts b/next.config.ts
index 5ef4af5..d0e96b9 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -28,6 +28,26 @@ const nextConfig: NextConfig = {
// We add long-lived cache headers for those immutable assets and a
// short revalidation window for HTML pages so users never see stale UI.
async headers() {
+ // Next applies *every* matching header rule in array order (later rules win
+ // for the same key), so a catch-all `source` on the HTML rule overlapped the
+ // hashed-asset rules below and clobbered their `Cache-Control`.
+ //
+ // `htmlSource` scopes the HTML rule with a negative lookahead so it can never
+ // match Next's own internal/immutable routes (`/_next/…`, which covers
+ // `/_next/static/…`, `/_next/image` and `/_next/data`) or the public
+ // `static/` asset prefix. Anything that is not those prefixes is a page and
+ // still gets `max-age=0, must-revalidate`.
+ //
+ // The `(?:/|$)` tails matter: they make each exclusion cover the whole
+ // prefix *and* every path under it, while never excluding look-alike routes
+ // that merely start with the same letters (`/static-assets`, `/_nextjs`),
+ // which must keep revalidating.
+ //
+ // NOTE: the lookahead sits right after the `/` the `source` prefix supplies,
+ // so excluded segments are written *without* their leading slash.
+ const htmlExcludedPrefixes = ['_next(?:/|$)', 'static(?:/|$)'];
+ const htmlSource = `/((?!${htmlExcludedPrefixes.join('|')}).*)`;
+
return [
{
source: '/(.*)',
@@ -63,8 +83,12 @@ const nextConfig: NextConfig = {
],
},
{
- // HTML pages – always revalidate so deployments are picked up quickly
- source: '/:path*',
+ // HTML pages – always revalidate so deployments are picked up quickly.
+ // `htmlSource` is what makes this rule safe: it is scoped to everything
+ // that is *not* a hashed/asset prefix, so it can no longer overlap (and,
+ // because it was last in the array, override) the immutable and 7-day
+ // rules above.
+ source: htmlSource,
headers: [
{
key: 'Cache-Control',