Unverified Commit 2b9afcfe authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Change flight querystring to header (#40752)

parent 5f7caf27
...@@ -29,11 +29,9 @@ import { ...@@ -29,11 +29,9 @@ import {
} from './hooks-client-context' } from './hooks-client-context'
import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import { useReducerWithReduxDevtools } from './use-reducer-with-devtools'
function urlToUrlWithoutFlightParameters(url: string): URL { function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin) const urlWithoutFlightParameters = new URL(url, location.origin)
urlWithoutFlightParameters.searchParams.delete('__flight__') // TODO-APP: handle .rsc for static export case
urlWithoutFlightParameters.searchParams.delete('__flight_router_state_tree__')
urlWithoutFlightParameters.searchParams.delete('__flight_prefetch__')
return urlWithoutFlightParameters return urlWithoutFlightParameters
} }
...@@ -45,22 +43,26 @@ export async function fetchServerResponse( ...@@ -45,22 +43,26 @@ export async function fetchServerResponse(
flightRouterState: FlightRouterState, flightRouterState: FlightRouterState,
prefetch?: true prefetch?: true
): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> { ): Promise<[FlightData: FlightData, canonicalUrlOverride: URL | undefined]> {
const flightUrl = new URL(url) const headers: {
const searchParams = flightUrl.searchParams __flight__: '1'
// Enable flight response __flight_router_state_tree__: string
searchParams.append('__flight__', '1') __flight_prefetch__?: '1'
// Provide the current router state } = {
searchParams.append( // Enable flight response
'__flight_router_state_tree__', __flight__: '1',
JSON.stringify(flightRouterState) // Provide the current router state
) __flight_router_state_tree__: JSON.stringify(flightRouterState),
}
if (prefetch) { if (prefetch) {
searchParams.append('__flight_prefetch__', '1') // Enable prefetch response
headers.__flight_prefetch__ = '1'
} }
const res = await fetch(flightUrl.toString()) const res = await fetch(url.toString(), {
headers,
})
const canonicalUrl = res.redirected const canonicalUrl = res.redirected
? urlToUrlWithoutFlightParameters(res.url) ? urlToUrlWithoutFlightMarker(res.url)
: undefined : undefined
// Handle the `fetch` readable stream that can be unwrapped by `React.use`. // Handle the `fetch` readable stream that can be unwrapped by `React.use`.
......
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
...@@ -493,6 +493,20 @@ function getScriptNonceFromHeader(cspHeaderValue: string): string | undefined { ...@@ -493,6 +493,20 @@ function getScriptNonceFromHeader(cspHeaderValue: string): string | undefined {
return nonce return nonce
} }
const FLIGHT_PARAMETERS = [
'__flight__',
'__flight_router_state_tree__',
'__flight_prefetch__',
] as const
function headersWithoutFlight(headers: IncomingHttpHeaders) {
const newHeaders = { ...headers }
for (const param of FLIGHT_PARAMETERS) {
delete newHeaders[param]
}
return newHeaders
}
export async function renderToHTMLOrFlight( export async function renderToHTMLOrFlight(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -545,8 +559,8 @@ export async function renderToHTMLOrFlight( ...@@ -545,8 +559,8 @@ export async function renderToHTMLOrFlight(
ComponentMod, ComponentMod,
} = renderOpts } = renderOpts
const isFlight = query.__flight__ !== undefined const isFlight = req.headers.__flight__ !== undefined
const isPrefetch = query.__flight_prefetch__ !== undefined const isPrefetch = req.headers.__flight_prefetch__ !== undefined
// Handle client-side navigation to pages directory // Handle client-side navigation to pages directory
if (isFlight && isPagesDir) { if (isFlight && isPagesDir) {
...@@ -569,8 +583,8 @@ export async function renderToHTMLOrFlight( ...@@ -569,8 +583,8 @@ 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.
*/ */
const providedFlightRouterState: FlightRouterState = isFlight const providedFlightRouterState: FlightRouterState = isFlight
? query.__flight_router_state_tree__ ? req.headers.__flight_router_state_tree__
? JSON.parse(query.__flight_router_state_tree__ as string) ? JSON.parse(req.headers.__flight_router_state_tree__ as string)
: {} : {}
: undefined : undefined
...@@ -584,7 +598,7 @@ export async function renderToHTMLOrFlight( ...@@ -584,7 +598,7 @@ export async function renderToHTMLOrFlight(
| typeof import('../client/components/hot-reloader.client').default | typeof import('../client/components/hot-reloader.client').default
| null | null
const headers = req.headers const headers = headersWithoutFlight(req.headers)
// TODO-APP: fix type of req // TODO-APP: fix type of req
// @ts-expect-error // @ts-expect-error
const cookies = req.cookies const cookies = req.cookies
......
...@@ -1032,7 +1032,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1032,7 +1032,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Don't delete query.__flight__ yet, it still needs to be used in renderToHTML later // Don't delete query.__flight__ yet, it still needs to be used in renderToHTML later
const isFlightRequest = Boolean( const isFlightRequest = Boolean(
this.serverComponentManifest && query.__flight__ this.serverComponentManifest && req.headers.__flight__
) )
// we need to ensure the status code if /404 is visited directly // we need to ensure the status code if /404 is visited directly
......
...@@ -825,7 +825,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -825,7 +825,7 @@ export default class NextNodeServer extends BaseServer {
if ( if (
this.nextConfig.experimental.appDir && this.nextConfig.experimental.appDir &&
(renderOpts.isAppPath || query.__flight__) (renderOpts.isAppPath || req.headers.__flight__)
) { ) {
const isPagesDir = !renderOpts.isAppPath const isPagesDir = !renderOpts.isAppPath
return appRenderToHTMLOrFlight( return appRenderToHTMLOrFlight(
...@@ -981,7 +981,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -981,7 +981,6 @@ export default class NextNodeServer extends BaseServer {
__nextDataReq: query.__nextDataReq, __nextDataReq: query.__nextDataReq,
__nextLocale: query.__nextLocale, __nextLocale: query.__nextLocale,
__nextDefaultLocale: query.__nextDefaultLocale, __nextDefaultLocale: query.__nextDefaultLocale,
__flight__: query.__flight__,
} as NextParsedUrlQuery) } as NextParsedUrlQuery)
: query), : query),
// For appDir params is excluded. // For appDir params is excluded.
......
...@@ -35,6 +35,12 @@ class NextRequestHint extends NextRequest { ...@@ -35,6 +35,12 @@ class NextRequestHint extends NextRequest {
} }
} }
const FLIGHT_PARAMETERS = [
'__flight__',
'__flight_router_state_tree__',
'__flight_prefetch__',
] as const
export async function adapter(params: { export async function adapter(params: {
handler: NextMiddleware handler: NextMiddleware
page: string page: string
...@@ -58,11 +64,12 @@ export async function adapter(params: { ...@@ -58,11 +64,12 @@ export async function adapter(params: {
requestUrl.pathname = '/' requestUrl.pathname = '/'
} }
// Preserve flight data. const requestHeaders = fromNodeHeaders(params.request.headers)
const flightSearchParameters = requestUrl.flightSearchParameters
// Parameters should only be stripped for middleware // Parameters should only be stripped for middleware
if (!isEdgeRendering) { if (!isEdgeRendering) {
requestUrl.flightSearchParameters = undefined for (const param of FLIGHT_PARAMETERS) {
requestHeaders.delete(param)
}
} }
// Strip internal query parameters off the request. // Strip internal query parameters off the request.
...@@ -74,7 +81,7 @@ export async function adapter(params: { ...@@ -74,7 +81,7 @@ export async function adapter(params: {
init: { init: {
body: params.request.body, body: params.request.body,
geo: params.request.geo, geo: params.request.geo,
headers: fromNodeHeaders(params.request.headers), headers: requestHeaders,
ip: params.request.ip, ip: params.request.ip,
method: params.request.method, method: params.request.method,
nextConfig: params.request.nextConfig, nextConfig: params.request.nextConfig,
...@@ -112,8 +119,6 @@ export async function adapter(params: { ...@@ -112,8 +119,6 @@ export async function adapter(params: {
if (rewriteUrl.host === request.nextUrl.host) { if (rewriteUrl.host === request.nextUrl.host) {
rewriteUrl.buildId = buildId || rewriteUrl.buildId rewriteUrl.buildId = buildId || rewriteUrl.buildId
rewriteUrl.flightSearchParameters =
flightSearchParameters || rewriteUrl.flightSearchParameters
response.headers.set('x-middleware-rewrite', String(rewriteUrl)) response.headers.set('x-middleware-rewrite', String(rewriteUrl))
} }
...@@ -151,8 +156,6 @@ export async function adapter(params: { ...@@ -151,8 +156,6 @@ export async function adapter(params: {
if (redirectURL.host === request.nextUrl.host) { if (redirectURL.host === request.nextUrl.host) {
redirectURL.buildId = buildId || redirectURL.buildId redirectURL.buildId = buildId || redirectURL.buildId
redirectURL.flightSearchParameters =
flightSearchParameters || redirectURL.flightSearchParameters
response.headers.set('Location', String(redirectURL)) response.headers.set('Location', String(redirectURL))
} }
......
...@@ -15,12 +15,6 @@ interface Options { ...@@ -15,12 +15,6 @@ interface Options {
} }
} }
const FLIGHT_PARAMETERS = [
'__flight__',
'__flight_router_state_tree__',
'__flight_prefetch__',
] as const
const REGEX_LOCALHOST_HOSTNAME = const REGEX_LOCALHOST_HOSTNAME =
/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1|localhost)/ /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1|localhost)/
...@@ -31,28 +25,6 @@ function parseURL(url: string | URL, base?: string | URL) { ...@@ -31,28 +25,6 @@ function parseURL(url: string | URL, base?: string | URL) {
) )
} }
function parseFlightParameters(
searchParams: URLSearchParams
): Record<string, string> | undefined {
let flightSearchParameters: Record<string, string> = {}
let flightSearchParametersUpdated = false
for (const name of FLIGHT_PARAMETERS) {
const value = searchParams.get(name)
if (value === null) {
continue
}
flightSearchParameters[name] = value
flightSearchParametersUpdated = true
}
if (!flightSearchParametersUpdated) {
return undefined
}
return flightSearchParameters
}
const Internal = Symbol('NextURLInternal') const Internal = Symbol('NextURLInternal')
export class NextURL { export class NextURL {
...@@ -118,9 +90,6 @@ export class NextURL { ...@@ -118,9 +90,6 @@ export class NextURL {
this[Internal].buildId = pathnameInfo.buildId this[Internal].buildId = pathnameInfo.buildId
this[Internal].locale = pathnameInfo.locale ?? defaultLocale this[Internal].locale = pathnameInfo.locale ?? defaultLocale
this[Internal].trailingSlash = pathnameInfo.trailingSlash this[Internal].trailingSlash = pathnameInfo.trailingSlash
this[Internal].flightSearchParameters = parseFlightParameters(
this[Internal].url.searchParams
)
} }
private formatPathname() { private formatPathname() {
...@@ -137,22 +106,7 @@ export class NextURL { ...@@ -137,22 +106,7 @@ export class NextURL {
} }
private formatSearch() { private formatSearch() {
const flightSearchParameters = this[Internal].flightSearchParameters return this[Internal].url.search
// If no flight parameters are set, return the search string as is.
// This is a fast path to ensure URLSearchParams only has to be recreated on Flight requests.
if (!flightSearchParameters) {
return this[Internal].url.search
}
// Create separate URLSearchParams to ensure the original search string is not modified.
const searchParams = new URLSearchParams(this[Internal].url.searchParams)
// If any exist this loop is always limited to the amount of FLIGHT_PARAMETERS.
for (const name in flightSearchParameters) {
searchParams.set(name, flightSearchParameters[name])
}
const params = searchParams.toString()
return params === '' ? '' : `?${params}`
} }
public get buildId() { public get buildId() {
...@@ -163,32 +117,6 @@ export class NextURL { ...@@ -163,32 +117,6 @@ export class NextURL {
this[Internal].buildId = buildId this[Internal].buildId = buildId
} }
public get flightSearchParameters() {
return this[Internal].flightSearchParameters
}
public set flightSearchParameters(
flightSearchParams: Record<string, string> | undefined
) {
if (flightSearchParams) {
for (const name of FLIGHT_PARAMETERS) {
// Ensure only the provided values are set
if (flightSearchParams[name]) {
this[Internal].url.searchParams.set(name, flightSearchParams[name])
} else {
// Delete the ones that are not provided as flightData should be overridden.
this[Internal].url.searchParams.delete(name)
}
}
} else {
for (const name of FLIGHT_PARAMETERS) {
this[Internal].url.searchParams.delete(name)
}
}
this[Internal].flightSearchParameters = flightSearchParams
}
public get locale() { public get locale() {
return this[Internal].locale ?? '' return this[Internal].locale ?? ''
} }
......
...@@ -20,7 +20,7 @@ export function middleware(request) { ...@@ -20,7 +20,7 @@ export function middleware(request) {
: 'redirect' : 'redirect'
const internal = ['__flight__', '__flight_router_state_tree__'] const internal = ['__flight__', '__flight_router_state_tree__']
if (internal.some((name) => request.nextUrl.searchParams.has(name))) { if (internal.some((name) => request.headers.has(name))) {
return NextResponse[method](new URL('/internal/failure', request.url)) return NextResponse[method](new URL('/internal/failure', request.url))
} }
......
...@@ -38,13 +38,28 @@ describe('app dir', () => { ...@@ -38,13 +38,28 @@ describe('app dir', () => {
it('should use application/octet-stream for flight', async () => { it('should use application/octet-stream for flight', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
next.url, next.url,
'/dashboard/deployments/123?__flight__' '/dashboard/deployments/123',
{},
{
headers: {
__flight__: '1',
},
}
) )
expect(res.headers.get('Content-Type')).toBe('application/octet-stream') expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
}) })
it('should use application/octet-stream for flight with edge runtime', async () => { it('should use application/octet-stream for flight with edge runtime', async () => {
const res = await fetchViaHTTP(next.url, '/dashboard?__flight__') const res = await fetchViaHTTP(
next.url,
'/dashboard',
{},
{
headers: {
__flight__: '1',
},
}
)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream') expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
}) })
......
...@@ -94,7 +94,8 @@ describe('app dir - react server components', () => { ...@@ -94,7 +94,8 @@ describe('app dir - react server components', () => {
'__nextDefaultLocale', '__nextDefaultLocale',
'__nextIsNotFound', '__nextIsNotFound',
'__flight__', '__flight__',
'__flight_router_path__', '__flight_router_state_tree__',
'__flight_prefetch__',
] ]
const hasNextInternalQuery = inlineFlightContents.some((content) => const hasNextInternalQuery = inlineFlightContents.some((content) =>
...@@ -110,14 +111,15 @@ describe('app dir - react server components', () => { ...@@ -110,14 +111,15 @@ describe('app dir - react server components', () => {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
requestsCount++ requestsCount++
const url = request.url() return request.allHeaders().then((headers) => {
if ( if (
url.includes('__flight__=1') && headers.__flight__ === '1' &&
// Prefetches also include `__flight__` // Prefetches also include `__flight__`
!url.includes('__flight_prefetch__=1') headers.__flight_prefetch__ !== '1'
) { ) {
hasFlightRequest = true hasFlightRequest = true
} }
})
}) })
}, },
}) })
...@@ -215,14 +217,14 @@ describe('app dir - react server components', () => { ...@@ -215,14 +217,14 @@ describe('app dir - react server components', () => {
const browser = await webdriver(next.url, '/root', { const browser = await webdriver(next.url, '/root', {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
const url = request.url() return request.allHeaders().then((headers) => {
if ( if (
url.includes('__flight__=1') && headers.__flight__ === '1' &&
// Prefetches also include `__flight__` headers.__flight_prefetch__ !== '1'
!url.includes('__flight_prefetch__=1') ) {
) { hasFlightRequest = true
hasFlightRequest = true }
} })
}) })
}, },
}) })
...@@ -336,7 +338,16 @@ describe('app dir - react server components', () => { ...@@ -336,7 +338,16 @@ describe('app dir - react server components', () => {
}) })
it('should support streaming for flight response', async () => { it('should support streaming for flight response', async () => {
await fetchViaHTTP(next.url, '/?__flight__=1').then(async (response) => { await fetchViaHTTP(
next.url,
'/',
{},
{
headers: {
__flight__: '1',
},
}
).then(async (response) => {
const result = await resolveStreamResponse(response) const result = await resolveStreamResponse(response)
expect(result).toContain('component:index.server') expect(result).toContain('component:index.server')
}) })
......
...@@ -119,10 +119,11 @@ describe('Switchable runtime', () => { ...@@ -119,10 +119,11 @@ describe('Switchable runtime', () => {
const browser = await webdriver(context.appPort, '/node', { const browser = await webdriver(context.appPort, '/node', {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
const url = request.url() return request.allHeaders().then((headers) => {
if (/\?__flight__=1/.test(url)) { if (headers.__flight__ === '1') {
flightRequest = url flightRequest = request.url()
} }
})
}) })
}, },
}) })
...@@ -136,7 +137,7 @@ describe('Switchable runtime', () => { ...@@ -136,7 +137,7 @@ describe('Switchable runtime', () => {
() => browser.eval('document.documentElement.innerHTML'), () => browser.eval('document.documentElement.innerHTML'),
/This is a SSR RSC page/ /This is a SSR RSC page/
) )
expect(flightRequest).toContain('/node-rsc-ssr?__flight__=1') expect(flightRequest).toContain('/node-rsc-ssr')
}) })
it.skip('should support client side navigation to ssg rsc pages', async () => { it.skip('should support client side navigation to ssg rsc pages', async () => {
...@@ -678,10 +679,11 @@ describe('Switchable runtime', () => { ...@@ -678,10 +679,11 @@ describe('Switchable runtime', () => {
const browser = await webdriver(context.appPort, '/node', { const browser = await webdriver(context.appPort, '/node', {
beforePageLoad(page) { beforePageLoad(page) {
page.on('request', (request) => { page.on('request', (request) => {
const url = request.url() request.allHeaders().then((headers) => {
if (/\?__flight__=1/.test(url)) { if (headers.__flight__ === '1') {
flightRequest = url flightRequest = request.url()
} }
})
}) })
}, },
}) })
...@@ -691,7 +693,7 @@ describe('Switchable runtime', () => { ...@@ -691,7 +693,7 @@ describe('Switchable runtime', () => {
expect(await browser.elementByCss('body').text()).toContain( expect(await browser.elementByCss('body').text()).toContain(
'This is a SSR RSC page.' 'This is a SSR RSC page.'
) )
expect(flightRequest).toContain('/node-rsc-ssr?__flight__=1') expect(flightRequest).toContain('/node-rsc-ssr')
}) })
it.skip('should support client side navigation to ssg rsc pages', async () => { it.skip('should support client side navigation to ssg rsc pages', async () => {
......
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