Unverified Commit c1a752bc authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Revert "prevent browser cache from using stale RSC responses from pre… (#88457)

…vious builds (#86554)"

This reverts commit 3bbb2e61.

Need to investigate some upstream constraints before we land this in a
stable release.
parent 1afaa65c
...@@ -1246,8 +1246,6 @@ export async function handler( ...@@ -1246,8 +1246,6 @@ export async function handler(
RSC_CONTENT_TYPE_HEADER RSC_CONTENT_TYPE_HEADER
), ),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader:
nextConfig.experimental.cdnCacheControlHeader,
}) })
} }
...@@ -1265,7 +1263,6 @@ export async function handler( ...@@ -1265,7 +1263,6 @@ 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,
}) })
} }
...@@ -1355,8 +1352,6 @@ export async function handler( ...@@ -1355,8 +1352,6 @@ 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.
...@@ -1373,8 +1368,6 @@ export async function handler( ...@@ -1373,8 +1368,6 @@ 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,
}) })
} }
...@@ -1390,7 +1383,6 @@ export async function handler( ...@@ -1390,7 +1383,6 @@ export async function handler(
RSC_CONTENT_TYPE_HEADER RSC_CONTENT_TYPE_HEADER
), ),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
}) })
} }
...@@ -1423,7 +1415,6 @@ export async function handler( ...@@ -1423,7 +1415,6 @@ export async function handler(
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: body, result: body,
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
cdnCacheControlHeader: nextConfig.experimental.cdnCacheControlHeader,
}) })
} }
...@@ -1450,7 +1441,6 @@ export async function handler( ...@@ -1450,7 +1441,6 @@ 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,
}) })
} }
...@@ -1510,7 +1500,6 @@ export async function handler( ...@@ -1510,7 +1500,6 @@ 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,
}) })
} }
......
...@@ -27,7 +27,7 @@ import { ...@@ -27,7 +27,7 @@ import {
fromNodeOutgoingHttpHeaders, fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders,
} from '../../server/web/utils' } from '../../server/web/utils'
import { setCacheControlHeaders } from '../../server/lib/cache-control' import { getCacheControlHeader } 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 {
...@@ -459,10 +459,9 @@ export async function handler( ...@@ -459,10 +459,9 @@ export async function handler(
!res.getHeader('Cache-Control') && !res.getHeader('Cache-Control') &&
!headers.get('Cache-Control') !headers.get('Cache-Control')
) { ) {
setCacheControlHeaders( headers.set(
headers, 'Cache-Control',
cacheEntry.cacheControl, getCacheControlHeader(cacheEntry.cacheControl)
nextConfig.experimental.cdnCacheControlHeader
) )
} }
......
...@@ -376,7 +376,6 @@ export default abstract class Server< ...@@ -376,7 +376,6 @@ 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>
...@@ -565,8 +564,6 @@ export default abstract class Server< ...@@ -565,8 +564,6 @@ 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,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
this.nextConfig.experimental.maxPostponedStateSize this.nextConfig.experimental.maxPostponedStateSize
), ),
...@@ -1800,8 +1797,6 @@ export default abstract class Server< ...@@ -1800,8 +1797,6 @@ export default abstract class Server<
generateEtags, generateEtags,
poweredByHeader, poweredByHeader,
cacheControl, cacheControl,
cdnCacheControlHeader:
this.nextConfig.experimental.cdnCacheControlHeader,
}) })
res.statusCode = originalStatus res.statusCode = originalStatus
} }
......
...@@ -192,7 +192,6 @@ export const experimentalSchema = { ...@@ -192,7 +192,6 @@ 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,12 +279,6 @@ export interface ExperimentalConfig { ...@@ -279,12 +279,6 @@ 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
...@@ -1508,7 +1502,6 @@ export const defaultConfig = Object.freeze({ ...@@ -1508,7 +1502,6 @@ 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,
...@@ -1658,7 +1651,6 @@ export interface NextConfigRuntime { ...@@ -1658,7 +1651,6 @@ export interface NextConfigRuntime {
| 'clientParamParsingOrigins' | 'clientParamParsingOrigins'
| 'adapterPath' | 'adapterPath'
| 'allowedRevalidateHeaderKeys' | 'allowedRevalidateHeaderKeys'
| 'cdnCacheControlHeader'
| 'fetchCacheKeyPrefix' | 'fetchCacheKeyPrefix'
| 'isrFlushToDisk' | 'isrFlushToDisk'
| 'optimizeCss' | 'optimizeCss'
...@@ -1715,7 +1707,6 @@ export function getNextConfigRuntime( ...@@ -1715,7 +1707,6 @@ 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'
/** /**
...@@ -15,15 +14,10 @@ export interface CacheControl { ...@@ -15,15 +14,10 @@ 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): CacheHeaders { }: CacheControl): string {
const swrHeader = const swrHeader =
typeof revalidate === 'number' && typeof revalidate === 'number' &&
expire !== undefined && expire !== undefined &&
...@@ -32,67 +26,10 @@ export function getCacheControlHeader({ ...@@ -32,67 +26,10 @@ export function getCacheControlHeader({
: '' : ''
if (revalidate === 0) { if (revalidate === 0) {
return { return 'private, no-cache, no-store, max-age=0, must-revalidate'
'Cache-Control': } else if (typeof revalidate === 'number') {
'private, no-cache, no-store, max-age=0, must-revalidate', return `s-maxage=${revalidate}${swrHeader}`
}
}
// 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)
}
} }
...@@ -609,7 +609,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -609,7 +609,6 @@ 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({
...@@ -619,7 +618,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -619,7 +618,6 @@ 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 { setResponseCacheControlHeaders } from './lib/cache-control' import { getCacheControlHeader } 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,7 +287,6 @@ export type RenderOptsPartial = { ...@@ -287,7 +287,6 @@ export type RenderOptsPartial = {
expireTime?: number expireTime?: number
experimental: { experimental: {
clientTraceMetadata?: string[] clientTraceMetadata?: string[]
cdnCacheControlHeader?: string
} }
} }
...@@ -556,10 +555,9 @@ export async function renderToHTMLImpl( ...@@ -556,10 +555,9 @@ 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) {
setResponseCacheControlHeaders( res.setHeader(
res, 'Cache-Control',
{ revalidate: false, expire: expireTime }, getCacheControlHeader({ revalidate: false, expire: expireTime })
renderOpts.experimental.cdnCacheControlHeader
) )
isAutoExport = false isAutoExport = false
} }
......
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
} from '../../response-cache' } from '../../response-cache'
import { import {
setResponseCacheControlHeaders, getCacheControlHeader,
type CacheControl, type CacheControl,
} from '../../lib/cache-control' } from '../../lib/cache-control'
import { normalizeRepeatedSlashes } from '../../../shared/lib/utils' import { normalizeRepeatedSlashes } from '../../../shared/lib/utils'
...@@ -616,11 +616,7 @@ export const getHandler = ({ ...@@ -616,11 +616,7 @@ 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')) {
setResponseCacheControlHeaders( res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))
res,
cacheControl,
nextConfig.experimental.cdnCacheControlHeader
)
} }
// notFound: true case // notFound: true case
...@@ -736,7 +732,6 @@ export const getHandler = ({ ...@@ -736,7 +732,6 @@ 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 { setResponseCacheControlHeaders } from './lib/cache-control' import { getCacheControlHeader } 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,7 +39,6 @@ export async function sendRenderResult({ ...@@ -39,7 +39,6 @@ export async function sendRenderResult({
generateEtags, generateEtags,
poweredByHeader, poweredByHeader,
cacheControl, cacheControl,
cdnCacheControlHeader,
}: { }: {
req: IncomingMessage req: IncomingMessage
res: ServerResponse res: ServerResponse
...@@ -47,7 +46,6 @@ export async function sendRenderResult({ ...@@ -47,7 +46,6 @@ 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
...@@ -60,7 +58,7 @@ export async function sendRenderResult({ ...@@ -60,7 +58,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')) {
setResponseCacheControlHeaders(res, cacheControl, cdnCacheControlHeader) res.setHeader('Cache-Control', getCacheControlHeader(cacheControl))
} }
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,14 +31,10 @@ describe('custom-cache-control', () => { ...@@ -31,14 +31,10 @@ 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 ? 'no-store, must-revalidate' : 's-maxage=120' isNextDev
? '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'
)
}
} }
) )
...@@ -73,13 +69,10 @@ describe('custom-cache-control', () => { ...@@ -73,13 +69,10 @@ 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 ? 'no-store, must-revalidate' : 's-maxage=120' isNextDev
? '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,19 +553,17 @@ describe('use-cache', () => { ...@@ -553,19 +553,17 @@ 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('s-maxage=100') expect(response.headers.get('cache-control')).toBe(
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
'max-age=100, stale-while-revalidate=200' 's-maxage=100, stale-while-revalidate=200'
) )
response = await next.fetch('/cache-fetch') response = await next.fetch('/cache-fetch')
expect(response.headers.get('cache-control')).toBe('s-maxage=900') expect(response.headers.get('cache-control')).toBe(
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
'max-age=900, stale-while-revalidate=31535100' 's-maxage=900, stale-while-revalidate=31535100'
) )
}) })
......
...@@ -676,25 +676,21 @@ describe('Prerender', () => { ...@@ -676,25 +676,21 @@ 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('s-maxage=2') expect(initialRes.headers.get('cache-control')).toBe(
if (!isDeploy) { isDeploy
expect(initialRes.headers.get('cdn-cache-control')).toBe( ? 'public, max-age=0, must-revalidate'
'max-age=2, stale-while-revalidate=31535998' : 's-maxage=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 ? 'public, max-age=0, must-revalidate' : 's-maxage=2' isDeploy
? '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(
...@@ -703,23 +699,19 @@ describe('Prerender', () => { ...@@ -703,23 +699,19 @@ 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 ? 'public, max-age=0, must-revalidate' : 's-maxage=2' isDeploy
? '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('s-maxage=2') expect(finalRes.headers.get('cache-control')).toBe(
if (!isDeploy) { isDeploy
expect(finalRes.headers.get('cdn-cache-control')).toBe( ? 'public, max-age=0, must-revalidate'
'max-age=2, stale-while-revalidate=31535998' : 's-maxage=2, stale-while-revalidate=31535998'
) )
}
expect(await finalRes.text()).not.toContain('hi fallback') expect(await finalRes.text()).not.toContain('hi fallback')
}) })
}) })
...@@ -739,22 +731,20 @@ describe('Prerender', () => { ...@@ -739,22 +731,20 @@ 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('s-maxage=2') expect(dataRes.headers.get('cache-control')).toBe(
if (!isDeploy) { isDeploy
expect(dataRes.headers.get('cdn-cache-control')).toBe( ? 'public, max-age=0, must-revalidate'
'max-age=2, stale-while-revalidate=31535998' : 's-maxage=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('s-maxage=2') expect(finalRes.headers.get('cache-control')).toBe(
if (!isDeploy) { isDeploy
expect(finalRes.headers.get('cdn-cache-control')).toBe( ? 'public, max-age=0, must-revalidate'
'max-age=2, stale-while-revalidate=31535998' : 's-maxage=2, stale-while-revalidate=31535998'
) )
}
expect(await finalRes.text()).not.toContain('hi fallback') expect(await finalRes.text()).not.toContain('hi fallback')
}) })
}) })
...@@ -1390,11 +1380,6 @@ describe('Prerender', () => { ...@@ -1390,11 +1380,6 @@ 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,9 +81,8 @@ const runTests = () => { ...@@ -81,9 +81,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( `s-maxage=1, stale-while-revalidate=31535999`
`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)
...@@ -92,9 +91,8 @@ const runTests = () => { ...@@ -92,9 +91,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( `s-maxage=1, stale-while-revalidate=31535999`
`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)
...@@ -104,9 +102,8 @@ const runTests = () => { ...@@ -104,9 +102,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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)
...@@ -118,9 +115,8 @@ const runTests = () => { ...@@ -118,9 +115,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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)
...@@ -132,9 +128,8 @@ const runTests = () => { ...@@ -132,9 +128,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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)
...@@ -152,9 +147,8 @@ const runTests = () => { ...@@ -152,9 +147,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( `s-maxage=1, stale-while-revalidate=31535999`
`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)
...@@ -164,9 +158,8 @@ const runTests = () => { ...@@ -164,9 +158,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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)
...@@ -178,9 +171,8 @@ const runTests = () => { ...@@ -178,9 +171,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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)
...@@ -192,9 +184,8 @@ const runTests = () => { ...@@ -192,9 +184,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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,7 +113,6 @@ describe('required server files app router', () => { ...@@ -113,7 +113,6 @@ 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 () => {
...@@ -172,9 +171,8 @@ describe('required server files app router', () => { ...@@ -172,9 +171,8 @@ 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=3600') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=3600, stale-while-revalidate=31532400'
'max-age=3600, stale-while-revalidate=31532400'
) )
}) })
......
...@@ -174,9 +174,8 @@ describe('required server files i18n', () => { ...@@ -174,9 +174,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'max-age=1, stale-while-revalidate=31535999'
) )
await waitFor(2000) await waitFor(2000)
...@@ -186,9 +185,8 @@ describe('required server files i18n', () => { ...@@ -186,9 +185,8 @@ 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('s-maxage=1') expect(res2.headers.get('cache-control')).toBe(
expect(res2.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'max-age=1, stale-while-revalidate=31535999'
) )
}) })
......
...@@ -220,18 +220,16 @@ describe('required server files', () => { ...@@ -220,18 +220,16 @@ 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', cacheControl: 's-maxage=5, stale-while-revalidate=31535995',
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, cdnCacheControl }) => { async ({ path, dest, cacheControl }) => {
const res = await fetchViaHTTP(appPort, path, undefined, { const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual', redirect: 'manual',
}) })
...@@ -240,7 +238,6 @@ describe('required server files', () => { ...@@ -240,7 +238,6 @@ 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,
...@@ -250,8 +247,6 @@ describe('required server files', () => { ...@@ -250,8 +247,6 @@ 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,
...@@ -302,24 +297,21 @@ describe('required server files', () => { ...@@ -302,24 +297,21 @@ 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', cacheControl: 's-maxage=5, stale-while-revalidate=31535995',
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, cdnCacheControl }) => { async ({ path, dest, cacheControl }) => {
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,
...@@ -330,7 +322,6 @@ describe('required server files', () => { ...@@ -330,7 +322,6 @@ 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)
} }
) )
...@@ -338,7 +329,6 @@ describe('required server files', () => { ...@@ -338,7 +329,6 @@ 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'],
...@@ -351,7 +341,6 @@ describe('required server files', () => { ...@@ -351,7 +341,6 @@ 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'],
}) })
...@@ -544,9 +533,8 @@ describe('required server files', () => { ...@@ -544,9 +533,8 @@ 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('s-maxage=1') expect(res.headers.get('cache-control')).toBe(
expect(res.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'max-age=1, stale-while-revalidate=31535999'
) )
await waitFor(2000) await waitFor(2000)
...@@ -556,9 +544,8 @@ describe('required server files', () => { ...@@ -556,9 +544,8 @@ 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('s-maxage=1') expect(res2.headers.get('cache-control')).toBe(
expect(res2.headers.get('cdn-cache-control')).toBe( 's-maxage=1, stale-while-revalidate=31535999'
'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