Unverified Commit 3bbb2e61 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

prevent browser cache from using stale RSC responses from previous builds (#86554)

When we landed #76207 we started propagating the
`stale-while-revalidate` value to RSC responses. We wanted a way to
express to CDNs that it can keep serving the cached content for some
time while a revalidation runs in the background, but we specifically
don't want that for private caches.

As a result of this header, when re-building your application locally
(or doing something on the server that would have expired the cache),
the browser's disk cache would serve a stale RSC response. We currently
encode a buildId in RSC payloads, so the client router will discard RSC
responses that don't match what it is expecting.

Unfortunately there isn't a `s-stale-while-revalidate` header to express
the intended semantics. This moves the `stale-while-revalidate`
configuration into the `CDN-Cache-Control` header, which is becoming
standardized and is supported by a wide variety of CDNs. This allows us
to specify the SWR behavior more explicitly to CDNs while not impacting
private caches like the browser. It restores the previous behavior of
only setting `s-maxage` on the `cache-control` itself to avoid
influencing browser cache.

If Next.js is deployed to a CDN that doesn't support this header, it can
be customized via `nextConfig.experimental.cdnCacheControlHeader`. Eg,
if deployed to Fastly, you'd configure this to `cdnCacheControlHeader:
'Surrogate-Control'`.

Closes NAR-525

Reference docs:


[Vercel](https://vercel.com/docs/headers/cache-control-headers#cdn-cache-control-header)

[Cloudflare](https://developers.cloudflare.com/cache/concepts/cdn-cache-control/)

[Fastly](https://www.fastly.com/documentation/reference/http/http-headers/Surrogate-Control/)

[RFC 9213](https://httpwg.org/specs/rfc9213.html)
parent 8fd79ff4
......@@ -1134,6 +1134,8 @@ export async function handler(
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader:
nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1151,6 +1153,7 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1240,6 +1243,8 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader:
nextConfig.experimental.cdnCacheControlHeader,
})
} else {
// Otherwise this case is not expected.
......@@ -1256,6 +1261,8 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader,
result: cachedData.html,
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader:
nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1271,6 +1278,7 @@ export async function handler(
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1303,6 +1311,7 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1329,6 +1338,7 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: { revalidate: 0, expire: undefined },
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......@@ -1388,6 +1398,7 @@ export async function handler(
// the response being sent to the client it's dynamic parts are streamed
// to the client on the same request.
cacheControl: { revalidate: 0, expire: undefined },
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......
......@@ -22,7 +22,7 @@ import {
fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders,
} from '../../server/web/utils'
import { getCacheControlHeader } from '../../server/lib/cache-control'
import { setCacheControlHeaders } from '../../server/lib/cache-control'
import { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
import {
......@@ -450,9 +450,10 @@ export async function handler(
!res.getHeader('Cache-Control') &&
!headers.get('Cache-Control')
) {
headers.set(
'Cache-Control',
getCacheControlHeader(cacheEntry.cacheControl)
setCacheControlHeaders(
headers,
cacheEntry.cacheControl,
nextConfig.experimental.cdnCacheControlHeader
)
}
......
......@@ -372,6 +372,7 @@ export default abstract class Server<
generateEtags: boolean
poweredByHeader: boolean
cacheControl: CacheControl | undefined
cdnCacheControlHeader?: string
}
): Promise<void>
......@@ -560,6 +561,8 @@ export default abstract class Server<
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
cdnCacheControlHeader:
this.nextConfig.experimental.cdnCacheControlHeader,
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
......@@ -1762,6 +1765,8 @@ export default abstract class Server<
generateEtags,
poweredByHeader,
cacheControl,
cdnCacheControlHeader:
this.nextConfig.experimental.cdnCacheControlHeader,
})
res.statusCode = originalStatus
}
......
......@@ -192,6 +192,7 @@ export const experimentalSchema = {
memoryBasedWorkersCount: z.boolean().optional(),
craCompat: z.boolean().optional(),
caseSensitiveRoutes: z.boolean().optional(),
cdnCacheControlHeader: z.string().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(),
dynamicOnHover: z.boolean().optional(),
disableOptimizedLoading: z.boolean().optional(),
......
......@@ -279,6 +279,12 @@ export interface ExperimentalConfig {
prerenderEarlyExit?: boolean
linkNoTouchStart?: boolean
caseSensitiveRoutes?: boolean
/**
* Custom header name to use for CDN cache control instead of the default
* 'CDN-Cache-Control'. This can be used to target specific CDN providers
* that do not support `CDN-Cache-Control` and have their own custom header.
*/
cdnCacheControlHeader?: string
/**
* The origins that are allowed to write the rewritten headers when
* performing a non-relative rewrite. When undefined, no non-relative
......@@ -1507,6 +1513,7 @@ export const defaultConfig = Object.freeze({
serverMinification: true,
linkNoTouchStart: false,
caseSensitiveRoutes: false,
cdnCacheControlHeader: undefined,
clientParamParsingOrigins: undefined,
dynamicOnHover: false,
preloadEntriesOnStart: true,
......@@ -1655,6 +1662,7 @@ export interface NextConfigRuntime {
| 'clientParamParsingOrigins'
| 'adapterPath'
| 'allowedRevalidateHeaderKeys'
| 'cdnCacheControlHeader'
| 'fetchCacheKeyPrefix'
| 'isrFlushToDisk'
| 'optimizeCss'
......@@ -1709,6 +1717,7 @@ export function getNextConfigRuntime(
clientParamParsingOrigins: ex.clientParamParsingOrigins,
adapterPath: ex.adapterPath,
allowedRevalidateHeaderKeys: ex.allowedRevalidateHeaderKeys,
cdnCacheControlHeader: ex.cdnCacheControlHeader,
fetchCacheKeyPrefix: ex.fetchCacheKeyPrefix,
isrFlushToDisk: ex.isrFlushToDisk,
optimizeCss: ex.optimizeCss,
......
import type { ServerResponse } from 'http'
import { CACHE_ONE_YEAR } from '../../lib/constants'
/**
......@@ -14,10 +15,15 @@ export interface CacheControl {
expire: number | undefined
}
export interface CacheHeaders {
'Cache-Control': string
cdnCacheControl?: string
}
export function getCacheControlHeader({
revalidate,
expire,
}: CacheControl): string {
}: CacheControl): CacheHeaders {
const swrHeader =
typeof revalidate === 'number' &&
expire !== undefined &&
......@@ -26,10 +32,67 @@ export function getCacheControlHeader({
: ''
if (revalidate === 0) {
return 'private, no-cache, no-store, max-age=0, must-revalidate'
} else if (typeof revalidate === 'number') {
return `s-maxage=${revalidate}${swrHeader}`
return {
'Cache-Control':
'private, no-cache, no-store, max-age=0, must-revalidate',
}
}
// For non-zero revalidation, we want to leverage CDN stale-while-revalidate caching
// semantics without allowing the browser to cache the response.
const maxAge = typeof revalidate === 'number' ? revalidate : CACHE_ONE_YEAR
const cdnCacheControl = `max-age=${maxAge}${swrHeader}`
const cacheControl = `s-maxage=${maxAge}`
return {
'Cache-Control': cacheControl,
cdnCacheControl: cdnCacheControl,
}
}
/**
* The default header name used for CDN cache control.
*/
export const DEFAULT_CDN_CACHE_CONTROL_HEADER = 'CDN-Cache-Control'
return `s-maxage=${CACHE_ONE_YEAR}${swrHeader}`
/**
* Sets cache control headers on a ServerResponse object.
* Use this helper to consistently set Cache-Control and CDN cache control headers.
*
* @param res - The ServerResponse object
* @param cacheControl - The cache control configuration
* @param cdnCacheControlHeader - Custom CDN cache control header name from config, falls back to 'CDN-Cache-Control' if undefined
*/
export function setResponseCacheControlHeaders(
res: ServerResponse,
cacheControl: CacheControl,
cdnCacheControlHeader: string | undefined
): void {
const cacheHeaders = getCacheControlHeader(cacheControl)
const headerName = cdnCacheControlHeader ?? DEFAULT_CDN_CACHE_CONTROL_HEADER
res.setHeader('Cache-Control', cacheHeaders['Cache-Control'])
if (cacheHeaders.cdnCacheControl) {
res.setHeader(headerName, cacheHeaders.cdnCacheControl)
}
}
/**
* Sets cache control headers on a Headers object (for Web API responses).
* Use this helper to consistently set Cache-Control and CDN cache control headers.
*
* @param headers - The Headers object
* @param cacheControl - The cache control configuration
* @param cdnCacheControlHeader - Custom CDN cache control header name from config, falls back to 'CDN-Cache-Control' if undefined
*/
export function setCacheControlHeaders(
headers: Headers,
cacheControl: CacheControl,
cdnCacheControlHeader: string | undefined
): void {
const cacheHeaders = getCacheControlHeader(cacheControl)
const headerName = cdnCacheControlHeader ?? DEFAULT_CDN_CACHE_CONTROL_HEADER
headers.set('Cache-Control', cacheHeaders['Cache-Control'])
if (cacheHeaders.cdnCacheControl) {
headers.set(headerName, cacheHeaders.cdnCacheControl)
}
}
......@@ -605,6 +605,7 @@ export default class NextNodeServer extends BaseServer<
generateEtags: boolean
poweredByHeader: boolean
cacheControl: CacheControl | undefined
cdnCacheControlHeader?: string
}
): Promise<void> {
return sendRenderResult({
......@@ -614,6 +615,7 @@ export default class NextNodeServer extends BaseServer<
generateEtags: options.generateEtags,
poweredByHeader: options.poweredByHeader,
cacheControl: options.cacheControl,
cdnCacheControlHeader: options.cdnCacheControlHeader,
})
}
......
......@@ -101,7 +101,7 @@ import {
import { getTracer } from './lib/trace/tracer'
import { RenderSpan } from './lib/trace/constants'
import { ReflectAdapter } from './web/spec-extension/adapters/reflect'
import { getCacheControlHeader } from './lib/cache-control'
import { setResponseCacheControlHeaders } from './lib/cache-control'
import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
......@@ -287,6 +287,7 @@ export type RenderOptsPartial = {
expireTime?: number
experimental: {
clientTraceMetadata?: string[]
cdnCacheControlHeader?: string
}
}
......@@ -555,9 +556,10 @@ export async function renderToHTMLImpl(
// ensure we set cache header so it's not rendered on-demand
// every request
if (isAutoExport && !dev && isExperimentalCompile) {
res.setHeader(
'Cache-Control',
getCacheControlHeader({ revalidate: false, expire: expireTime })
setResponseCacheControlHeaders(
res,
{ revalidate: false, expire: expireTime },
renderOpts.experimental.cdnCacheControlHeader
)
isAutoExport = false
}
......
......@@ -17,7 +17,7 @@ import {
} from '../../response-cache'
import {
getCacheControlHeader,
setResponseCacheControlHeaders,
type CacheControl,
} from '../../lib/cache-control'
import { normalizeRepeatedSlashes } from '../../../shared/lib/utils'
......@@ -607,7 +607,11 @@ export const getHandler = ({
// If cache control is already set on the response we don't
// override it to allow users to customize it via next.config
if (cacheControl && !res.getHeader('Cache-Control')) {
res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))
setResponseCacheControlHeaders(
res,
cacheControl,
nextConfig.experimental.cdnCacheControlHeader
)
}
// notFound: true case
......@@ -718,6 +722,7 @@ export const getHandler = ({
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
cacheControl: routeModule.isDev ? undefined : cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
})
}
......
......@@ -5,7 +5,7 @@ import type { CacheControl } from './lib/cache-control'
import { isResSent } from '../shared/lib/utils'
import { generateETag } from './lib/etag'
import fresh from 'next/dist/compiled/fresh'
import { getCacheControlHeader } from './lib/cache-control'
import { setResponseCacheControlHeaders } from './lib/cache-control'
import { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'
export function sendEtagResponse(
......@@ -39,6 +39,7 @@ export async function sendRenderResult({
generateEtags,
poweredByHeader,
cacheControl,
cdnCacheControlHeader,
}: {
req: IncomingMessage
res: ServerResponse
......@@ -46,6 +47,7 @@ export async function sendRenderResult({
generateEtags: boolean
poweredByHeader: boolean
cacheControl: CacheControl | undefined
cdnCacheControlHeader?: string
}): Promise<void> {
if (isResSent(res)) {
return
......@@ -58,7 +60,7 @@ export async function sendRenderResult({
// If cache control is already set on the response we don't
// override it to allow users to customize it via next.config
if (cacheControl && !res.getHeader('Cache-Control')) {
res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))
setResponseCacheControlHeaders(res, cacheControl, cdnCacheControlHeader)
}
const payload = result.isDynamic ? null : result.toUnchunkedString()
......
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use cache'
import { cacheLife } from 'next/cache'
export default async function Page() {
cacheLife('minutes')
return <p>Hello World</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('cdn-cache-control-header', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
if (isNextDeploy) {
it('should skip for deploy', () => {})
return
}
it('should use custom CDN cache control header name from experimental config', async () => {
const res = await next.fetch('/')
// In dev mode, no caching headers are set
if (isNextDev) {
expect(res.headers.get('cache-control')).toBe('no-store, must-revalidate')
expect(res.headers.get('surrogate-control')).toBeNull()
expect(res.headers.get('cdn-cache-control')).toBeNull()
return
}
expect(res.headers.get('cache-control')).toBe('s-maxage=60')
expect(res.headers.get('surrogate-control')).toMatch(/^max-age=\d+/)
expect(res.headers.get('cdn-cache-control')).toBeNull()
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
cdnCacheControlHeader: 'Surrogate-Control',
},
}
module.exports = nextConfig
......@@ -31,10 +31,14 @@ describe('custom-cache-control', () => {
const res = await next.fetch('/app-ssg/another')
// eslint-disable-next-line jest/no-standalone-expect
expect(res.headers.get('cache-control')).toBe(
isNextDev
? 'no-store, must-revalidate'
: 's-maxage=120, stale-while-revalidate=31535880'
isNextDev ? 'no-store, must-revalidate' : 's-maxage=120'
)
if (!isNextDev) {
// eslint-disable-next-line jest/no-standalone-expect
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=120, stale-while-revalidate=31535880'
)
}
}
)
......@@ -69,10 +73,13 @@ describe('custom-cache-control', () => {
it('should have default cache-control for pages-ssg another', async () => {
const res = await next.fetch('/pages-ssg/another')
expect(res.headers.get('cache-control')).toBe(
isNextDev
? 'no-store, must-revalidate'
: 's-maxage=120, stale-while-revalidate=31535880'
isNextDev ? 'no-store, must-revalidate' : 's-maxage=120'
)
if (!isNextDev) {
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=120, stale-while-revalidate=31535880'
)
}
})
it('should have default cache-control for pages-ssr', async () => {
......
......@@ -553,17 +553,19 @@ describe('use-cache', () => {
it('should send an SWR cache-control header based on the revalidate and expire values', async () => {
let response = await next.fetch('/cache-life')
expect(response.headers.get('cache-control')).toBe(
expect(response.headers.get('cache-control')).toBe('s-maxage=100')
expect(response.headers.get('cdn-cache-control')).toBe(
// revalidate is set to 100, expire is set to 300 => SWR 200
's-maxage=100, stale-while-revalidate=200'
'max-age=100, stale-while-revalidate=200'
)
response = await next.fetch('/cache-fetch')
expect(response.headers.get('cache-control')).toBe(
expect(response.headers.get('cache-control')).toBe('s-maxage=900')
expect(response.headers.get('cdn-cache-control')).toBe(
// revalidate is set to 900, expire is one year (31536000, default
// expireTime) => SWR 31535100
's-maxage=900, stale-while-revalidate=31535100'
'max-age=900, stale-while-revalidate=31535100'
)
})
......
......@@ -676,21 +676,25 @@ describe('Prerender', () => {
if (!isDev) {
it('should use correct caching headers for a revalidate page', async () => {
const initialRes = await fetchViaHTTP(next.url, '/')
expect(initialRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
)
expect(initialRes.headers.get('cache-control')).toBe('s-maxage=2')
if (!isDeploy) {
expect(initialRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
})
it('should use correct caching headers for a fallback-true page (prerendered)', async () => {
const initialRes = await fetchViaHTTP(next.url, '/fallback-true/first')
expect(initialRes.status).toBe(200)
expect(initialRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
isDeploy ? 'public, max-age=0, must-revalidate' : 's-maxage=2'
)
if (!isDeploy) {
expect(initialRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
expect(await initialRes.text()).not.toContain('hi fallback')
const dataRes = await fetchViaHTTP(
......@@ -699,19 +703,23 @@ describe('Prerender', () => {
)
expect(dataRes.status).toBe(200)
expect(dataRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
isDeploy ? 'public, max-age=0, must-revalidate' : 's-maxage=2'
)
if (!isDeploy) {
expect(dataRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
await retry(async () => {
const finalRes = await fetchViaHTTP(next.url, `/fallback-true/first`)
expect(finalRes.status).toBe(200)
expect(finalRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
)
expect(finalRes.headers.get('cache-control')).toBe('s-maxage=2')
if (!isDeploy) {
expect(finalRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
expect(await finalRes.text()).not.toContain('hi fallback')
})
})
......@@ -731,20 +739,22 @@ describe('Prerender', () => {
`/_next/data/${next.buildId}/fallback-true/second.json`
)
expect(dataRes.status).toBe(200)
expect(dataRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
)
expect(dataRes.headers.get('cache-control')).toBe('s-maxage=2')
if (!isDeploy) {
expect(dataRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
await retry(async () => {
const finalRes = await fetchViaHTTP(next.url, `/fallback-true/second`)
expect(finalRes.status).toBe(200)
expect(finalRes.headers.get('cache-control')).toBe(
isDeploy
? 'public, max-age=0, must-revalidate'
: 's-maxage=2, stale-while-revalidate=31535998'
)
expect(finalRes.headers.get('cache-control')).toBe('s-maxage=2')
if (!isDeploy) {
expect(finalRes.headers.get('cdn-cache-control')).toBe(
'max-age=2, stale-while-revalidate=31535998'
)
}
expect(await finalRes.text()).not.toContain('hi fallback')
})
})
......@@ -1380,6 +1390,11 @@ describe('Prerender', () => {
expect(initialRes.headers.get('cache-control')).toBe(
isDeploy ? 'public, max-age=0, must-revalidate' : 's-maxage=31536000'
)
if (!isDeploy) {
expect(initialRes.headers.get('cdn-cache-control')).toBe(
'max-age=31536000'
)
}
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
})
......
......@@ -81,8 +81,9 @@ const runTests = () => {
let res = await fetchViaHTTP(appPort, '/fallback-blocking/hello')
let $ = cheerio.load(await res.text())
expect(res.headers.get('cache-control')).toBe(
`s-maxage=1, stale-while-revalidate=31535999`
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
`max-age=1, stale-while-revalidate=31535999`
)
expect(res.status).toBe(404)
expect(JSON.parse($('#props').text()).notFound).toBe(true)
......@@ -91,8 +92,9 @@ const runTests = () => {
res = await fetchViaHTTP(appPort, '/fallback-blocking/hello')
$ = cheerio.load(await res.text())
expect(res.headers.get('cache-control')).toBe(
`s-maxage=1, stale-while-revalidate=31535999`
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
`max-age=1, stale-while-revalidate=31535999`
)
expect(res.status).toBe(404)
expect(JSON.parse($('#props').text()).notFound).toBe(true)
......@@ -102,8 +104,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props.found).toBe(true)
......@@ -115,8 +118,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props2 = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props2.found).toBe(true)
......@@ -128,8 +132,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props3 = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props3.found).toBe(true)
......@@ -147,8 +152,9 @@ const runTests = () => {
let res = await fetchViaHTTP(appPort, '/fallback-true/world')
let $ = cheerio.load(await res.text())
expect(res.headers.get('cache-control')).toBe(
`s-maxage=1, stale-while-revalidate=31535999`
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
`max-age=1, stale-while-revalidate=31535999`
)
expect(res.status).toBe(404)
expect(JSON.parse($('#props').text()).notFound).toBe(true)
......@@ -158,8 +164,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props.found).toBe(true)
......@@ -171,8 +178,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props2 = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props2.found).toBe(true)
......@@ -184,8 +192,9 @@ const runTests = () => {
$ = cheerio.load(await res.text())
const props3 = JSON.parse($('#props').text())
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
expect(res.status).toBe(200)
expect(props3.found).toBe(true)
......
......@@ -113,6 +113,7 @@ describe('required server files app router', () => {
})
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
expect(res.headers.get('cdn-cache-control')).toBe('max-age=31536000')
})
it('should handle optional catchall', async () => {
......@@ -171,8 +172,9 @@ describe('required server files app router', () => {
},
})
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=3600, stale-while-revalidate=31532400'
expect(res.headers.get('cache-control')).toBe('s-maxage=3600')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=3600, stale-while-revalidate=31532400'
)
})
......
......@@ -174,8 +174,9 @@ describe('required server files i18n', () => {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
await waitFor(2000)
......@@ -185,8 +186,9 @@ describe('required server files i18n', () => {
redirect: 'manual',
})
expect(res2.status).toBe(404)
expect(res2.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res2.headers.get('cache-control')).toBe('s-maxage=1')
expect(res2.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
})
......
......@@ -220,16 +220,18 @@ describe('required server files', () => {
path: '/optional-ssg/redirect-1',
dest: '/somewhere',
cacheControl: 's-maxage=31536000',
cdnCacheControl: 'max-age=31536000',
},
{
case: 'redirect with revalidate',
path: '/optional-ssg/redirect-2',
dest: '/somewhere-else',
cacheControl: 's-maxage=5, stale-while-revalidate=31535995',
cacheControl: 's-maxage=5',
cdnCacheControl: 'max-age=5, stale-while-revalidate=31535995',
},
])(
`should have correct cache-control for $case`,
async ({ path, dest, cacheControl }) => {
async ({ path, dest, cacheControl, cdnCacheControl }) => {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
......@@ -238,6 +240,7 @@ describe('required server files', () => {
dest
)
expect(res.headers.get('cache-control')).toBe(cacheControl)
expect(res.headers.get('cdn-cache-control')).toBe(cdnCacheControl)
const dataRes = await fetchViaHTTP(
appPort,
......@@ -247,6 +250,8 @@ describe('required server files', () => {
redirect: 'manual',
}
)
expect(dataRes.headers.get('cache-control')).toBe(cacheControl)
expect(dataRes.headers.get('cdn-cache-control')).toBe(cdnCacheControl)
expect((await dataRes.json()).pageProps).toEqual({
__N_REDIRECT: dest,
__N_REDIRECT_STATUS: 307,
......@@ -297,21 +302,24 @@ describe('required server files', () => {
path: '/optional-ssg/not-found-1',
dest: '/somewhere',
cacheControl: 's-maxage=31536000',
cdnCacheControl: 'max-age=31536000',
},
{
case: 'notFound with revalidate',
path: '/optional-ssg/not-found-2',
dest: '/somewhere-else',
cacheControl: 's-maxage=5, stale-while-revalidate=31535995',
cacheControl: 's-maxage=5',
cdnCacheControl: 'max-age=5, stale-while-revalidate=31535995',
},
])(
`should have correct cache-control for $case`,
async ({ path, dest, cacheControl }) => {
async ({ path, dest, cacheControl, cdnCacheControl }) => {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(404)
expect(res.headers.get('cache-control')).toBe(cacheControl)
expect(res.headers.get('cdn-cache-control')).toBe(cdnCacheControl)
const dataRes = await fetchViaHTTP(
appPort,
......@@ -322,6 +330,7 @@ describe('required server files', () => {
}
)
expect(dataRes.headers.get('cache-control')).toBe(cacheControl)
expect(dataRes.headers.get('cdn-cache-control')).toBe(cdnCacheControl)
}
)
......@@ -329,6 +338,7 @@ describe('required server files', () => {
const res = await fetchViaHTTP(appPort, '/optional-ssg/props-no-revalidate')
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
expect(res.headers.get('cdn-cache-control')).toBe('max-age=31536000')
const $ = cheerio.load(await res.text())
expect(JSON.parse($('#props').text()).params).toEqual({
rest: ['props-no-revalidate'],
......@@ -341,6 +351,7 @@ describe('required server files', () => {
)
expect(dataRes.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
expect(res.headers.get('cdn-cache-control')).toBe('max-age=31536000')
expect((await dataRes.json()).pageProps.params).toEqual({
rest: ['props-no-revalidate'],
})
......@@ -533,8 +544,9 @@ describe('required server files', () => {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res.headers.get('cache-control')).toBe('s-maxage=1')
expect(res.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
await waitFor(2000)
......@@ -544,8 +556,9 @@ describe('required server files', () => {
redirect: 'manual',
})
expect(res2.status).toBe(404)
expect(res2.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
expect(res2.headers.get('cache-control')).toBe('s-maxage=1')
expect(res2.headers.get('cdn-cache-control')).toBe(
'max-age=1, stale-while-revalidate=31535999'
)
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment