Unverified Commit 99d4d6c5 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Implement web server as the request handler for edge SSR (#33635)

(#31506 for context)

This PR implements the minimum viable web server on top of the Next.js base server, and integrates it into our middleware (edge) SSR runtime to handle all the requests.

This also addresses problems like missing dynamic routes support in our current handler.

Note that this is the initial implementation with the assumption that the web server is running under minimal mode. Also later we can refactor the `__server_context` environment to properly passing the context via the constructor or methods.
parent f0e31ee8
...@@ -157,7 +157,6 @@ export function createEntrypoints( ...@@ -157,7 +157,6 @@ export function createEntrypoints(
const isFlight = isFlightPage(config, absolutePagePath) const isFlight = isFlightPage(config, absolutePagePath)
const webServerRuntime = !!config.experimental.concurrentFeatures const webServerRuntime = !!config.experimental.concurrentFeatures
const hasServerComponents = !!config.experimental.serverComponents
if (page.match(MIDDLEWARE_ROUTE)) { if (page.match(MIDDLEWARE_ROUTE)) {
const loaderOpts: MiddlewareLoaderOptions = { const loaderOpts: MiddlewareLoaderOptions = {
...@@ -176,11 +175,12 @@ export function createEntrypoints( ...@@ -176,11 +175,12 @@ export function createEntrypoints(
serverWeb[serverBundlePath] = finalizeEntrypoint({ serverWeb[serverBundlePath] = finalizeEntrypoint({
name: '[name].js', name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({ value: `next-middleware-ssr-loader?${stringify({
dev: false,
page, page,
stringifiedConfig: JSON.stringify(config),
absolute500Path: pages['/500'] || '', absolute500Path: pages['/500'] || '',
absolutePagePath, absolutePagePath,
isServerComponent: isFlight, isServerComponent: isFlight,
serverComponents: hasServerComponents,
...defaultServerlessOptions, ...defaultServerlessOptions,
} as any)}!`, } as any)}!`,
isServer: false, isServer: false,
......
...@@ -2,13 +2,16 @@ import { stringifyRequest } from '../../stringify-request' ...@@ -2,13 +2,16 @@ import { stringifyRequest } from '../../stringify-request'
export default async function middlewareSSRLoader(this: any) { export default async function middlewareSSRLoader(this: any) {
const { const {
dev,
page,
buildId,
absolutePagePath, absolutePagePath,
absoluteAppPath, absoluteAppPath,
absoluteDocumentPath, absoluteDocumentPath,
absolute500Path, absolute500Path,
absoluteErrorPath, absoluteErrorPath,
isServerComponent, isServerComponent,
...restRenderOpts stringifiedConfig,
} = this.getOptions() } = this.getOptions()
const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath) const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath)
...@@ -42,16 +45,37 @@ export default async function middlewareSSRLoader(this: any) { ...@@ -42,16 +45,37 @@ export default async function middlewareSSRLoader(this: any) {
throw new Error('Your page must export a \`default\` component') throw new Error('Your page must export a \`default\` component')
} }
const render = getRender({ // Set server context
App, self.__current_route = ${JSON.stringify(page)}
Document, self.__server_context = {
pageMod, Component: pageMod.default,
errorMod, pageConfig: pageMod.config || {},
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
rscManifest, Document,
App,
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
ComponentMod: undefined,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
// components
errorMod,
// renderOpts
buildId: ${JSON.stringify(buildId)},
dev: ${dev},
env: process.env,
supportsDynamicHTML: true,
concurrentFeatures: true,
disableOptimizedLoading: true,
}
const render = getRender({
Document,
isServerComponent: ${isServerComponent}, isServerComponent: ${isServerComponent},
restRenderOpts: ${JSON.stringify(restRenderOpts)} config: ${stringifiedConfig},
}) })
export default function rscMiddleware(opts) { export default function rscMiddleware(opts) {
......
import type { NextConfig } from '../../../../server/config-shared'
import { NextRequest } from '../../../../server/web/spec-extension/request' import { NextRequest } from '../../../../server/web/spec-extension/request'
import { renderToHTML } from '../../../../server/web/render'
import RenderResult from '../../../../server/render-result'
import { toNodeHeaders } from '../../../../server/web/utils' import { toNodeHeaders } from '../../../../server/web/utils'
import WebServer from '../../../../server/web-server'
import { WebNextRequest, WebNextResponse } from '../../../../server/base-http'
const createHeaders = (args?: any) => ({ const createHeaders = (args?: any) => ({
...args, ...args,
'x-middleware-ssr': '1', 'x-middleware-ssr': '1',
...@@ -18,26 +21,22 @@ function sendError(req: any, error: Error) { ...@@ -18,26 +21,22 @@ function sendError(req: any, error: Error) {
} }
export function getRender({ export function getRender({
App,
Document, Document,
pageMod,
errorMod,
rscManifest,
buildManifest,
reactLoadableManifest,
isServerComponent, isServerComponent,
restRenderOpts, config,
}: { }: {
App: any
Document: any Document: any
pageMod: any
errorMod: any
rscManifest: object
buildManifest: any
reactLoadableManifest: any
isServerComponent: boolean isServerComponent: boolean
restRenderOpts: any config: NextConfig
}) { }) {
// Polyfilled for `path-browserify`.
process.cwd = () => ''
const server = new WebServer({
conf: config,
minimalMode: true,
})
const requestHandler = server.getRequestHandler()
return async function render(request: NextRequest) { return async function render(request: NextRequest) {
const { nextUrl: url, cookies, headers } = request const { nextUrl: url, cookies, headers } = request
const { pathname, searchParams } = url const { pathname, searchParams } = url
...@@ -56,6 +55,7 @@ export function getRender({ ...@@ -56,6 +55,7 @@ export function getRender({
}) })
} }
// @TODO: We should move this into server/render.
if (Document.getInitialProps) { if (Document.getInitialProps) {
const err = new Error( const err = new Error(
'`getInitialProps` in Document component is not supported with `concurrentFeatures` enabled.' '`getInitialProps` in Document component is not supported with `concurrentFeatures` enabled.'
...@@ -72,92 +72,15 @@ export function getRender({ ...@@ -72,92 +72,15 @@ export function getRender({
? JSON.parse(query.__props__) ? JSON.parse(query.__props__)
: undefined : undefined
delete query.__flight__ // Extend the context.
delete query.__props__ Object.assign((self as any).__server_context, {
const renderOpts = {
...restRenderOpts,
// Locales are not supported yet.
// locales: i18n?.locales,
// locale: detectedLocale,
// defaultLocale,
// domainLocales: i18n?.domains,
dev: process.env.NODE_ENV !== 'production',
App,
Document,
buildManifest,
Component: pageMod.default,
pageConfig: pageMod.config || {},
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
reactLoadableManifest,
env: process.env,
supportsDynamicHTML: true,
concurrentFeatures: true,
// When streaming, opt-out the `defer` behavior for script tags.
disableOptimizedLoading: true,
renderServerComponentData, renderServerComponentData,
serverComponentProps, serverComponentProps,
serverComponentManifest: isServerComponent ? rscManifest : null,
ComponentMod: null,
}
const transformStream = new TransformStream()
const writer = transformStream.writable.getWriter()
const encoder = new TextEncoder()
let result: RenderResult | null
let renderError: any
try {
result = await renderToHTML(
req as any,
{} as any,
pathname,
query,
renderOpts
)
} catch (err: any) {
console.error(
'An error occurred while rendering the initial result:',
err
)
const errorRes = { statusCode: 500, err }
renderError = err
try {
req.url = '/_error'
result = await renderToHTML(
req as any,
errorRes as any,
'/_error',
query,
{
...renderOpts,
err,
Component: errorMod.default,
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
}
)
} catch (err2: any) {
return sendError(req, err2)
}
}
if (!result) {
return sendError(req, new Error('No result returned from render.'))
}
result.pipe({
write: (str: string) => writer.write(encoder.encode(str)),
end: () => writer.close(),
// Not implemented: cork/uncork/on/removeListener
} as any)
return new Response(transformStream.readable, {
headers: createHeaders(),
status: renderError ? 500 : 200,
}) })
const extendedReq = new WebNextRequest(request)
const extendedRes = new WebNextResponse()
requestHandler(extendedReq, extendedRes)
return await extendedRes.toResponse()
} }
} }
let chalk: typeof import('next/dist/compiled/chalk') let chalk: typeof import('next/dist/compiled/chalk')
if (typeof window === 'undefined') { if (!process.browser) {
chalk = require('next/dist/compiled/chalk') chalk = require('next/dist/compiled/chalk')
} else { } else {
chalk = require('./web/chalk').default chalk = require('./web/chalk').default
......
...@@ -4,8 +4,7 @@ ...@@ -4,8 +4,7 @@
// - chalk.red('error') // - chalk.red('error')
// - chalk.bold.cyan('message') // - chalk.bold.cyan('message')
// - chalk.hex('#fff').underline('hello') // - chalk.hex('#fff').underline('hello')
const log = console.log const chalk: any = new Proxy((s: string) => s, {
const chalk: any = new Proxy(log, {
get(_, prop: string) { get(_, prop: string) {
if ( if (
['hex', 'rgb', 'ansi256', 'bgHex', 'bgRgb', 'bgAnsi256'].includes(prop) ['hex', 'rgb', 'ansi256', 'bgHex', 'bgRgb', 'bgAnsi256'].includes(prop)
......
This diff is collapsed.
...@@ -525,22 +525,16 @@ export default class HotReloader { ...@@ -525,22 +525,16 @@ export default class HotReloader {
entrypoints[bundlePath] = finalizeEntrypoint({ entrypoints[bundlePath] = finalizeEntrypoint({
name: '[name].js', name: '[name].js',
value: `next-middleware-ssr-loader?${stringify({ value: `next-middleware-ssr-loader?${stringify({
dev: true,
page, page,
stringifiedConfig: JSON.stringify(this.config),
absoluteAppPath: this.pagesMapping['/_app'], absoluteAppPath: this.pagesMapping['/_app'],
absoluteDocumentPath: this.pagesMapping['/_document'], absoluteDocumentPath: this.pagesMapping['/_document'],
absoluteErrorPath: this.pagesMapping['/_error'], absoluteErrorPath: this.pagesMapping['/_error'],
absolute404Path: this.pagesMapping['/404'] || '', absolute404Path: this.pagesMapping['/404'] || '',
absolutePagePath, absolutePagePath,
isServerComponent, isServerComponent,
serverComponents: this.hasServerComponents,
buildId: this.buildId, buildId: this.buildId,
basePath: this.config.basePath,
assetPrefix: this.config.assetPrefix,
generateEtags: this.config.generateEtags,
poweredByHeader: this.config.poweredByHeader,
canonicalBase: this.config.amp.canonicalBase,
i18n: this.config.i18n,
previewProps: this.previewProps,
} as any)}!`, } as any)}!`,
isServer: false, isServer: false,
isServerWeb: true, isServerWeb: true,
......
...@@ -3,7 +3,6 @@ import type { CacheFs } from '../shared/lib/utils' ...@@ -3,7 +3,6 @@ import type { CacheFs } from '../shared/lib/utils'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import path from 'path' import path from 'path'
import { PrerenderManifest } from '../build' import { PrerenderManifest } from '../build'
import { PRERENDER_MANIFEST } from '../shared/lib/constants'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
function toRoute(pathname: string): string { function toRoute(pathname: string): string {
...@@ -52,6 +51,7 @@ export class IncrementalCache { ...@@ -52,6 +51,7 @@ export class IncrementalCache {
pagesDir, pagesDir,
flushToDisk, flushToDisk,
locales, locales,
getPrerenderManifest,
}: { }: {
fs: CacheFs fs: CacheFs
dev: boolean dev: boolean
...@@ -60,6 +60,7 @@ export class IncrementalCache { ...@@ -60,6 +60,7 @@ export class IncrementalCache {
pagesDir: string pagesDir: string
flushToDisk?: boolean flushToDisk?: boolean
locales?: string[] locales?: string[]
getPrerenderManifest: () => PrerenderManifest
}) { }) {
this.fs = fs this.fs = fs
this.incrementalOptions = { this.incrementalOptions = {
...@@ -70,21 +71,7 @@ export class IncrementalCache { ...@@ -70,21 +71,7 @@ export class IncrementalCache {
!dev && (typeof flushToDisk !== 'undefined' ? flushToDisk : true), !dev && (typeof flushToDisk !== 'undefined' ? flushToDisk : true),
} }
this.locales = locales this.locales = locales
this.prerenderManifest = getPrerenderManifest()
if (dev) {
this.prerenderManifest = {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: null as any, // `preview` is special case read in next-dev-server
}
} else {
const manifestJson = this.fs.readFileSync(
path.join(distDir, PRERENDER_MANIFEST)
)
this.prerenderManifest = JSON.parse(manifestJson)
}
if (process.env.__NEXT_TEST_MAX_ISR_CACHE) { if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {
// Allow cache size to be overridden for testing purposes // Allow cache size to be overridden for testing purposes
......
...@@ -6,6 +6,7 @@ import type RenderResult from './render-result' ...@@ -6,6 +6,7 @@ import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types' import type { FetchEventResult } from './web/types'
import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url' import type { ParsedNextUrl } from '../shared/lib/router/utils/parse-next-url'
import type { PrerenderManifest } from '../build' import type { PrerenderManifest } from '../build'
import type { Rewrite } from '../lib/load-custom-routes'
import { execOnce } from '../shared/lib/utils' import { execOnce } from '../shared/lib/utils'
import { import {
...@@ -72,6 +73,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' ...@@ -72,6 +73,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getMiddlewareRegex, getRouteMatcher } from '../shared/lib/router/utils' import { getMiddlewareRegex, getRouteMatcher } from '../shared/lib/router/utils'
import { MIDDLEWARE_ROUTE } from '../lib/constants' import { MIDDLEWARE_ROUTE } from '../lib/constants'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { getCustomRoute } from './server-route-utils'
export * from './base-server' export * from './base-server'
...@@ -91,7 +93,9 @@ export interface NodeRequestHandler { ...@@ -91,7 +93,9 @@ export interface NodeRequestHandler {
export default class NextNodeServer extends BaseServer { export default class NextNodeServer extends BaseServer {
constructor(options: Options) { constructor(options: Options) {
// Initialize super class
super(options) super(options)
/** /**
* This sets environment variable to be used at the time of SSR by head.tsx. * This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling * Using this from process.env allows targeting both serverless and SSR by calling
...@@ -197,6 +201,10 @@ export default class NextNodeServer extends BaseServer { ...@@ -197,6 +201,10 @@ export default class NextNodeServer extends BaseServer {
: [] : []
} }
protected setImmutableAssetCacheControl(res: BaseNextResponse): void {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
}
protected generateFsStaticRoutes(): Route[] { protected generateFsStaticRoutes(): Route[] {
return [ return [
{ {
...@@ -677,6 +685,24 @@ export default class NextNodeServer extends BaseServer { ...@@ -677,6 +685,24 @@ export default class NextNodeServer extends BaseServer {
) )
} }
protected async hasMiddleware(
pathname: string,
_isSSR?: boolean
): Promise<boolean> {
try {
return (
getMiddlewareInfo({
dev: this.renderOpts.dev,
distDir: this.distDir,
page: pathname,
serverless: this._isLikeServerless,
}).paths.length > 0
)
} catch (_) {}
return false
}
public async serveStatic( public async serveStatic(
req: BaseNextRequest | IncomingMessage, req: BaseNextRequest | IncomingMessage,
res: BaseNextResponse | ServerResponse, res: BaseNextResponse | ServerResponse,
...@@ -795,6 +821,79 @@ export default class NextNodeServer extends BaseServer { ...@@ -795,6 +821,79 @@ export default class NextNodeServer extends BaseServer {
return undefined return undefined
} }
protected generateRewrites({
restrictedRedirectPaths,
}: {
restrictedRedirectPaths: string[]
}) {
let beforeFiles: Route[] = []
let afterFiles: Route[] = []
let fallback: Route[] = []
if (!this.minimalMode) {
const buildRewrite = (rewrite: Rewrite, check = true) => {
const rewriteRoute = getCustomRoute({
type: 'rewrite',
rule: rewrite,
restrictedRedirectPaths,
})
return {
...rewriteRoute,
check,
type: rewriteRoute.type,
name: `Rewrite route ${rewriteRoute.source}`,
match: rewriteRoute.match,
fn: async (req, res, params, parsedUrl) => {
const { newUrl, parsedDestination } = prepareDestination({
appendParamsToQuery: true,
destination: rewriteRoute.destination,
params: params,
query: parsedUrl.query,
})
// external rewrite, proxy it
if (parsedDestination.protocol) {
return this.proxyRequest(
req as NodeNextRequest,
res as NodeNextResponse,
parsedDestination
)
}
addRequestMeta(req, '_nextRewroteUrl', newUrl)
addRequestMeta(req, '_nextDidRewrite', newUrl !== req.url)
return {
finished: false,
pathname: newUrl,
query: parsedDestination.query,
}
},
} as Route
}
if (Array.isArray(this.customRoutes.rewrites)) {
afterFiles = this.customRoutes.rewrites.map((r) => buildRewrite(r))
} else {
beforeFiles = this.customRoutes.rewrites.beforeFiles.map((r) =>
buildRewrite(r, false)
)
afterFiles = this.customRoutes.rewrites.afterFiles.map((r) =>
buildRewrite(r)
)
fallback = this.customRoutes.rewrites.fallback.map((r) =>
buildRewrite(r)
)
}
}
return {
beforeFiles,
afterFiles,
fallback,
}
}
protected generateCatchAllMiddlewareRoute(): Route | undefined { protected generateCatchAllMiddlewareRoute(): Route | undefined {
if (this.minimalMode) return undefined if (this.minimalMode) return undefined
......
import type {
Header,
Redirect,
Rewrite,
RouteType,
} from '../lib/load-custom-routes'
import type { Route } from './router'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring'
import { getRedirectStatus, modifyRouteRegex } from '../lib/load-custom-routes'
import pathMatch from '../shared/lib/router/utils/path-match'
import {
compileNonPath,
prepareDestination,
} from '../shared/lib/router/utils/prepare-destination'
import { getRequestMeta } from './request-meta'
import { stringify as stringifyQs } from 'querystring'
import { format as formatUrl } from 'url'
import { normalizeRepeatedSlashes } from '../shared/lib/utils'
const getCustomRouteMatcher = pathMatch(true)
export const getCustomRoute = ({
type,
rule,
restrictedRedirectPaths,
}: {
rule: Rewrite | Redirect | Header
type: RouteType
restrictedRedirectPaths: string[]
}) => {
const match = getCustomRouteMatcher(
rule.source,
!(rule as any).internal
? (regex: string) =>
modifyRouteRegex(
regex,
type === 'redirect' ? restrictedRedirectPaths : undefined
)
: undefined
)
return {
...rule,
type,
match,
name: type,
fn: async (_req, _res, _params, _parsedUrl) => ({ finished: false }),
} as Route & Rewrite & Header
}
export const createHeaderRoute = ({
rule,
restrictedRedirectPaths,
}: {
rule: Header
restrictedRedirectPaths: string[]
}) => {
const headerRoute = getCustomRoute({
type: 'header',
rule,
restrictedRedirectPaths,
})
return {
match: headerRoute.match,
has: headerRoute.has,
type: headerRoute.type,
name: `${headerRoute.type} ${headerRoute.source} header route`,
fn: async (_req, res, params, _parsedUrl) => {
const hasParams = Object.keys(params).length > 0
for (const header of (headerRoute as Header).headers) {
let { key, value } = header
if (hasParams) {
key = compileNonPath(key, params)
value = compileNonPath(value, params)
}
res.setHeader(key, value)
}
return { finished: false }
},
} as Route
}
export const createRedirectRoute = ({
rule,
restrictedRedirectPaths,
}: {
rule: Redirect
restrictedRedirectPaths: string[]
}) => {
const redirectRoute = getCustomRoute({
type: 'redirect',
rule,
restrictedRedirectPaths,
})
return {
internal: redirectRoute.internal,
type: redirectRoute.type,
match: redirectRoute.match,
has: redirectRoute.has,
statusCode: redirectRoute.statusCode,
name: `Redirect route ${redirectRoute.source}`,
fn: async (req, res, params, parsedUrl) => {
const { parsedDestination } = prepareDestination({
appendParamsToQuery: false,
destination: redirectRoute.destination,
params: params,
query: parsedUrl.query,
})
const { query } = parsedDestination
delete (parsedDestination as any).query
parsedDestination.search = stringifyQuery(req, query)
let updatedDestination = formatUrl(parsedDestination)
if (updatedDestination.startsWith('/')) {
updatedDestination = normalizeRepeatedSlashes(updatedDestination)
}
res
.redirect(
updatedDestination,
getRedirectStatus(redirectRoute as Redirect)
)
.body(updatedDestination)
.send()
return {
finished: true,
}
},
} as Route
}
// since initial query values are decoded by querystring.parse
// we need to re-encode them here but still allow passing through
// values from rewrites/redirects
export const stringifyQuery = (req: BaseNextRequest, query: ParsedUrlQuery) => {
const initialQueryValues = Object.values(
getRequestMeta(req, '__NEXT_INIT_QUERY') || {}
)
return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (initialQueryValues.some((val) => val === value)) {
return encodeURIComponent(value)
}
return value
},
})
}
import type { WebNextRequest, WebNextResponse } from './base-http'
import type { RenderOpts } from './render'
import type RenderResult from './render-result'
import type { NextParsedUrlQuery } from './request-meta'
import type { Params } from './router'
import type { PayloadOptions } from './send-payload'
import BaseServer from './base-server'
import { renderToHTML } from './render'
import { LoadComponentsReturnType } from './load-components'
export default class NextWebServer extends BaseServer {
protected generateRewrites() {
// @TODO: assuming minimal mode right now
return {
beforeFiles: [],
afterFiles: [],
fallback: [],
}
}
protected handleCompression() {
// @TODO
}
protected getRoutesManifest() {
return {
headers: [],
rewrites: {
fallback: [],
afterFiles: [],
beforeFiles: [],
},
redirects: [],
}
}
protected getPagePath() {
// @TODO
return ''
}
protected getPublicDir() {
// @TODO
return ''
}
protected getBuildId() {
return (globalThis as any).__server_context.buildId
}
protected loadEnvConfig() {
// @TODO
}
protected getHasStaticDir() {
return false
}
protected async hasMiddleware() {
return false
}
protected generateImageRoutes() {
return []
}
protected generateStaticRotes() {
return []
}
protected generateFsStaticRoutes() {
return []
}
protected generatePublicRoutes() {
return []
}
protected getMiddleware() {
return []
}
protected generateCatchAllMiddlewareRoute() {
return undefined
}
protected getFontManifest() {
return undefined
}
protected getMiddlewareManifest() {
return undefined
}
protected getPagesManifest() {
return {
[(globalThis as any).__current_route]: '',
}
}
protected getFilesystemPaths() {
return new Set<string>()
}
protected getPrerenderManifest() {
return {
version: 3 as const,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: '',
previewModeSigningKey: '',
previewModeEncryptionKey: '',
},
}
}
protected async renderHTML(
req: WebNextRequest,
_res: WebNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts
): Promise<RenderResult | null> {
return renderToHTML(
{
url: pathname,
cookies: req.cookies,
headers: req.headers,
} as any,
{} as any,
pathname,
query,
{
...renderOpts,
supportsDynamicHTML: true,
concurrentFeatures: true,
disableOptimizedLoading: true,
}
)
}
protected async sendRenderResult(
_req: WebNextRequest,
res: WebNextResponse,
options: {
result: RenderResult
type: 'html' | 'json'
generateEtags: boolean
poweredByHeader: boolean
options?: PayloadOptions | undefined
}
): Promise<void> {
// @TODO
const writer = res.transformStream.writable.getWriter()
const encoder = new TextEncoder()
options.result.pipe({
write: (str: string) => writer.write(encoder.encode(str)),
end: () => writer.close(),
// Not implemented: cork/uncork/on/removeListener
} as any)
// To prevent Safari's bfcache caching the "shell", we have to add the
// `no-cache` header to document responses.
res.setHeader(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
res.send()
}
protected async runApi() {
// @TODO
return true
}
protected async findPageComponents(
pathname: string,
query?: NextParsedUrlQuery,
params?: Params | null
) {
if (pathname === (globalThis as any).__current_route) {
return {
query: {
...(query || {}),
...(params || {}),
},
components: (globalThis as any)
.__server_context as LoadComponentsReturnType,
}
}
if (pathname === '/_error') {
const errorMod = (globalThis as any).__server_context.errorMod
return {
query: {
...(query || {}),
...(params || {}),
},
components: {
...(globalThis as any).__server_context,
Component: errorMod.default,
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
} as LoadComponentsReturnType,
}
}
return null
}
}
export default function Pid() { export default function Pid({ router }) {
return '[pid]' // TODO: display based on query return <div>{`query: ${router.query.dynamic}`}</div>
} }
...@@ -344,20 +344,18 @@ async function runBasicTests(context, env) { ...@@ -344,20 +344,18 @@ async function runBasicTests(context, env) {
expect(homeHTML).toContain('path:/') expect(homeHTML).toContain('path:/')
expect(homeHTML).toContain('foo.client') expect(homeHTML).toContain('foo.client')
expect(dynamicRouteHTML1).toContain('[pid]') expect(dynamicRouteHTML1).toContain('query: dynamic1')
expect(dynamicRouteHTML2).toContain('[pid]') expect(dynamicRouteHTML2).toContain('query: dynamic2')
const $404 = cheerio.load(path404HTML) const $404 = cheerio.load(path404HTML)
expect($404('#__next').text()).toBe(page404Content) expect($404('#__next').text()).toBe(page404Content)
// in dev mode: custom error page is still using default _error // In dev mode: it should show the error popup.
expect(path500HTML).toContain( expect(path500HTML).toContain(isDev ? 'Error: oops' : 'custom-500-page')
isDev ? 'Internal Server Error' : 'custom-500-page'
)
expect(pathNotFoundHTML).toContain(page404Content) expect(pathNotFoundHTML).toContain(page404Content)
}) })
it('should disable cache for RSC pages', async () => { it('should disable cache for fizz pages', async () => {
const urls = ['/', '/next-api/image', '/next-api/link'] const urls = ['/', '/next-api/image', '/next-api/link']
await Promise.all( await Promise.all(
urls.map(async (url) => { urls.map(async (url) => {
...@@ -377,16 +375,21 @@ async function runBasicTests(context, env) { ...@@ -377,16 +375,21 @@ async function runBasicTests(context, env) {
expect(linkText).toContain('go home') expect(linkText).toContain('go home')
const browser = await webdriver(context.appPort, '/next-api/link') const browser = await webdriver(context.appPort, '/next-api/link')
// We need to make sure the app is fully hydrated before clicking, otherwise
// it will be a full redirection instead of being taken over by the next
// router. This timeout prevents it being flaky caused by fast refresh's
// rebuilding event.
await new Promise((res) => setTimeout(res, 1000))
await browser.eval('window.beforeNav = 1') await browser.eval('window.beforeNav = 1')
await browser.waitForElementByCss('#next_id').click() await browser.waitForElementByCss('#next_id').click()
await check(() => browser.elementByCss('#query').text(), 'query:1') await check(() => browser.elementByCss('#query').text(), 'query:1')
await browser.waitForElementByCss('#next_id').click() await browser.waitForElementByCss('#next_id').click()
await check(() => browser.elementByCss('#query').text(), 'query:2') await check(() => browser.elementByCss('#query').text(), 'query:2')
if (!isDev) { expect(await browser.eval('window.beforeNav')).toBe(1)
expect(await browser.eval('window.beforeNav')).toBe(1)
}
}) })
it('should suspense next/image on server side', async () => { it('should suspense next/image on server side', 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