Unverified Commit c84be735 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add nodejs runtime support for middleware (#75624)

This allows setting `runtime: 'nodejs'` in middleware, which removes the
constraint of only using edge runtime APIs for middleware. This doesn't
change the signature of middleware and it still receives `(req:
NextRequest, event: NextFetchEvent) => Response`.

x-ref: https://github.com/vercel/next.js/discussions/71727
x-ref: https://github.com/vercel/next.js/discussions/46722
parent 5f73def0
......@@ -614,12 +614,7 @@ export async function getPagesPageStaticInfo({
const config = parsePagesSegmentConfig(exportedConfig, route)
const isAnAPIRoute = isAPIRoute(route)
const resolvedRuntime =
isEdgeRuntime(config.runtime ?? config.config?.runtime) ||
getServerSideProps ||
getStaticProps
? config.runtime ?? config.config?.runtime
: undefined
const resolvedRuntime = config.runtime ?? config.config?.runtime
if (resolvedRuntime === SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge(isAnAPIRoute ? page! : null)
......
......@@ -9,6 +9,7 @@ import type {
MiddlewareMatcher,
PageStaticInfo,
} from './analysis/get-page-static-info'
import * as Log from './output/log'
import type { LoadedEnvFiles } from '@next/env'
import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
......@@ -517,9 +518,15 @@ export function runDependingOnPageType<T>(params: {
}
if (isMiddlewareFile(params.page)) {
params.onEdgeServer()
return
if (params.pageRuntime === 'nodejs') {
params.onServer()
return
} else {
params.onEdgeServer()
return
}
}
if (isAPIRoute(params.page)) {
if (isEdgeRuntime(params.pageRuntime)) {
params.onEdgeServer()
......@@ -650,6 +657,20 @@ export async function createEntrypoints(
const isInstrumentation =
isInstrumentationHookFile(page) && pagesType === PAGE_TYPES.ROOT
let pageRuntime = staticInfo?.runtime
if (
isMiddlewareFile(page) &&
!config.experimental.nodeMiddleware &&
pageRuntime === 'nodejs'
) {
Log.warn(
'nodejs runtime support for middleware requires experimental.nodeMiddleware be enabled in your next.config'
)
pageRuntime = 'edge'
}
runDependingOnPageType({
page,
pageRuntime: staticInfo.runtime,
......@@ -692,6 +713,20 @@ export async function createEntrypoints(
isEdgeServer: false,
isDev: false,
})
} else if (isMiddlewareFile(page)) {
server[serverBundlePath] = getEdgeServerEntry({
...params,
rootDir,
absolutePagePath: absolutePagePath,
bundlePath: clientBundlePath,
isDev: false,
isServerComponent,
page,
middleware: staticInfo?.middleware,
pagesType,
preferredRegion: staticInfo.preferredRegion,
middlewareConfig: staticInfo.middleware,
})
} else if (isAPIRoute(page)) {
server[serverBundlePath] = [
getRouteLoaderEntry({
......
......@@ -497,12 +497,19 @@ async function writeClientSsgManifest(
)
}
interface FunctionsConfigManifest {
export interface FunctionsConfigManifest {
version: number
functions: Record<
string,
{
maxDuration?: number | undefined
runtime?: 'nodejs'
matchers?: Array<{
regexp: string
originalSource: string
has?: Rewrite['has']
missing?: Rewrite['has']
}>
}
>
}
......@@ -2224,6 +2231,7 @@ export default async function build(
path.relative(distDir, pagesManifestPath),
BUILD_MANIFEST,
PRERENDER_MANIFEST,
path.join(SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST),
path.join(SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
path.join(SERVER_DIRECTORY, MIDDLEWARE_BUILD_MANIFEST + '.js'),
...(config.experimental.streamingMetadata
......@@ -2300,6 +2308,34 @@ export default async function build(
)
}
const middlewareFile = rootPaths.find((p) =>
p.includes(MIDDLEWARE_FILENAME)
)
if (middlewareFile) {
const staticInfo = await getStaticInfoIncludingLayouts({
isInsideAppDir: false,
pageFilePath: path.join(dir, middlewareFile),
config,
appDir,
pageExtensions: config.pageExtensions,
isDev: false,
page: 'middleware',
})
if (staticInfo.runtime === 'nodejs') {
functionsConfigManifest.functions['/_middleware'] = {
runtime: staticInfo.runtime,
matchers: staticInfo.middleware?.matchers ?? [
{
regexp: '^.*$',
originalSource: '/:path*',
},
],
}
}
}
await writeFunctionsConfigManifest(distDir, functionsConfigManifest)
if (!isGenerateMode && !buildTracesPromise) {
......
......@@ -44,7 +44,9 @@ function createEdgeRuntimeManifest(originAssetMap: BuildManifest): string {
lowPriorityFiles: [],
}
const manifestDefCode = `self.__BUILD_MANIFEST = ${JSON.stringify(
// we use globalThis here because middleware can be node
// which doesn't have "self"
const manifestDefCode = `globalThis.__BUILD_MANIFEST = ${JSON.stringify(
assetMap,
null,
2
......@@ -52,7 +54,7 @@ function createEdgeRuntimeManifest(originAssetMap: BuildManifest): string {
// edge lowPriorityFiles item: '"/static/" + process.env.__NEXT_BUILD_ID + "/low-priority.js"'.
// Since lowPriorityFiles is not fixed and relying on `process.env.__NEXT_BUILD_ID`, we'll produce code creating it dynamically.
const lowPriorityFilesCode =
`self.__BUILD_MANIFEST.lowPriorityFiles = [\n` +
`globalThis.__BUILD_MANIFEST.lowPriorityFiles = [\n` +
manifestFilenames
.map((filename) => {
return `"/static/" + process.env.__NEXT_BUILD_ID + "/${filename}",\n`
......
......@@ -252,6 +252,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
excludeDefaultMomentLocales: z.boolean().optional(),
experimental: z
.strictObject({
nodeMiddleware: z.boolean().optional(),
after: z.boolean().optional(),
appDocumentPreloading: z.boolean().optional(),
appIsrStatus: z.boolean().optional(),
......
......@@ -259,6 +259,7 @@ export interface LoggingConfig {
}
export interface ExperimentalConfig {
nodeMiddleware?: boolean
cacheHandlers?: {
default?: string
remote?: string
......@@ -1129,6 +1130,7 @@ export const defaultConfig: NextConfig = {
modularizeImports: undefined,
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
experimental: {
nodeMiddleware: false,
cacheLife: {
default: {
stale: undefined, // defaults to staleTimes.static
......
......@@ -888,9 +888,22 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
const isInstrumentation =
isInstrumentationHookFile(page) && pageType === PAGE_TYPES.ROOT
let pageRuntime = staticInfo?.runtime
if (
isMiddlewareFile(page) &&
!this.config.experimental.nodeMiddleware &&
pageRuntime === 'nodejs'
) {
Log.warn(
'nodejs runtime support for middleware requires experimental.nodeMiddleware be enabled in your next.config'
)
pageRuntime = 'edge'
}
runDependingOnPageType({
page,
pageRuntime: staticInfo?.runtime,
pageRuntime,
pageType,
onEdgeServer: () => {
// TODO-APP: verify if child entry should support.
......@@ -1011,6 +1024,20 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
value,
hasAppDir,
})
} else if (isMiddlewareFile(page)) {
value = getEdgeServerEntry({
absolutePagePath: entryData.absolutePagePath,
rootDir: this.dir,
buildId: this.buildId,
bundlePath,
config: this.config,
isDev: true,
page,
pages: this.pagesMapping,
isServerComponent,
pagesType: PAGE_TYPES.PAGES,
preferredRegion: staticInfo?.preferredRegion,
})
} else if (isAppPath) {
value = getAppEntry({
name: bundlePath,
......@@ -1377,9 +1404,11 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
const pageChanges = serverOnlyChanges
.concat(edgeServerOnlyChanges)
.filter((key) => key.startsWith('pages/'))
const middlewareChanges = Array.from(changedEdgeServerPages).filter(
(name) => isMiddlewareFilename(name)
)
const middlewareChanges = [
...Array.from(changedEdgeServerPages),
...Array.from(changedServerPages),
].filter((name) => isMiddlewareFilename(name))
if (middlewareChanges.length > 0) {
this.send({
......
......@@ -802,9 +802,15 @@ export function onDemandEntryHandler({
const isServerComponent =
isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client
let pageRuntime = staticInfo.runtime
if (isMiddlewareFile(page) && !nextConfig.experimental.nodeMiddleware) {
pageRuntime = 'edge'
}
runDependingOnPageType({
page: route.page,
pageRuntime: staticInfo.runtime,
pageRuntime,
pageType: pageBundleType,
onClient: () => {
// Skip adding the client entry for app / Server Components.
......
import type {
FunctionsConfigManifest,
ManifestRoute,
PrerenderManifest,
RoutesManifest,
......@@ -30,6 +31,7 @@ import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/midd
import {
APP_PATH_ROUTES_MANIFEST,
BUILD_ID_FILE,
FUNCTIONS_CONFIG_MANIFEST,
MIDDLEWARE_MANIFEST,
PAGES_MANIFEST,
PRERENDER_MANIFEST,
......@@ -201,6 +203,11 @@ export async function setupFsCheck(opts: {
'server',
MIDDLEWARE_MANIFEST
)
const functionsConfigManifestPath = path.join(
distDir,
'server',
FUNCTIONS_CONFIG_MANIFEST
)
const pagesManifestPath = path.join(distDir, 'server', PAGES_MANIFEST)
const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)
......@@ -216,6 +223,10 @@ export async function setupFsCheck(opts: {
await fs.readFile(middlewareManifestPath, 'utf8').catch(() => '{}')
) as MiddlewareManifest
const functionsConfigManifest = JSON.parse(
await fs.readFile(functionsConfigManifestPath, 'utf8').catch(() => '{}')
) as FunctionsConfigManifest
const pagesManifest = JSON.parse(
await fs.readFile(pagesManifestPath, 'utf8')
)
......@@ -274,6 +285,12 @@ export async function setupFsCheck(opts: {
middlewareMatcher = getMiddlewareRouteMatcher(
middlewareManifest.middleware?.['/']?.matchers
)
} else if (functionsConfigManifest?.functions['/_middleware']) {
middlewareMatcher = getMiddlewareRouteMatcher(
functionsConfigManifest.functions['/_middleware'].matchers ?? [
{ regexp: '.*', originalSource: '/:path*' },
]
)
}
customRoutes = {
......
......@@ -41,6 +41,7 @@ import {
NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
FUNCTIONS_CONFIG_MANIFEST,
} from '../shared/lib/constants'
import { findDir } from '../lib/find-pages-dir'
import { NodeNextRequest, NodeNextResponse } from './base-http/node'
......@@ -110,6 +111,7 @@ import { AwaiterOnce } from './after/awaiter'
import { AsyncCallbackSet } from './lib/async-callback-set'
import DefaultCacheHandler from './lib/cache-handlers/default'
import { cacheHandlerGlobal, cacheHandlersSymbol } from './use-cache/constants'
import type { UnwrapPromise } from '../lib/coalesced-function'
export * from './base-server'
......@@ -1343,6 +1345,19 @@ export default class NextNodeServer extends BaseServer<
const manifest = this.getMiddlewareManifest()
const middleware = manifest?.middleware?.['/']
if (!middleware) {
const middlewareModule = this.loadNodeMiddleware()
if (middlewareModule) {
return {
match: getMiddlewareRouteMatcher(
middlewareModule.config?.matchers || [
{ regexp: '.*', originalSource: '/:path*' },
]
),
page: '/',
}
}
return
}
......@@ -1420,6 +1435,30 @@ export default class NextNodeServer extends BaseServer<
}
}
private loadNodeMiddleware() {
if (!this.nextConfig.experimental.nodeMiddleware) {
return
}
try {
const functionsConfig = this.renderOpts.dev
? {}
: require(join(this.distDir, 'server', FUNCTIONS_CONFIG_MANIFEST))
if (this.renderOpts.dev || functionsConfig?.functions?.['/_middleware']) {
return require(join(this.distDir, 'server', 'middleware.js'))
}
} catch (err) {
if (
isError(err) &&
err.code !== 'ENOENT' &&
err.code !== 'MODULE_NOT_FOUND'
) {
throw err
}
}
}
/**
* Checks if a middleware exists. This method is useful for the development
* server where we need to check the filesystem. Here we just check the
......@@ -1427,6 +1466,10 @@ export default class NextNodeServer extends BaseServer<
*/
protected async hasMiddleware(pathname: string): Promise<boolean> {
const info = this.getEdgeFunctionInfo({ page: pathname, middleware: true })
if (!info && this.loadNodeMiddleware()) {
return true
}
return Boolean(info && info.paths.length > 0)
}
......@@ -1512,36 +1555,63 @@ export default class NextNodeServer extends BaseServer<
middleware: true,
})
const method = (params.request.method || 'GET').toUpperCase()
const requestData = {
headers: params.request.headers,
method,
nextConfig: {
basePath: this.nextConfig.basePath,
i18n: this.nextConfig.i18n,
trailingSlash: this.nextConfig.trailingSlash,
experimental: this.nextConfig.experimental,
},
url: url,
page,
body:
method !== 'GET' && method !== 'HEAD'
? (getRequestMeta(params.request, 'clonableBody') as any)
: undefined,
signal: signalFromNodeResponse(params.response.originalResponse),
waitUntil: this.getWaitUntil(),
}
let result:
| UnwrapPromise<ReturnType<typeof import('./web/sandbox').run>>
| undefined
// if no middleware info check for Node.js middleware
// this is not in the middleware-manifest as that historically
// has only included edge-functions, we need to do a breaking
// version bump for that manifest to write this info there if
// we decide we want to
if (!middlewareInfo) {
throw new MiddlewareNotFoundError()
}
let middlewareModule
middlewareModule = this.loadNodeMiddleware()
const method = (params.request.method || 'GET').toUpperCase()
const { run } = require('./web/sandbox') as typeof import('./web/sandbox')
if (!middlewareModule) {
throw new MiddlewareNotFoundError()
}
const adapterFn: typeof import('./web/adapter').adapter =
middlewareModule.default || middlewareModule
const result = await run({
distDir: this.distDir,
name: middlewareInfo.name,
paths: middlewareInfo.paths,
edgeFunctionEntry: middlewareInfo,
request: {
headers: params.request.headers,
method,
nextConfig: {
basePath: this.nextConfig.basePath,
i18n: this.nextConfig.i18n,
trailingSlash: this.nextConfig.trailingSlash,
experimental: this.nextConfig.experimental,
},
url: url,
page,
body: getRequestMeta(params.request, 'clonableBody'),
signal: signalFromNodeResponse(params.response.originalResponse),
waitUntil: this.getWaitUntil(),
},
useCache: true,
onWarning: params.onWarning,
})
result = await adapterFn({
handler: middlewareModule.middleware || middlewareModule,
request: requestData,
page: 'middleware',
})
} else {
const { run } = require('./web/sandbox') as typeof import('./web/sandbox')
result = await run({
distDir: this.distDir,
name: middlewareInfo.name,
paths: middlewareInfo.paths,
edgeFunctionEntry: middlewareInfo,
request: requestData,
useCache: true,
onWarning: params.onWarning,
})
}
if (!this.renderOpts.dev) {
result.waitUntil.catch((error) => {
......
......@@ -103,7 +103,8 @@ export async function adapter(
await ensureInstrumentationRegistered()
// TODO-APP: use explicit marker for this
const isEdgeRendering = typeof self.__BUILD_MANIFEST !== 'undefined'
const isEdgeRendering =
typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'
params.request.url = normalizeRscURL(params.request.url)
......
......@@ -82,6 +82,10 @@ function __import_unsupported(moduleName: string) {
}
function enhanceGlobals() {
if (process.env.NEXT_RUNTIME !== 'edge') {
return
}
// The condition is true when the "process" module is provided
if (process !== global.process) {
// prefer local process but global.process has correct "env"
......
......@@ -423,7 +423,9 @@ export class TurbopackManifestLoader {
)
await writeFileAtomic(
middlewareBuildManifestPath,
`self.__BUILD_MANIFEST=${JSON.stringify(buildManifest)};`
// we use globalThis here because middleware can be node
// which doesn't have "self"
`globalThis.__BUILD_MANIFEST=${JSON.stringify(buildManifest)};`
)
const interceptionRewrites = JSON.stringify(
......
/* global globalThis */
import { NextRequest, NextResponse } from 'next/server'
import magicValue from 'shared-package'
export const config = {
regions: 'auto',
runtime: 'nodejs',
}
const PATTERNS = []
const params = (url) => {
const input = url.split('?')[0]
let result = {}
for (const [pattern, handler] of PATTERNS) {
const patternResult = pattern.exec(input)
if (patternResult !== null && 'pathname' in patternResult) {
result = handler(patternResult)
break
}
}
return result
}
export async function middleware(request) {
const url = request.nextUrl
if (process.env.NEXT_RUNTIME === 'nodejs') {
if (url.pathname.startsWith('/test-node-fs')) {
const fs = await import('fs')
const path = await import('path')
const pkgPath = path.join(process.cwd(), 'package.json')
const pkgData = JSON.parse(await fs.promises.readFile(pkgPath, 'utf8'))
return NextResponse.json(pkgData)
}
}
if (request.headers.get('x-prerender-revalidate')) {
return NextResponse.next({
headers: { 'x-middleware': 'hi' },
})
}
// this is needed for tests to get the BUILD_ID
if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
return NextResponse.next()
}
if (
url.pathname.includes('/_next/static/chunks/pages/_app-non-existent.js')
) {
return NextResponse.rewrite('https://example.vercel.sh')
}
if (url.pathname === '/api/edge-search-params') {
const newUrl = url.clone()
newUrl.searchParams.set('foo', 'bar')
return NextResponse.rewrite(newUrl)
}
if (url.pathname === '/') {
url.pathname = '/ssg/first'
return NextResponse.rewrite(url)
}
if (url.pathname === '/to-ssg') {
url.pathname = '/ssg/hello'
url.searchParams.set('from', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname === '/sha') {
url.pathname = '/shallow'
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/fetch-user-agent-default')) {
try {
const apiRoute = new URL(url)
apiRoute.pathname = '/api/headers'
const res = await fetch(withLocalIp(apiRoute))
return serializeData(await res.text())
} catch (err) {
return serializeError(err)
}
}
if (url.pathname === '/rewrite-to-dynamic') {
url.pathname = '/blog/from-middleware'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-to-config-rewrite') {
url.pathname = '/rewrite-3'
url.searchParams.set('some', 'middleware')
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/fetch-user-agent-crypto')) {
try {
const apiRoute = new URL(url)
apiRoute.pathname = '/api/headers'
const res = await fetch(withLocalIp(apiRoute), {
headers: {
'user-agent': 'custom-agent',
},
})
return serializeData(await res.text())
} catch (err) {
return serializeError(err)
}
}
if (url.pathname === '/global') {
return serializeData(
JSON.stringify({
process: {
env: {
ANOTHER_MIDDLEWARE_TEST: process.env.ANOTHER_MIDDLEWARE_TEST,
STRING_ENV_VAR: process.env.STRING_ENV_VAR,
MIDDLEWARE_TEST: process.env.MIDDLEWARE_TEST,
NEXT_RUNTIME: process.env.NEXT_RUNTIME,
},
},
})
)
}
if (url.pathname.endsWith('/globalthis')) {
return serializeData(JSON.stringify(Object.keys(globalThis)))
}
if (url.pathname.endsWith('/webcrypto')) {
const response = {}
try {
const algorithm = {
name: 'RSA-PSS',
hash: 'SHA-256',
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: 2048,
}
const keyUsages = ['sign', 'verify']
await crypto.subtle.generateKey(algorithm, false, keyUsages)
} catch (err) {
response.error = true
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname.endsWith('/fetch-url')) {
const response = {}
try {
await fetch(new URL('http://localhost'))
} catch (err) {
response.error = {
name: err.name,
message: err.message,
}
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname === '/abort-controller') {
const controller = new AbortController()
const signal = controller.signal
controller.abort()
const response = {}
try {
await fetch('https://example.vercel.sh', { signal })
} catch (err) {
response.error = {
name: err.name,
message: err.message,
}
} finally {
return serializeData(JSON.stringify(response))
}
}
if (url.pathname.endsWith('/root-subrequest')) {
const res = await fetch(url)
res.headers.set('x-dynamic-path', 'true')
return res
}
if (url.pathname === '/about') {
if (magicValue !== 42) throw new Error('shared-package problem')
return NextResponse.rewrite(new URL('/about/a', request.url))
}
if (url.pathname === '/redirect-to-somewhere') {
url.pathname = '/somewhere'
return NextResponse.redirect(url, {
headers: {
'x-redirect-header': 'hi',
},
})
}
if (url.pathname.startsWith('/url')) {
try {
if (request.nextUrl.pathname === '/url/relative-url') {
new URL('/relative')
return Response.next()
}
if (request.nextUrl.pathname === '/url/relative-request') {
await fetch(new Request('/urls-b'))
return Response.next()
}
if (request.nextUrl.pathname === '/url/relative-redirect') {
return Response.redirect('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-redirect') {
return NextResponse.redirect('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-rewrite') {
return NextResponse.rewrite('/urls-b')
}
if (request.nextUrl.pathname === '/url/relative-next-request') {
await fetch(new NextRequest('/urls-b'))
return NextResponse.next()
}
} catch (error) {
return new NextResponse(null, { headers: { error: error.message } })
}
}
if (url.pathname === '/ssr-page') {
url.pathname = '/ssr-page-2'
return NextResponse.rewrite(url)
}
if (url.pathname === '/error-throw' && request.__isData) {
throw new Error('test error')
}
const original = new URL(request.url)
return NextResponse.next({
headers: {
'req-url-path': `${original.pathname}${original.search}`,
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-query': request.nextUrl.searchParams.get('foo'),
'req-url-locale': request.nextUrl.locale,
'req-url-params':
url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}',
},
})
}
function serializeData(data) {
return new NextResponse(null, { headers: { data } })
}
function serializeError(error) {
return new NextResponse(null, { headers: { error: error.message } })
}
function withLocalIp(url) {
return String(url).replace('localhost', '127.0.0.1')
}
......@@ -2,7 +2,9 @@
import { NextRequest, NextResponse, URLPattern } from 'next/server'
import magicValue from 'shared-package'
export const config = { regions: 'auto' }
export const config = {
regions: 'auto',
}
const PATTERNS = [
[
......
......@@ -3,7 +3,7 @@
import fs from 'fs-extra'
import { join } from 'path'
import webdriver from 'next-webdriver'
import { NextInstance } from 'e2e-utils'
import { isNextStart, NextInstance } from 'e2e-utils'
import {
check,
fetchViaHTTP,
......@@ -17,6 +17,12 @@ const urlsError = 'Please use only absolute URLs'
describe('Middleware Runtime', () => {
let next: NextInstance
const isNodeMiddleware = Boolean(process.env.TEST_NODE_MIDDLEWARE)
if (isNodeMiddleware && (global as any).isNextDeploy) {
return it('should skip deploy for node middleware for now', () => {})
}
const setup = ({ i18n }: { i18n: boolean }) => {
afterAll(async () => {
await next.destroy()
......@@ -24,7 +30,13 @@ describe('Middleware Runtime', () => {
beforeAll(async () => {
next = await createNext({
files: {
'middleware.js': new FileRef(join(__dirname, '../app/middleware.js')),
'middleware.js': new FileRef(
join(
__dirname,
'../app',
isNodeMiddleware ? 'middleware-node.js' : 'middleware.js'
)
),
pages: new FileRef(join(__dirname, '../app/pages')),
'shared-package': new FileRef(
join(__dirname, '../app/node_modules/shared-package')
......@@ -33,6 +45,7 @@ describe('Middleware Runtime', () => {
nextConfig: {
experimental: {
webpackBuildWorker: true,
nodeMiddleware: true,
},
...(i18n
? {
......@@ -102,6 +115,34 @@ describe('Middleware Runtime', () => {
}
function runTests({ i18n }: { i18n?: boolean }) {
if (isNodeMiddleware) {
it('should be able to use node builtins with node runtime', async () => {
const res = await next.fetch('/test-node-fs')
expect(res.status).toBe(200)
const body = await res.json()
expect(body.dependencies || body.devDependencies).toBeTruthy()
})
if (isNextStart) {
it('should have added middleware in functions manifest', async () => {
const { functions } = await next.readJSON(
'.next/server/functions-config-manifest.json'
)
expect(functions['/_middleware']).toEqual({
runtime: 'nodejs',
matchers: [
{
regexp: '^.*$',
originalSource: '/:path*',
},
],
})
})
}
}
it('should handle 404 on fallback: false route correctly', async () => {
const res = await next.fetch('/ssg-fallback-false/first')
expect(res.status).toBe(200)
......@@ -170,7 +211,7 @@ describe('Middleware Runtime', () => {
})
}
if ((global as any).isNextStart) {
if ((global as any).isNextStart && !isNodeMiddleware) {
it('should have valid middleware field in manifest', async () => {
const manifest = await fs.readJSON(
join(next.testDir, '.next/server/middleware-manifest.json')
......@@ -523,7 +564,7 @@ describe('Middleware Runtime', () => {
const res = await fetchViaHTTP(next.url, `/fetch-user-agent-default`)
expect(readMiddlewareJSON(res).headers['user-agent']).toBe(
'Next.js Middleware'
isNodeMiddleware ? 'node' : 'Next.js Middleware'
)
const res2 = await fetchViaHTTP(next.url, `/fetch-user-agent-crypto`)
......@@ -544,7 +585,7 @@ describe('Middleware Runtime', () => {
...((global as any).isNextDeploy
? {}
: {
NEXT_RUNTIME: 'edge',
NEXT_RUNTIME: isNodeMiddleware ? 'nodejs' : 'edge',
}),
})) {
expect(json.process.env[key]).toBe(value)
......@@ -586,9 +627,13 @@ describe('Middleware Runtime', () => {
expect(res.headers.get('req-url-basepath')).toBeFalsy()
expect(res.headers.get('req-url-pathname')).toBe('/static')
const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
expect(pathname).toBe(undefined)
expect(params).toEqual(undefined)
if (!isNodeMiddleware) {
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe(undefined)
expect(params).toEqual(undefined)
}
expect(res.headers.get('req-url-query')).not.toBe('bar')
})
......@@ -600,11 +645,13 @@ describe('Middleware Runtime', () => {
expect(res.headers.get('req-url-basepath')).toBeFalsy()
expect(res.headers.get('req-url-pathname')).toBe('/1')
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: '1' })
if (!isNodeMiddleware) {
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: '1' })
}
expect(res.headers.get('req-url-query')).not.toBe('bar')
expect(res.headers.get('req-url-locale')).toBe('fr')
......@@ -614,11 +661,13 @@ describe('Middleware Runtime', () => {
const res = await fetchViaHTTP(next.url, `/fr/abc123`)
expect(res.headers.get('req-url-basepath')).toBeFalsy()
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: 'abc123' })
if (!isNodeMiddleware) {
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: 'abc123' })
}
expect(res.headers.get('req-url-query')).not.toBe('bar')
expect(res.headers.get('req-url-locale')).toBe('fr')
......@@ -629,10 +678,14 @@ describe('Middleware Runtime', () => {
const res = await fetchViaHTTP(next.url, `/abc123?foo=bar`)
expect(res.headers.get('req-url-basepath')).toBeFalsy()
const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
if (!isNodeMiddleware) {
const { pathname, params } = JSON.parse(
res.headers.get('req-url-params')
)
expect(pathname).toBe('/:id')
expect(params).toEqual({ id: 'abc123' })
expect(pathname).toBe('/:id')
expect(params).toEqual({ id: 'abc123' })
}
expect(res.headers.get('req-url-query')).toBe('bar')
......@@ -658,12 +711,16 @@ describe('Middleware Runtime', () => {
// these errors differ on Vercel
it('should throw when using Request with a relative URL', async () => {
const response = await fetchViaHTTP(next.url, `/url/relative-request`)
expect(readMiddlewareError(response)).toContain(urlsError)
expect(readMiddlewareError(response)).toContain(
isNodeMiddleware ? 'Failed to parse URL from' : urlsError
)
})
it('should warn when using Response.redirect with a relative URL', async () => {
const response = await fetchViaHTTP(next.url, `/url/relative-redirect`)
expect(readMiddlewareError(response)).toContain(urlsError)
expect(readMiddlewareError(response)).toContain(
isNodeMiddleware ? 'Failed to parse URL from' : urlsError
)
})
}
......
process.env.TEST_NODE_MIDDLEWARE = 'true'
if (process.env.TURBOPACK) {
it('should skip', () => {})
} else {
require('./index.test')
}
......@@ -30,7 +30,7 @@ describe('parse page static info', () => {
nextConfig: createNextConfig(),
pageType: PAGE_TYPES.PAGES,
})
expect(runtime).toBe(undefined)
expect(runtime).toBe('nodejs')
expect(getServerSideProps).toBe(false)
expect(getStaticProps).toBe(false)
})
......
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