Unverified Commit ade52553 authored by Gerald Monaco's avatar Gerald Monaco Committed by GitHub

Add `RequestContext` (#27303)

How a page is rendered depends on whether or not we're streaming. For example, if we're just rendering to a `string` or we're generating a response for a crawler or other robot, we don't want React 18 to dynamically flush `<script>` tags to update Suspense boundaries as they resolve. Instead, we just want to wait for the full HTML to resolve and return a result similar to `renderToString`.

This is what `RequestContext` and the new/refactored `pipe` and `getStaticHTML` methods allow.  They add a `requireStaticHTML` option that gets passed down. A follow-up PR will make sure this is `true` when serving a robot, and also ensure React is invoked appropriately.
parent a96739fc
...@@ -134,6 +134,14 @@ export type ServerConstructor = { ...@@ -134,6 +134,14 @@ export type ServerConstructor = {
customServer?: boolean customServer?: boolean
} }
type RequestContext = {
req: IncomingMessage
res: ServerResponse
pathname: string
query: ParsedUrlQuery
renderOpts: RenderOptsPartial
}
export default class Server { export default class Server {
protected dir: string protected dir: string
protected quiet: boolean protected quiet: boolean
...@@ -1313,11 +1321,30 @@ export default class Server { ...@@ -1313,11 +1321,30 @@ export default class Server {
await this.render404(req, res, parsedUrl) await this.render404(req, res, parsedUrl)
} }
protected async sendResponse( private async pipe(
req: IncomingMessage, fn: (ctx: RequestContext) => Promise<ResponsePayload | null>,
res: ServerResponse, partialContext: {
{ type, body, revalidateOptions }: ResponsePayload req: IncomingMessage
res: ServerResponse
pathname: string
query: ParsedUrlQuery
}
): Promise<void> { ): Promise<void> {
// TODO: Determine when dynamic HTML is allowed
const requireStaticHTML = true
const ctx = {
...partialContext,
renderOpts: {
...this.renderOpts,
requireStaticHTML,
},
} as const
const payload = await fn(ctx)
if (payload === null) {
return
}
const { req, res } = ctx
const { body, type, revalidateOptions } = payload
if (!isResSent(res)) { if (!isResSent(res)) {
const { generateEtags, poweredByHeader, dev } = this.renderOpts const { generateEtags, poweredByHeader, dev } = this.renderOpts
if (dev) { if (dev) {
...@@ -1338,6 +1365,25 @@ export default class Server { ...@@ -1338,6 +1365,25 @@ export default class Server {
} }
} }
private async getStaticHTML(
fn: (ctx: RequestContext) => Promise<ResponsePayload | null>,
partialContext: {
req: IncomingMessage
res: ServerResponse
pathname: string
query: ParsedUrlQuery
}
): Promise<string | null> {
const payload = await fn({
...partialContext,
renderOpts: {
...this.renderOpts,
requireStaticHTML: true,
},
})
return payload ? payload.body : null
}
public async render( public async render(
req: IncomingMessage, req: IncomingMessage,
res: ServerResponse, res: ServerResponse,
...@@ -1385,13 +1431,12 @@ export default class Server { ...@@ -1385,13 +1431,12 @@ export default class Server {
return this.render404(req, res, parsedUrl) return this.render404(req, res, parsedUrl)
} }
const response = await this.renderToResponse(req, res, pathname, query) return this.pipe((ctx) => this.renderToResponse(ctx), {
// Request was ended by the user req,
if (response === null) { res,
return pathname,
} query,
})
return this.sendResponse(req, res, response)
} }
protected async findPageComponents( protected async findPageComponents(
...@@ -1479,11 +1524,8 @@ export default class Server { ...@@ -1479,11 +1524,8 @@ export default class Server {
} }
private async renderToResponseWithComponents( private async renderToResponseWithComponents(
req: IncomingMessage, { req, res, pathname, renderOpts: opts }: RequestContext,
res: ServerResponse, { components, query }: FindComponentsResult
pathname: string,
{ components, query }: FindComponentsResult,
opts: RenderOptsPartial
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
const is404Page = pathname === '/404' const is404Page = pathname === '/404'
const is500Page = pathname === '/500' const is500Page = pathname === '/500'
...@@ -1863,11 +1905,9 @@ export default class Server { ...@@ -1863,11 +1905,9 @@ export default class Server {
} }
private async renderToResponse( private async renderToResponse(
req: IncomingMessage, ctx: RequestContext
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {}
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
const { res, query, pathname } = ctx
const bubbleNoFallback = !!query._nextBubbleNoFallback const bubbleNoFallback = !!query._nextBubbleNoFallback
delete query._nextBubbleNoFallback delete query._nextBubbleNoFallback
...@@ -1875,13 +1915,7 @@ export default class Server { ...@@ -1875,13 +1915,7 @@ export default class Server {
const result = await this.findPageComponents(pathname, query) const result = await this.findPageComponents(pathname, query)
if (result) { if (result) {
try { try {
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(ctx, result)
req,
res,
pathname,
result,
{ ...this.renderOpts }
)
} catch (err) { } catch (err) {
const isNoFallbackError = err instanceof NoFallbackError const isNoFallbackError = err instanceof NoFallbackError
...@@ -1906,11 +1940,15 @@ export default class Server { ...@@ -1906,11 +1940,15 @@ export default class Server {
if (dynamicRouteResult) { if (dynamicRouteResult) {
try { try {
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
req, {
res, ...ctx,
dynamicRoute.page, pathname: dynamicRoute.page,
dynamicRouteResult, renderOpts: {
{ ...this.renderOpts, params } ...ctx.renderOpts,
params,
},
},
dynamicRouteResult
) )
} catch (err) { } catch (err) {
const isNoFallbackError = err instanceof NoFallbackError const isNoFallbackError = err instanceof NoFallbackError
...@@ -1931,17 +1969,14 @@ export default class Server { ...@@ -1931,17 +1969,14 @@ export default class Server {
} }
if (err instanceof DecodeError) { if (err instanceof DecodeError) {
res.statusCode = 400 res.statusCode = 400
return await this.renderErrorToResponse(err, req, res, pathname, query) return await this.renderErrorToResponse(ctx, err)
} }
res.statusCode = 500 res.statusCode = 500
const isWrappedError = err instanceof WrappedBuildError const isWrappedError = err instanceof WrappedBuildError
const response = await this.renderErrorToResponse( const response = await this.renderErrorToResponse(
isWrappedError ? err.innerError : err, ctx,
req, isWrappedError ? err.innerError : err
res,
pathname,
query
) )
if (!isWrappedError) { if (!isWrappedError) {
...@@ -1953,7 +1988,7 @@ export default class Server { ...@@ -1953,7 +1988,7 @@ export default class Server {
return response return response
} }
res.statusCode = 404 res.statusCode = 404
return this.renderErrorToResponse(null, req, res, pathname, query) return this.renderErrorToResponse(ctx, null)
} }
public async renderToHTML( public async renderToHTML(
...@@ -1962,8 +1997,12 @@ export default class Server { ...@@ -1962,8 +1997,12 @@ export default class Server {
pathname: string, pathname: string,
query: ParsedUrlQuery = {} query: ParsedUrlQuery = {}
): Promise<string | null> { ): Promise<string | null> {
const response = await this.renderToResponse(req, res, pathname, query) return this.getStaticHTML((ctx) => this.renderToResponse(ctx), {
return response ? response.body : null req,
res,
pathname,
query,
})
} }
public async renderError( public async renderError(
...@@ -1980,21 +2019,17 @@ export default class Server { ...@@ -1980,21 +2019,17 @@ export default class Server {
'no-cache, no-store, max-age=0, must-revalidate' 'no-cache, no-store, max-age=0, must-revalidate'
) )
} }
const response = await this.renderErrorToResponse(
err,
req,
res,
pathname,
query
)
if (this.minimalMode && res.statusCode === 500) { return this.pipe(
throw err async (ctx) => {
} const response = await this.renderErrorToResponse(ctx, err)
if (response === null) { if (this.minimalMode && res.statusCode === 500) {
return throw err
} }
return this.sendResponse(req, res, response) return response
},
{ req, res, pathname, query }
)
} }
private customErrorNo404Warn = execOnce(() => { private customErrorNo404Warn = execOnce(() => {
...@@ -2007,12 +2042,10 @@ export default class Server { ...@@ -2007,12 +2042,10 @@ export default class Server {
}) })
private async renderErrorToResponse( private async renderErrorToResponse(
_err: Error | null, ctx: RequestContext,
req: IncomingMessage, _err: Error | null
res: ServerResponse,
_pathname: string,
query: ParsedUrlQuery = {}
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
const { res, query } = ctx
let err = _err let err = _err
if (this.renderOpts.dev && !err && res.statusCode === 500) { if (this.renderOpts.dev && !err && res.statusCode === 500) {
err = new Error( err = new Error(
...@@ -2053,14 +2086,15 @@ export default class Server { ...@@ -2053,14 +2086,15 @@ export default class Server {
try { try {
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
req,
res,
statusPage,
result!,
{ {
...this.renderOpts, ...ctx,
err, pathname: statusPage,
} renderOpts: {
...ctx.renderOpts,
err,
},
},
result!
) )
} catch (maybeFallbackError) { } catch (maybeFallbackError) {
if (maybeFallbackError instanceof NoFallbackError) { if (maybeFallbackError instanceof NoFallbackError) {
...@@ -2078,20 +2112,21 @@ export default class Server { ...@@ -2078,20 +2112,21 @@ export default class Server {
if (fallbackComponents) { if (fallbackComponents) {
return this.renderToResponseWithComponents( return this.renderToResponseWithComponents(
req,
res,
'/_error',
{ {
query, ...ctx,
components: fallbackComponents, pathname: '/_error',
renderOpts: {
...ctx.renderOpts,
// We render `renderToHtmlError` here because `err` is
// already captured in the stacktrace.
err: isWrappedError
? renderToHtmlError.innerError
: renderToHtmlError,
},
}, },
{ {
...this.renderOpts, query,
// We render `renderToHtmlError` here because `err` is components: fallbackComponents,
// already captured in the stacktrace.
err: isWrappedError
? renderToHtmlError.innerError
: renderToHtmlError,
} }
) )
} }
...@@ -2109,14 +2144,12 @@ export default class Server { ...@@ -2109,14 +2144,12 @@ export default class Server {
pathname: string, pathname: string,
query: ParsedUrlQuery = {} query: ParsedUrlQuery = {}
): Promise<string | null> { ): Promise<string | null> {
const response = await this.renderErrorToResponse( return this.getStaticHTML((ctx) => this.renderErrorToResponse(ctx, err), {
err,
req, req,
res, res,
pathname, pathname,
query query,
) })
return response ? response.body : null
} }
protected async getFallbackErrorComponents(): Promise<LoadComponentsReturnType | null> { protected async getFallbackErrorComponents(): Promise<LoadComponentsReturnType | null> {
...@@ -2139,6 +2172,7 @@ export default class Server { ...@@ -2139,6 +2172,7 @@ export default class Server {
query.__nextDefaultLocale = query.__nextDefaultLocale =
query.__nextDefaultLocale || i18n.defaultLocale query.__nextDefaultLocale || i18n.defaultLocale
} }
res.statusCode = 404 res.statusCode = 404
return this.renderError(null, req, res, pathname!, query, setHeaders) return this.renderError(null, req, res, pathname!, query, setHeaders)
} }
......
...@@ -188,6 +188,7 @@ export type RenderOptsPartial = { ...@@ -188,6 +188,7 @@ export type RenderOptsPartial = {
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocales domainLocales?: DomainLocales
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
requireStaticHTML?: boolean
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
......
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