Unverified Commit efe00e94 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Enable Pages Route Module Rendering for Edge (#51894)

This adapts the new route module rendering to support edge as well.

- Added a new `routeModule` export to the Edge SSR Loader
- Updated some tests to validate page state

Fixes NEXT-1327
parent 636c7761
......@@ -1440,7 +1440,7 @@ export async function isPageStatic({
// This is present on the new route modules.
const userland: AppRouteUserlandModule | undefined =
componentsResult.ComponentMod.routeModule?.userland
componentsResult.routeModule?.userland
const staticGenerationAsyncStorage: StaticGenerationAsyncStorage =
componentsResult.ComponentMod.staticGenerationAsyncStorage
......
import type webpack from 'webpack'
import type { SizeLimit } from '../../../../../types'
import type { PagesRouteModuleOptions } from '../../../../server/future/route-modules/pages/module'
import type { MiddlewareConfig } from '../../../analysis/get-page-static-info'
import { getModuleBuildInfo } from '../get-module-build-info'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { stringifyRequest } from '../../stringify-request'
import { MiddlewareConfig } from '../../../analysis/get-page-static-info'
import { RouteKind } from '../../../../server/future/route-kind'
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'
export type EdgeSSRLoaderQuery = {
absolute500Path: string
......@@ -38,6 +41,21 @@ function swapDistFolderWithEsmDistFolder(path: string) {
return path.replace('next/dist/pages', 'next/dist/esm/pages')
}
function getRouteModuleOptions(page: string) {
const options: Omit<PagesRouteModuleOptions, 'userland' | 'components'> = {
definition: {
kind: RouteKind.PAGES,
page: normalizePagePath(page),
pathname: page,
// The following aren't used in production.
bundlePath: '',
filename: '',
},
}
return options
}
const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
function edgeSSRLoader(this) {
const {
......@@ -129,21 +147,63 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
`
: `
import Document from ${stringifiedDocumentPath}
import { renderToHTML } from 'next/dist/esm/server/render'
import * as pageMod from ${stringifiedPagePath}
import * as appMod from ${stringifiedAppPath}
import * as errorMod from ${stringifiedErrorPath}
import * as userlandPage from ${stringifiedPagePath}
import * as userlandErrorPage from ${stringifiedErrorPath}
${
stringified500Path
? `import * as error500Mod from ${stringified500Path}`
: `const error500Mod = null`
? `import * as userland500Page from ${stringified500Path}`
: ''
}
`
const renderToHTML = undefined
import RouteModule from "next/dist/esm/server/future/route-modules/pages/module"
const pageMod = {
...userlandPage,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions(page))},
components: {
App: appMod.default,
Document,
},
userland: userlandPage,
}),
}
const errorMod = {
...userlandErrorPage,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions('/_error'))},
components: {
App: appMod.default,
Document,
},
userland: userlandErrorPage,
}),
}
const error500Mod = ${
stringified500Path
? `{
...userland500Page,
routeModule: new RouteModule({
...${JSON.stringify(getRouteModuleOptions('/500'))},
components: {
App: appMod.default,
Document,
},
userland: userland500Page,
}),
}`
: 'null'
}`
}
${
incrementalCacheHandlerPath
? `import incrementalCacheHandler from "${incrementalCacheHandlerPath}"`
? `import incrementalCacheHandler from ${JSON.stringify(
incrementalCacheHandlerPath
)}`
: 'const incrementalCacheHandler = null'
}
......
......@@ -45,7 +45,7 @@ export function getRender({
pageMod: any
errorMod: any
error500Mod: any
renderToHTML: any
renderToHTML?: any
Document: DocumentType
buildManifest: BuildManifest
prerenderManifest: PrerenderManifest
......@@ -104,6 +104,7 @@ export function getRender({
ComponentMod: pageMod,
isAppPath: !!pageMod.__next_app__,
pathname,
routeModule: pageMod.routeModule,
}
}
......@@ -118,6 +119,7 @@ export function getRender({
getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod,
pathname,
routeModule: error500Mod.routeModule,
}
}
......@@ -131,6 +133,7 @@ export function getRender({
getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod,
pathname,
routeModule: errorMod.routeModule,
}
}
......
......@@ -31,6 +31,7 @@ import type { PagesRouteModule } from './future/route-modules/pages/module'
import type { NodeNextRequest, NodeNextResponse } from './base-http/node'
import type { AppRouteRouteMatch } from './future/route-matches/app-route-route-match'
import type { RouteDefinition } from './future/route-definitions/route-definition'
import type { WebNextRequest, WebNextResponse } from './base-http/web'
import { format as formatUrl, parse as parseUrl } from 'url'
import { getRedirectStatus } from '../lib/redirect-status'
......@@ -1687,9 +1688,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
getRequestMeta(req, '_nextMatch') ??
// If the match can't be found, rely on the loaded route module. This
// should only be required during development when we add FS routes.
(this.renderOpts.dev && components.ComponentMod?.routeModule
((this.renderOpts.dev || process.env.NEXT_RUNTIME === 'edge') &&
components.routeModule
? {
definition: components.ComponentMod.routeModule.definition,
definition: components.routeModule.definition,
params: opts.params
? parsedUrlQueryToParams(opts.params)
: undefined,
......@@ -1776,10 +1778,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
else if (
match &&
isRouteMatch(match, RouteKind.PAGES) &&
process.env.NEXT_RUNTIME !== 'edge' &&
components.ComponentMod.routeModule
components.routeModule
) {
const module: PagesRouteModule = components.ComponentMod.routeModule
const module = components.routeModule as PagesRouteModule
// Due to the way we pass data by mutating `renderOpts`, we can't extend
// the object here but only updating its `clientReferenceManifest`
......@@ -1787,13 +1788,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.nextFontManifest = this.nextFontManifest
// Call the built-in render method on the module. We cast these to
// NodeNextRequest and NodeNextResponse because we know that we're
// in the node runtime because we check that we're not in edge mode
// above.
// Call the built-in render method on the module.
result = await module.render(
(req as NodeNextRequest).originalRequest,
(res as NodeNextResponse).originalResponse,
(req as NodeNextRequest).originalRequest ?? (req as WebNextRequest),
(res as NodeNextResponse).originalResponse ??
(res as WebNextResponse),
{ page: pathname, params: match.params, query, renderOpts }
)
} else {
......@@ -2560,9 +2559,9 @@ 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) {
if (result.components.routeModule) {
addRequestMeta(ctx.req, '_nextMatch', {
definition: result.components.ComponentMod.routeModule.definition,
definition: result.components.routeModule.definition,
params: undefined,
})
} else {
......@@ -2600,7 +2599,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// There was an error, so use it's definition from the route module
// to add the match to the request.
addRequestMeta(ctx.req, '_nextMatch', {
definition: fallbackComponents.ComponentMod.routeModule.definition,
definition: fallbackComponents.routeModule!.definition,
params: undefined,
})
......
......@@ -77,7 +77,7 @@ export async function loadStaticPaths({
if (isAppPath) {
const userland: AppRouteUserlandModule | undefined =
components.ComponentMod.routeModule?.userland
components.routeModule?.userland
const generateParams: GenerateParams = userland
? [
{
......
......@@ -10,6 +10,8 @@ import type {
GetServerSideProps,
GetStaticProps,
} from 'next/types'
import type { RouteModule } from './future/route-modules/route-module'
import {
BUILD_MANIFEST,
REACT_LOADABLE_MANIFEST,
......@@ -44,6 +46,7 @@ export type LoadComponentsReturnType = {
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
ComponentMod: any
routeModule?: RouteModule
isAppPath?: boolean
pathname: string
}
......@@ -70,6 +73,7 @@ async function loadDefaultErrorComponentsImpl(
reactLoadableManifest: {},
ComponentMod,
pathname: '/_error',
routeModule: ComponentMod.routeModule,
}
}
......@@ -152,6 +156,7 @@ async function loadComponentsImpl({
serverActionsManifest,
isAppPath,
pathname,
routeModule: ComponentMod.routeModule,
}
}
......
......@@ -36,8 +36,8 @@ interface WebServerOptions extends Options {
extendRenderOpts: Partial<BaseServer['renderOpts']> &
Pick<BaseServer['renderOpts'], 'buildId'>
renderToHTML:
| typeof import('./render').renderToHTML
| typeof import('./app-render/app-render').renderToHTMLOrFlight
| undefined
incrementalCacheHandler?: any
prerenderManifest: PrerenderManifest | undefined
}
......@@ -371,6 +371,11 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
renderOpts: RenderOpts
): Promise<RenderResult> {
const { renderToHTML } = this.serverOptions.webServerConfig
if (!renderToHTML) {
throw new Error(
'Invariant: routeModule should be configured when rendering pages'
)
}
return renderToHTML(
req as any,
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, normalizeRegEx, renderViaHTTP } from 'next-test-utils'
import { fetchViaHTTP, normalizeRegEx } from 'next-test-utils'
import cheerio from 'cheerio'
import { join } from 'path'
import escapeStringRegexp from 'escape-string-regexp'
......@@ -63,7 +63,9 @@ describe('edge-render-getserversideprops', () => {
})
it('should have correct query/params on index', async () => {
const html = await renderViaHTTP(next.url, '/')
const res = await fetchViaHTTP(next.url, '/')
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/index')
const props = JSON.parse($('#props').text())
......@@ -73,7 +75,9 @@ describe('edge-render-getserversideprops', () => {
})
it('should have correct query/params on /[id]', async () => {
const html = await renderViaHTTP(next.url, '/123', { hello: 'world' })
const res = await fetchViaHTTP(next.url, '/123', { hello: 'world' })
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/[id]')
const props = JSON.parse($('#props').text())
......@@ -83,9 +87,11 @@ describe('edge-render-getserversideprops', () => {
})
it('should have correct query/params on rewrite', async () => {
const html = await renderViaHTTP(next.url, '/rewrite-me', {
const res = await fetchViaHTTP(next.url, '/rewrite-me', {
hello: 'world',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/index')
const props = JSON.parse($('#props').text())
......@@ -95,9 +101,11 @@ describe('edge-render-getserversideprops', () => {
})
it('should have correct query/params on dynamic rewrite', async () => {
const html = await renderViaHTTP(next.url, '/rewrite-me-dynamic', {
const res = await fetchViaHTTP(next.url, '/rewrite-me-dynamic', {
hello: 'world',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/[id]')
const props = JSON.parse($('#props').text())
......
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