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