Unverified Commit 2358e9c2 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Rename RSC and Router headers (#42482)

Removes the `_` prefix from the RSC and Router headers as nginx strips
`_` prefixed headers by default.

Fixes #42164

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent c5bccf4d
...@@ -123,6 +123,7 @@ import { RemotePattern } from '../shared/lib/image-config' ...@@ -123,6 +123,7 @@ import { RemotePattern } from '../shared/lib/image-config'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins' import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin' import { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import { RSC, RSC_VARY_HEADER } from '../client/components/app-router-headers'
export type SsgRoute = { export type SsgRoute = {
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
...@@ -755,6 +756,10 @@ export default async function build( ...@@ -755,6 +756,10 @@ export default async function build(
defaultLocale: string defaultLocale: string
localeDetection?: false localeDetection?: false
} }
rsc: {
header: typeof RSC
varyHeader: typeof RSC_VARY_HEADER
}
} = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => { } = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => {
const sortedRoutes = getSortedRoutes([ const sortedRoutes = getSortedRoutes([
...pageKeys.pages, ...pageKeys.pages,
...@@ -781,6 +786,10 @@ export default async function build( ...@@ -781,6 +786,10 @@ export default async function build(
staticRoutes, staticRoutes,
dataRoutes: [], dataRoutes: [],
i18n: config.i18n || undefined, i18n: config.i18n || undefined,
rsc: {
header: RSC,
varyHeader: RSC_VARY_HEADER,
},
} }
}) })
......
export const RSC = 'RSC' as const
export const NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree' as const
export const NEXT_ROUTER_PREFETCH = 'Next-Router-Prefetch' as const
export const RSC_VARY_HEADER =
`${RSC}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH}` as const
...@@ -29,6 +29,11 @@ import { ...@@ -29,6 +29,11 @@ import {
} from '../../shared/lib/hooks-client-context' } from '../../shared/lib/hooks-client-context'
import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import { useReducerWithReduxDevtools } from './use-reducer-with-devtools'
import { ErrorBoundary, GlobalErrorComponent } from './error-boundary' import { ErrorBoundary, GlobalErrorComponent } from './error-boundary'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
RSC,
} from './app-router-headers'
function urlToUrlWithoutFlightMarker(url: string): URL { function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin) const urlWithoutFlightParameters = new URL(url, location.origin)
...@@ -53,18 +58,18 @@ export async function fetchServerResponse( ...@@ -53,18 +58,18 @@ export async function fetchServerResponse(
prefetch?: true prefetch?: true
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> { ): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
const headers: { const headers: {
__rsc__: '1' [RSC]: '1'
__next_router_state_tree__: string [NEXT_ROUTER_STATE_TREE]: string
__next_router_prefetch__?: '1' [NEXT_ROUTER_PREFETCH]?: '1'
} = { } = {
// Enable flight response // Enable flight response
__rsc__: '1', [RSC]: '1',
// Provide the current router state // Provide the current router state
__next_router_state_tree__: JSON.stringify(flightRouterState), [NEXT_ROUTER_STATE_TREE]: JSON.stringify(flightRouterState),
} }
if (prefetch) { if (prefetch) {
// Enable prefetch response // Enable prefetch response
headers.__next_router_prefetch__ = '1' headers[NEXT_ROUTER_PREFETCH] = '1'
} }
const res = await fetch(url.toString(), { const res = await fetch(url.toString(), {
......
...@@ -38,6 +38,11 @@ import { NOT_FOUND_ERROR_CODE } from '../client/components/not-found' ...@@ -38,6 +38,11 @@ import { NOT_FOUND_ERROR_CODE } from '../client/components/not-found'
import { HeadManagerContext } from '../shared/lib/head-manager-context' import { HeadManagerContext } from '../shared/lib/head-manager-context'
import { Writable } from 'stream' import { Writable } from 'stream'
import stringHash from 'next/dist/compiled/string-hash' import stringHash from 'next/dist/compiled/string-hash'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
RSC,
} from '../client/components/app-router-headers'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -686,16 +691,16 @@ function getScriptNonceFromHeader(cspHeaderValue: string): string | undefined { ...@@ -686,16 +691,16 @@ function getScriptNonceFromHeader(cspHeaderValue: string): string | undefined {
return nonce return nonce
} }
const FLIGHT_PARAMETERS = [ export const FLIGHT_PARAMETERS = [
'__rsc__', [RSC],
'__next_router_state_tree__', [NEXT_ROUTER_STATE_TREE],
'__next_router_prefetch__', [NEXT_ROUTER_PREFETCH],
] as const ] as const
function headersWithoutFlight(headers: IncomingHttpHeaders) { function headersWithoutFlight(headers: IncomingHttpHeaders) {
const newHeaders = { ...headers } const newHeaders = { ...headers }
for (const param of FLIGHT_PARAMETERS) { for (const param of FLIGHT_PARAMETERS) {
delete newHeaders[param] delete newHeaders[param.toString().toLowerCase()]
} }
return newHeaders return newHeaders
} }
...@@ -728,7 +733,7 @@ export async function renderToHTMLOrFlight( ...@@ -728,7 +733,7 @@ export async function renderToHTMLOrFlight(
*/ */
const isStaticGeneration = const isStaticGeneration =
renderOpts.supportsDynamicHTML !== true && !renderOpts.isBot renderOpts.supportsDynamicHTML !== true && !renderOpts.isBot
const isFlight = req.headers.__rsc__ !== undefined const isFlight = req.headers[RSC.toLowerCase()] !== undefined
const capturedErrors: Error[] = [] const capturedErrors: Error[] = []
const allCapturedErrors: Error[] = [] const allCapturedErrors: Error[] = []
...@@ -786,7 +791,8 @@ export async function renderToHTMLOrFlight( ...@@ -786,7 +791,8 @@ export async function renderToHTMLOrFlight(
// don't modify original query object // don't modify original query object
query = Object.assign({}, query) query = Object.assign({}, query)
const isPrefetch = req.headers.__next_router_prefetch__ !== undefined const isPrefetch =
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] !== undefined
// TODO-APP: verify the tree is valid // TODO-APP: verify the tree is valid
// TODO-APP: verify query param is single value (not an array) // TODO-APP: verify query param is single value (not an array)
...@@ -795,8 +801,10 @@ export async function renderToHTMLOrFlight( ...@@ -795,8 +801,10 @@ export async function renderToHTMLOrFlight(
* Router state provided from the client-side router. Used to handle rendering from the common layout down. * Router state provided from the client-side router. Used to handle rendering from the common layout down.
*/ */
let providedFlightRouterState: FlightRouterState = isFlight let providedFlightRouterState: FlightRouterState = isFlight
? req.headers.__next_router_state_tree__ ? req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
? JSON.parse(req.headers.__next_router_state_tree__ as string) ? JSON.parse(
req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()] as string
)
: undefined : undefined
: undefined : undefined
......
...@@ -74,6 +74,8 @@ import { getHostname } from '../shared/lib/get-hostname' ...@@ -74,6 +74,8 @@ import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { MiddlewareMatcher } from '../build/analysis/get-page-static-info' import { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import { RSC, RSC_VARY_HEADER } from '../client/components/app-router-headers'
import { FLIGHT_PARAMETERS } from './app-render'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -1053,12 +1055,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1053,12 +1055,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
(isSSG || hasServerProps) (isSSG || hasServerProps)
if (isAppPath) { if (isAppPath) {
res.setHeader( res.setHeader('vary', RSC_VARY_HEADER)
'vary',
'__rsc__, __next_router_state_tree__, __next_router_prefetch__'
)
if (isSSG && req.headers['__rsc__']) { if (isSSG && req.headers[RSC.toLowerCase()]) {
if (!this.minimalMode) { if (!this.minimalMode) {
isDataReq = true isDataReq = true
} }
...@@ -1067,9 +1066,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1067,9 +1066,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
opts.runtime !== 'experimental-edge' || opts.runtime !== 'experimental-edge' ||
(this.serverOptions as any).webServerConfig (this.serverOptions as any).webServerConfig
) { ) {
delete req.headers['__rsc__'] for (const param of FLIGHT_PARAMETERS) {
delete req.headers['__next_router_state_tree__'] delete req.headers[param.toString().toLowerCase()]
delete req.headers['__next_router_prefetch__'] }
} }
} }
} }
...@@ -1096,9 +1095,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1096,9 +1095,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) )
} }
// Don't delete query.__rsc__ yet, it still needs to be used in renderToHTML later // Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isFlightRequest = Boolean( const isFlightRequest = Boolean(
this.serverComponentManifest && req.headers.__rsc__ this.serverComponentManifest && req.headers[RSC.toLowerCase()]
) )
// we need to ensure the status code if /404 is visited directly // we need to ensure the status code if /404 is visited directly
......
...@@ -5,11 +5,6 @@ const INTERNAL_QUERY_NAMES = [ ...@@ -5,11 +5,6 @@ const INTERNAL_QUERY_NAMES = [
'__nextLocale', '__nextLocale',
'__nextDefaultLocale', '__nextDefaultLocale',
'__nextIsNotFound', '__nextIsNotFound',
// RSC
'__rsc__',
// Routing
'__next_router_state_tree__',
'__next_router_prefetch__',
] as const ] as const
const EXTENDED_INTERNAL_QUERY_NAMES = ['__nextDataReq'] as const const EXTENDED_INTERNAL_QUERY_NAMES = ['__nextDataReq'] as const
......
...@@ -10,6 +10,11 @@ import { waitUntilSymbol } from './spec-extension/fetch-event' ...@@ -10,6 +10,11 @@ import { waitUntilSymbol } from './spec-extension/fetch-event'
import { NextURL } from './next-url' import { NextURL } from './next-url'
import { stripInternalSearchParams } from '../internal-utils' import { stripInternalSearchParams } from '../internal-utils'
import { normalizeRscPath } from '../../shared/lib/router/utils/app-paths' import { normalizeRscPath } from '../../shared/lib/router/utils/app-paths'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
RSC,
} from '../../client/components/app-router-headers'
class NextRequestHint extends NextRequest { class NextRequestHint extends NextRequest {
sourcePage: string sourcePage: string
...@@ -37,9 +42,9 @@ class NextRequestHint extends NextRequest { ...@@ -37,9 +42,9 @@ class NextRequestHint extends NextRequest {
} }
const FLIGHT_PARAMETERS = [ const FLIGHT_PARAMETERS = [
'__rsc__', [RSC],
'__next_router_state_tree__', [NEXT_ROUTER_STATE_TREE],
'__next_router_prefetch__', [NEXT_ROUTER_PREFETCH],
] as const ] as const
export async function adapter(params: { export async function adapter(params: {
...@@ -71,7 +76,7 @@ export async function adapter(params: { ...@@ -71,7 +76,7 @@ export async function adapter(params: {
// Parameters should only be stripped for middleware // Parameters should only be stripped for middleware
if (!isEdgeRendering) { if (!isEdgeRendering) {
for (const param of FLIGHT_PARAMETERS) { for (const param of FLIGHT_PARAMETERS) {
requestHeaders.delete(param) requestHeaders.delete(param.toString().toLowerCase())
} }
} }
......
...@@ -35,8 +35,8 @@ export function middleware(request) { ...@@ -35,8 +35,8 @@ export function middleware(request) {
? 'rewrite' ? 'rewrite'
: 'redirect' : 'redirect'
const internal = ['__rsc__', '__next_router_state_tree__'] const internal = ['RSC', 'Next-Router-State-Tree']
if (internal.some((name) => request.headers.has(name))) { if (internal.some((name) => request.headers.has(name.toLowerCase()))) {
return NextResponse[method](new URL('/internal/failure', request.url)) return NextResponse[method](new URL('/internal/failure', request.url))
} }
......
...@@ -84,7 +84,7 @@ describe('app dir', () => { ...@@ -84,7 +84,7 @@ describe('app dir', () => {
{}, {},
{ {
headers: { headers: {
__rsc__: '1', ['RSC'.toString()]: '1',
}, },
} }
) )
...@@ -98,7 +98,7 @@ describe('app dir', () => { ...@@ -98,7 +98,7 @@ describe('app dir', () => {
{}, {},
{ {
headers: { headers: {
__rsc__: '1', ['RSC'.toString()]: '1',
}, },
} }
) )
......
...@@ -88,9 +88,6 @@ describe('app dir - rsc basics', () => { ...@@ -88,9 +88,6 @@ describe('app dir - rsc basics', () => {
'__nextLocale', '__nextLocale',
'__nextDefaultLocale', '__nextDefaultLocale',
'__nextIsNotFound', '__nextIsNotFound',
'__rsc__',
'__next_router_state_tree__',
'__next_router_prefetch__',
] ]
const hasNextInternalQuery = inlineFlightContents.some((content) => const hasNextInternalQuery = inlineFlightContents.some((content) =>
...@@ -108,9 +105,9 @@ describe('app dir - rsc basics', () => { ...@@ -108,9 +105,9 @@ describe('app dir - rsc basics', () => {
requestsCount++ requestsCount++
return request.allHeaders().then((headers) => { return request.allHeaders().then((headers) => {
if ( if (
headers.__rsc__ === '1' && headers['RSC'.toLowerCase()] === '1' &&
// Prefetches also include `__rsc__` // Prefetches also include `RSC`
headers.__next_router_prefetch__ !== '1' headers['Next-Router-Prefetch'.toLowerCase()] !== '1'
) { ) {
hasFlightRequest = true hasFlightRequest = true
} }
...@@ -185,41 +182,18 @@ describe('app dir - rsc basics', () => { ...@@ -185,41 +182,18 @@ describe('app dir - rsc basics', () => {
} }
}) })
it('should refresh correctly with next/link', async () => { it('should link correctly with next/link without mpa navigation to the page', async () => {
// Select the button which is not hidden but rendered // Select the button which is not hidden but rendered
const selector = '#goto-next-link' const selector = '#goto-next-link'
let hasFlightRequest = false const browser = await webdriver(next.url, '/root', {})
const browser = await webdriver(next.url, '/root', {
beforePageLoad(page) {
page.on('request', (request) => {
return request.allHeaders().then((headers) => {
if (
headers.__rsc__ === '1' &&
headers.__next_router_prefetch__ !== '1'
) {
hasFlightRequest = true
}
})
})
},
})
// wait for hydration await browser.eval('window.didNotReloadPage = true')
await new Promise((res) => setTimeout(res, 1000)) await browser.elementByCss(selector).click().waitForElementByCss('#query')
if (isNextDev) {
expect(hasFlightRequest).toBe(false)
}
await browser.elementByCss(selector).click()
// wait for re-hydration expect(await browser.eval('window.didNotReloadPage')).toBe(true)
if (isNextDev) {
await check( const text = await browser.elementByCss('#query').text()
() => (hasFlightRequest ? 'success' : hasFlightRequest), expect(text).toBe('query:0')
'success'
)
}
const refreshText = await browser.elementByCss(selector).text()
expect(refreshText).toBe('next link')
}) })
it('should escape streaming data correctly', async () => { it('should escape streaming data correctly', async () => {
...@@ -381,7 +355,7 @@ describe('app dir - rsc basics', () => { ...@@ -381,7 +355,7 @@ describe('app dir - rsc basics', () => {
{}, {},
{ {
headers: { headers: {
__rsc__: '1', ['RSC'.toString()]: '1',
}, },
} }
).then(async (response) => { ).then(async (response) => {
......
...@@ -120,7 +120,7 @@ describe('Switchable runtime', () => { ...@@ -120,7 +120,7 @@ describe('Switchable runtime', () => {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
return request.allHeaders().then((headers) => { return request.allHeaders().then((headers) => {
if (headers.__rsc__ === '1') { if (headers['RSC'.toLowerCase()] === '1') {
flightRequest = request.url() flightRequest = request.url()
} }
}) })
...@@ -680,7 +680,7 @@ describe('Switchable runtime', () => { ...@@ -680,7 +680,7 @@ describe('Switchable runtime', () => {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
request.allHeaders().then((headers) => { request.allHeaders().then((headers) => {
if (headers.__rsc__ === '1') { if (headers['RSC'.toLowerCase()] === '1') {
flightRequest = request.url() flightRequest = request.url()
} }
}) })
......
...@@ -2215,6 +2215,10 @@ const runTests = (isDev = false) => { ...@@ -2215,6 +2215,10 @@ const runTests = (isDev = false) => {
routeKeys: {}, routeKeys: {},
}, },
], ],
rsc: {
header: 'RSC',
varyHeader: 'RSC, Next-Router-State-Tree, Next-Router-Prefetch',
},
}) })
}) })
......
...@@ -1426,6 +1426,10 @@ function runTests({ dev }) { ...@@ -1426,6 +1426,10 @@ function runTests({ dev }) {
}, },
}, },
], ],
rsc: {
header: 'RSC',
varyHeader: 'RSC, Next-Router-State-Tree, Next-Router-Prefetch',
},
}) })
}) })
......
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