Unverified Commit f07ef56a authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add handling for setting deployment id via cookie (#78841)

As discussed this adds a flag to allow setting deployment ID via a
cookie instead of in query string on asset requests which allows for
better caching with the trade-off of users potentially staying on older
deployments longer until the ID is no longer accepted or the session
cookie is cleared.
parent 7cc6c220
...@@ -155,7 +155,10 @@ export function getDefineEnv({ ...@@ -155,7 +155,10 @@ export function getDefineEnv({
'process.env.__NEXT_PPR': isPPREnabled, 'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_DYNAMIC_IO': isDynamicIOEnabled, 'process.env.__NEXT_DYNAMIC_IO': isDynamicIOEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || false,
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
// Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
// variable to the client. // variable to the client.
'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING': 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':
......
...@@ -719,6 +719,18 @@ export default async function loadCustomRoutes( ...@@ -719,6 +719,18 @@ export default async function loadCustomRoutes(
) )
} }
if (config.experimental?.useSkewCookie && config.deploymentId) {
headers.unshift({
source: '/:path*',
headers: [
{
key: 'Set-Cookie',
value: `__vdpl=${config.deploymentId}; Path=/; HttpOnly`,
},
],
})
}
if (!config.skipTrailingSlashRedirect) { if (!config.skipTrailingSlashRedirect) {
if (config.trailingSlash) { if (config.trailingSlash) {
redirects.unshift( redirects.unshift(
......
...@@ -315,6 +315,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -315,6 +315,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
excludeDefaultMomentLocales: z.boolean().optional(), excludeDefaultMomentLocales: z.boolean().optional(),
experimental: z experimental: z
.strictObject({ .strictObject({
useSkewCookie: z.boolean().optional(),
nodeMiddleware: z.boolean().optional(), nodeMiddleware: z.boolean().optional(),
after: z.boolean().optional(), after: z.boolean().optional(),
appDocumentPreloading: z.boolean().optional(), appDocumentPreloading: z.boolean().optional(),
......
...@@ -273,6 +273,7 @@ export interface LoggingConfig { ...@@ -273,6 +273,7 @@ export interface LoggingConfig {
} }
export interface ExperimentalConfig { export interface ExperimentalConfig {
useSkewCookie?: boolean
nodeMiddleware?: boolean nodeMiddleware?: boolean
cacheHandlers?: { cacheHandlers?: {
default?: string default?: string
...@@ -1237,6 +1238,7 @@ export const defaultConfig: NextConfig = { ...@@ -1237,6 +1238,7 @@ export const defaultConfig: NextConfig = {
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '', outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
allowedDevOrigins: undefined, allowedDevOrigins: undefined,
experimental: { experimental: {
useSkewCookie: false,
nodeMiddleware: false, nodeMiddleware: false,
cacheLife: { cacheLife: {
default: { default: {
......
...@@ -284,7 +284,9 @@ export default class NextNodeServer extends BaseServer< ...@@ -284,7 +284,9 @@ export default class NextNodeServer extends BaseServer<
if (this.renderOpts.nextScriptWorkers) { if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true) process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
} }
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || '' process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.experimental.useSkewCookie
? ''
: this.nextConfig.deploymentId || ''
if (!this.minimalMode) { if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode) this.imageResponseCache = new ResponseCache(this.minimalMode)
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
deploymentId: process.env.CUSTOM_DEPLOYMENT_ID, deploymentId: process.env.CUSTOM_DEPLOYMENT_ID,
experimental: {
useSkewCookie: Boolean(process.env.COOKIE_SKEW),
},
} }
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'node:path'
describe('deployment-id-handling disabled', () => {
const deploymentId = Date.now() + ''
const { next } = nextTestSetup({
files: join(__dirname, 'app'),
env: {
COOKIE_SKEW: '1',
NEXT_DEPLOYMENT_ID: 'thankyounext',
},
})
it('should set set-cookie header correctly', async () => {
const res = await next.fetch('/')
expect(res.headers.get('set-cookie')).toBe(
'__vdpl=thankyounext; Path=/; HttpOnly'
)
})
it.each([
{ urlPath: '/' },
{ urlPath: '/pages-edge' },
{ urlPath: '/from-app' },
{ urlPath: '/from-app/edge' },
])(
'should not append dpl query to all assets for $urlPath',
async ({ urlPath }) => {
const $ = await next.render$(urlPath)
expect($('#deploymentId').text()).not.toBe(deploymentId)
const scripts = Array.from($('script'))
expect(scripts.length).toBeGreaterThan(0)
for (const script of scripts) {
if (script.attribs.src) {
expect(script.attribs.src).not.toContain('dpl=' + deploymentId)
}
}
const links = Array.from($('link'))
expect(links.length).toBeGreaterThan(0)
for (const link of links) {
if (link.attribs.href) {
if (link.attribs.as === 'font') {
expect(link.attribs.href).not.toContain('dpl=' + deploymentId)
} else {
expect(link.attribs.href).not.toContain('dpl=' + deploymentId)
}
}
}
const browser = await next.browser(urlPath)
const requests = []
browser.on('request', (req) => {
requests.push(req.url())
})
await browser.elementByCss('#dynamic-import').click()
await check(
() => (requests.length > 0 ? 'success' : JSON.stringify(requests)),
'success'
)
try {
expect(
requests.every((item) => !item.includes('dpl=' + deploymentId))
).toBe(true)
} finally {
require('console').error('requests', requests)
}
}
)
})
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