Unverified Commit 5871b0d6 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Pages Error Route Module Rendering (#51374)

Continuing on changes to move the rendering logic into the bundles.

- Unifies edge render functions: `appRenderToHTML` and `pagesRenderToHTML` becomes `renderToHTML`
- When an error occurs, the error module's match is used so the module's internal render can be used (easing transition away from using the server's render method)
- Improved test resiliance
parent 5127c33f
...@@ -116,17 +116,16 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -116,17 +116,16 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
${ ${
isAppDir isAppDir
? ` ? `
import { renderToHTMLOrFlight as appRenderToHTML } from 'next/dist/esm/server/app-render/app-render' import { renderToHTMLOrFlight as renderToHTML } from 'next/dist/esm/server/app-render/app-render'
import * as pageMod from ${JSON.stringify(pageModPath)} import * as pageMod from ${JSON.stringify(pageModPath)}
const Document = null const Document = null
const pagesRenderToHTML = null
const appMod = null const appMod = null
const errorMod = null const errorMod = null
const error500Mod = null const error500Mod = null
` `
: ` : `
import Document from ${stringifiedDocumentPath} import Document from ${stringifiedDocumentPath}
import { renderToHTML as pagesRenderToHTML } from 'next/dist/esm/server/render' import { renderToHTML } from 'next/dist/esm/server/render'
import * as pageMod from ${stringifiedPagePath} import * as pageMod from ${stringifiedPagePath}
import * as appMod from ${stringifiedAppPath} import * as appMod from ${stringifiedAppPath}
import * as errorMod from ${stringifiedErrorPath} import * as errorMod from ${stringifiedErrorPath}
...@@ -135,7 +134,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -135,7 +134,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
? `import * as error500Mod from ${stringified500Path}` ? `import * as error500Mod from ${stringified500Path}`
: `const error500Mod = null` : `const error500Mod = null`
} }
const appRenderToHTML = null
` `
} }
...@@ -171,8 +169,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -171,8 +169,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
buildManifest, buildManifest,
isAppPath: ${!!isAppDir}, isAppPath: ${!!isAppDir},
prerenderManifest, prerenderManifest,
appRenderToHTML, renderToHTML,
pagesRenderToHTML,
reactLoadableManifest, reactLoadableManifest,
clientReferenceManifest: ${isServerComponent} ? rscManifest : null, clientReferenceManifest: ${isServerComponent} ? rscManifest : null,
serverActionsManifest: ${isServerComponent} ? rscServerManifest : null, serverActionsManifest: ${isServerComponent} ? rscServerManifest : null,
......
...@@ -27,8 +27,7 @@ export function getRender({ ...@@ -27,8 +27,7 @@ export function getRender({
buildManifest, buildManifest,
prerenderManifest, prerenderManifest,
reactLoadableManifest, reactLoadableManifest,
appRenderToHTML, renderToHTML,
pagesRenderToHTML,
clientReferenceManifest, clientReferenceManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
serverActionsManifest, serverActionsManifest,
...@@ -44,8 +43,7 @@ export function getRender({ ...@@ -44,8 +43,7 @@ export function getRender({
pageMod: any pageMod: any
errorMod: any errorMod: any
error500Mod: any error500Mod: any
appRenderToHTML: any renderToHTML: any
pagesRenderToHTML: any
Document: DocumentType Document: DocumentType
buildManifest: BuildManifest buildManifest: BuildManifest
prerenderManifest: PrerenderManifest prerenderManifest: PrerenderManifest
...@@ -88,8 +86,7 @@ export function getRender({ ...@@ -88,8 +86,7 @@ export function getRender({
clientReferenceManifest, clientReferenceManifest,
serverActionsManifest, serverActionsManifest,
}, },
appRenderToHTML, renderToHTML,
pagesRenderToHTML,
incrementalCacheHandler, incrementalCacheHandler,
loadComponent: async (pathname) => { loadComponent: async (pathname) => {
if (pathname === page) { if (pathname === page) {
...@@ -137,12 +134,15 @@ export function getRender({ ...@@ -137,12 +134,15 @@ export function getRender({
}, },
}, },
}) })
const requestHandler = server.getRequestHandler()
const handler = server.getRequestHandler()
return async function render(request: Request) { return async function render(request: Request) {
const extendedReq = new WebNextRequest(request) const extendedReq = new WebNextRequest(request)
const extendedRes = new WebNextResponse() const extendedRes = new WebNextResponse()
requestHandler(extendedReq, extendedRes)
handler(extendedReq, extendedRes)
return await extendedRes.toResponse() return await extendedRes.toResponse()
} }
} }
...@@ -61,7 +61,11 @@ import * as Log from '../build/output/log' ...@@ -61,7 +61,11 @@ import * as Log from '../build/output/log'
import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters' import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
import { getUtils } from './server-utils' import { getUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import { addRequestMeta, getRequestMeta } from './request-meta' import {
addRequestMeta,
getRequestMeta,
removeRequestMeta,
} from './request-meta'
import { ImageConfigComplete } from '../shared/lib/image-config' import { ImageConfigComplete } from '../shared/lib/image-config'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
...@@ -1670,11 +1674,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1670,11 +1674,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// served by the server. // served by the server.
let result: RenderResult let result: RenderResult
// We want to use the match when we're not trying to render an error page. // Get the match for the page if it exists.
const match = const match = getRequestMeta(req, '_nextMatch')
pathname !== '/_error' && !is404Page && !is500Page
? getRequestMeta(req, '_nextMatch')
: undefined
if ( if (
match && match &&
...@@ -1716,12 +1717,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1716,12 +1717,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (!headers['content-type'] && blob.type) { if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type headers['content-type'] = blob.type
} }
let revalidate: number | false | undefined =
context.staticGenerationContext.store?.revalidate
if (typeof revalidate == 'undefined') { const revalidate =
revalidate = false context.staticGenerationContext.store?.revalidate ?? false
}
// Create the cache entry for the response. // Create the cache entry for the response.
const cacheEntry: ResponseCacheEntry = { const cacheEntry: ResponseCacheEntry = {
...@@ -2540,6 +2538,17 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2540,6 +2538,17 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) )
} }
// If the page has a route module, use it for the new match. If it doesn't
// have a route module, remove the match.
if (result.components.ComponentMod.routeModule) {
addRequestMeta(ctx.req, '_nextMatch', {
definition: result.components.ComponentMod.routeModule.definition,
params: undefined,
})
} else {
removeRequestMeta(ctx.req, '_nextMatch')
}
try { try {
return await this.renderToResponseWithComponents( return await this.renderToResponseWithComponents(
{ {
......
...@@ -42,6 +42,14 @@ export interface RequestMeta { ...@@ -42,6 +42,14 @@ export interface RequestMeta {
_nextMinimalMode?: boolean _nextMinimalMode?: boolean
} }
/**
* Gets the request metadata. If no key is provided, the entire metadata object
* is returned.
*
* @param req the request to get the metadata from
* @param key the key to get from the metadata (optional)
* @returns the value for the key or the entire metadata object
*/
export function getRequestMeta( export function getRequestMeta(
req: NextIncomingMessage, req: NextIncomingMessage,
key?: undefined key?: undefined
...@@ -58,11 +66,26 @@ export function getRequestMeta<K extends keyof RequestMeta>( ...@@ -58,11 +66,26 @@ export function getRequestMeta<K extends keyof RequestMeta>(
return typeof key === 'string' ? meta[key] : meta return typeof key === 'string' ? meta[key] : meta
} }
/**
* Sets the request metadata.
*
* @param req the request to set the metadata on
* @param meta the metadata to set
* @returns the mutated request metadata
*/
export function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta) { export function setRequestMeta(req: NextIncomingMessage, meta: RequestMeta) {
req[NEXT_REQUEST_META] = meta req[NEXT_REQUEST_META] = meta
return getRequestMeta(req) return meta
} }
/**
* Adds a value to the request metadata.
*
* @param request the request to mutate
* @param key the key to set
* @param value the value to set
* @returns the mutated request metadata
*/
export function addRequestMeta<K extends keyof RequestMeta>( export function addRequestMeta<K extends keyof RequestMeta>(
request: NextIncomingMessage, request: NextIncomingMessage,
key: K, key: K,
...@@ -73,6 +96,22 @@ export function addRequestMeta<K extends keyof RequestMeta>( ...@@ -73,6 +96,22 @@ export function addRequestMeta<K extends keyof RequestMeta>(
return setRequestMeta(request, meta) return setRequestMeta(request, meta)
} }
/**
* Removes a key from the request metadata.
*
* @param request the request to mutate
* @param key the key to remove
* @returns the mutated request metadata
*/
export function removeRequestMeta<K extends keyof RequestMeta>(
request: NextIncomingMessage,
key: K
) {
const meta = getRequestMeta(request)
delete meta[key]
return setRequestMeta(request, meta)
}
type NextQueryMetadata = { type NextQueryMetadata = {
__nextNotFoundSrcPage?: string __nextNotFoundSrcPage?: string
__nextDefaultLocale?: string __nextDefaultLocale?: string
......
...@@ -35,8 +35,9 @@ interface WebServerOptions extends Options { ...@@ -35,8 +35,9 @@ interface WebServerOptions extends Options {
) => Promise<LoadComponentsReturnType | null> ) => Promise<LoadComponentsReturnType | null>
extendRenderOpts: Partial<BaseServer['renderOpts']> & extendRenderOpts: Partial<BaseServer['renderOpts']> &
Pick<BaseServer['renderOpts'], 'buildId'> Pick<BaseServer['renderOpts'], 'buildId'>
pagesRenderToHTML?: typeof import('./render').renderToHTML renderToHTML:
appRenderToHTML?: typeof import('./app-render/app-render').renderToHTMLOrFlight | typeof import('./render').renderToHTML
| typeof import('./app-render/app-render').renderToHTMLOrFlight
incrementalCacheHandler?: any incrementalCacheHandler?: any
prerenderManifest: PrerenderManifest | undefined prerenderManifest: PrerenderManifest | undefined
} }
...@@ -362,32 +363,27 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -362,32 +363,27 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
return false return false
} }
protected async renderHTML( protected renderHTML(
req: WebNextRequest, req: WebNextRequest,
res: WebNextResponse, res: WebNextResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: RenderOpts
): Promise<RenderResult> { ): Promise<RenderResult> {
const { pagesRenderToHTML, appRenderToHTML } = const { renderToHTML } = this.serverOptions.webServerConfig
this.serverOptions.webServerConfig
const curRenderToHTML = pagesRenderToHTML || appRenderToHTML return renderToHTML(
req as any,
if (curRenderToHTML) { res as any,
return await curRenderToHTML( pathname,
req as any, query,
res as any, Object.assign(renderOpts, {
pathname, disableOptimizedLoading: true,
query, runtime: 'experimental-edge',
Object.assign(renderOpts, { })
disableOptimizedLoading: true, )
runtime: 'experimental-edge',
})
)
} else {
throw new Error(`Invariant: curRenderToHTML is missing`)
}
} }
protected async sendRenderResult( protected async sendRenderResult(
_req: WebNextRequest, _req: WebNextRequest,
res: WebNextResponse, res: WebNextResponse,
......
...@@ -21,56 +21,68 @@ createNextDescribe( ...@@ -21,56 +21,68 @@ createNextDescribe(
const browser = await next.browser('/dashboard') const browser = await next.browser('/dashboard')
// Should body text in red // Should body text in red
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('.p')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('.p')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
// Should inject global css for .green selectors // Should inject global css for .green selectors
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('.green')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('.green')).color`
).toBe('rgb(0, 128, 0)') ),
'rgb(0, 128, 0)'
)
}) })
it('should support css modules inside server layouts', async () => { it('should support css modules inside server layouts', async () => {
const browser = await next.browser('/css/css-nested') const browser = await next.browser('/css/css-nested')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('#server-cssm')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('#server-cssm')).color`
).toBe('rgb(0, 128, 0)') ),
'rgb(0, 128, 0)'
)
}) })
it('should support external css imports', async () => { it('should support external css imports', async () => {
const browser = await next.browser('/css/css-external') const browser = await next.browser('/css/css-external')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('main')).paddingTop` await browser.eval(
) `window.getComputedStyle(document.querySelector('main')).paddingTop`
).toBe('80px') ),
'80px'
)
}) })
}) })
describe('server pages', () => { describe('server pages', () => {
it('should support global css inside server pages', async () => { it('should support global css inside server pages', async () => {
const browser = await next.browser('/css/css-page') const browser = await next.browser('/css/css-page')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should support css modules inside server pages', async () => { it('should support css modules inside server pages', async () => {
const browser = await next.browser('/css/css-page') const browser = await next.browser('/css/css-page')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('#cssm')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('#cssm')).color`
).toBe('rgb(0, 0, 255)') ),
'rgb(0, 0, 255)'
)
}) })
it('should not contain pages css in app dir page', async () => { it('should not contain pages css in app dir page', async () => {
...@@ -84,22 +96,26 @@ createNextDescribe( ...@@ -84,22 +96,26 @@ createNextDescribe(
const browser = await next.browser('/client-nested') const browser = await next.browser('/client-nested')
// Should render h1 in red // Should render h1 in red
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should support global css inside client layouts', async () => { it('should support global css inside client layouts', async () => {
const browser = await next.browser('/client-nested') const browser = await next.browser('/client-nested')
// Should render button in red // Should render button in red
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('button')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('button')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
}) })
...@@ -108,22 +124,26 @@ createNextDescribe( ...@@ -108,22 +124,26 @@ createNextDescribe(
const browser = await next.browser('/client-component-route') const browser = await next.browser('/client-component-route')
// Should render p in red // Should render p in red
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('p')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('p')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should support global css inside client pages', async () => { it('should support global css inside client pages', async () => {
const browser = await next.browser('/client-component-route') const browser = await next.browser('/client-component-route')
// Should render `b` in blue // Should render `b` in blue
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('b')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('b')).color`
).toBe('rgb(0, 0, 255)') ),
'rgb(0, 0, 255)'
)
}) })
}) })
...@@ -131,21 +151,25 @@ createNextDescribe( ...@@ -131,21 +151,25 @@ createNextDescribe(
it('should support css modules inside client page', async () => { it('should support css modules inside client page', async () => {
const browser = await next.browser('/css/css-client') const browser = await next.browser('/css/css-client')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('#css-modules')).fontSize` await browser.eval(
) `window.getComputedStyle(document.querySelector('#css-modules')).fontSize`
).toBe('100px') ),
'100px'
)
}) })
it('should support css modules inside client components', async () => { it('should support css modules inside client components', async () => {
const browser = await next.browser('/css/css-client/inner') const browser = await next.browser('/css/css-client/inner')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('#client-component')).fontSize` await browser.eval(
) `window.getComputedStyle(document.querySelector('#client-component')).fontSize`
).toBe('100px') ),
'100px'
)
}) })
}) })
...@@ -160,61 +184,75 @@ createNextDescribe( ...@@ -160,61 +184,75 @@ createNextDescribe(
it('should include css imported in client template.js', async () => { it('should include css imported in client template.js', async () => {
const browser = await next.browser('/template/clientcomponent') const browser = await next.browser('/template/clientcomponent')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('button')).fontSize` await browser.eval(
) `window.getComputedStyle(document.querySelector('button')).fontSize`
).toBe('100px') ),
'100px'
)
}) })
it('should include css imported in server template.js', async () => { it('should include css imported in server template.js', async () => {
const browser = await next.browser('/template/servercomponent') const browser = await next.browser('/template/servercomponent')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should include css imported in client not-found.js', async () => { it('should include css imported in client not-found.js', async () => {
const browser = await next.browser('/not-found/clientcomponent') const browser = await next.browser('/not-found/clientcomponent')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should include css imported in server not-found.js', async () => { it('should include css imported in server not-found.js', async () => {
const browser = await next.browser('/not-found/servercomponent') const browser = await next.browser('/not-found/servercomponent')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
it('should include root layout css for root not-found.js', async () => { it('should include root layout css for root not-found.js', async () => {
const browser = await next.browser('/this-path-does-not-exist') const browser = await next.browser('/this-path-does-not-exist')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(210, 105, 30)') ),
'rgb(210, 105, 30)'
)
}) })
it('should include css imported in root not-found.js', async () => { it('should include css imported in root not-found.js', async () => {
const browser = await next.browser('/random-non-existing-path') const browser = await next.browser('/random-non-existing-path')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(210, 105, 30)') ),
expect( 'rgb(210, 105, 30)'
await browser.eval( )
`window.getComputedStyle(document.querySelector('h1')).backgroundColor` await check(
) async () =>
).toBe('rgb(0, 0, 0)') await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).backgroundColor`
),
'rgb(0, 0, 0)'
)
}) })
it('should include css imported in error.js', async () => { it('should include css imported in error.js', async () => {
...@@ -224,22 +262,26 @@ createNextDescribe( ...@@ -224,22 +262,26 @@ createNextDescribe(
// Wait for error page to render and CSS to be loaded // Wait for error page to render and CSS to be loaded
await new Promise((resolve) => setTimeout(resolve, 2000)) await new Promise((resolve) => setTimeout(resolve, 2000))
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('button')).fontSize` await browser.eval(
) `window.getComputedStyle(document.querySelector('button')).fontSize`
).toBe('50px') ),
'50px'
)
}) })
}) })
describe('page extensions', () => { describe('page extensions', () => {
it('should include css imported in MDX pages', async () => { it('should include css imported in MDX pages', async () => {
const browser = await next.browser('/mdx') const browser = await next.browser('/mdx')
expect( await check(
await browser.eval( async () =>
`window.getComputedStyle(document.querySelector('h1')).color` await browser.eval(
) `window.getComputedStyle(document.querySelector('h1')).color`
).toBe('rgb(255, 0, 0)') ),
'rgb(255, 0, 0)'
)
}) })
}) })
......
...@@ -535,8 +535,15 @@ export async function startCleanStaticServer(dir) { ...@@ -535,8 +535,15 @@ export async function startCleanStaticServer(dir) {
return server return server
} }
// check for content in 1 second intervals timing out after /**
// 30 seconds * Check for content in 1 second intervals timing out after 30 seconds.
*
* @param {() => Promise<unknown> | unknown} contentFn
* @param {RegExp | string | number} regex
* @param {boolean} hardError
* @param {number} maxRetries
* @returns {Promise<boolean>}
*/
export async function check( export async function check(
contentFn, contentFn,
regex, regex,
......
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