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