Unverified Commit b522b94c authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by GitHub

feat(next): Support has match and locale option on middleware config (#39257)

## Feature

As the title, support `has` match, `local`  that works the same with the `rewrites` and `redirects` of next.config.js on middleware config. With this PR, you can write the config like the following:

```js
export const config = {
  matcher: [
    "/foo",
    { source: "/bar" },
    {
      source: "/baz",
      has: [
        {
          type: 'header',
          key: 'x-my-header',
          value: 'my-value',
        }
      ]
    },
    {
      source: "/en/asdf",
      locale: false,
     },
  ]
}
```

Also, fixes https://github.com/vercel/next.js/issues/39428

related https://github.com/vercel/edge-functions/issues/178, https://github.com/vercel/edge-functions/issues/179

- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 481950c3
import { isServerRuntime } from '../../server/config-shared' import { isServerRuntime } from '../../server/config-shared'
import type { NextConfig } from '../../server/config-shared' import type { NextConfig } from '../../server/config-shared'
import type { Middleware, RouteHas } from '../../lib/load-custom-routes'
import { import {
extractExportedConstValue, extractExportedConstValue,
UnsupportedValueError, UnsupportedValueError,
...@@ -9,10 +10,17 @@ import { promises as fs } from 'fs' ...@@ -9,10 +10,17 @@ import { promises as fs } from 'fs'
import { tryToParsePath } from '../../lib/try-to-parse-path' import { tryToParsePath } from '../../lib/try-to-parse-path'
import * as Log from '../output/log' import * as Log from '../output/log'
import { SERVER_RUNTIME } from '../../lib/constants' import { SERVER_RUNTIME } from '../../lib/constants'
import { ServerRuntime } from '../../types' import { ServerRuntime } from 'next/types'
import { checkCustomRoutes } from '../../lib/load-custom-routes'
interface MiddlewareConfig { export interface MiddlewareConfig {
pathMatcher: RegExp matchers: MiddlewareMatcher[]
}
export interface MiddlewareMatcher {
regexp: string
locale?: false
has?: RouteHas[]
} }
export interface PageStaticInfo { export interface PageStaticInfo {
...@@ -81,55 +89,63 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) { ...@@ -81,55 +89,63 @@ async function tryToReadFile(filePath: string, shouldThrow: boolean) {
} }
} }
function getMiddlewareRegExpStrings( function getMiddlewareMatchers(
matcherOrMatchers: unknown, matcherOrMatchers: unknown,
nextConfig: NextConfig nextConfig: NextConfig
): string[] { ): MiddlewareMatcher[] {
let matchers: unknown[] = []
if (Array.isArray(matcherOrMatchers)) { if (Array.isArray(matcherOrMatchers)) {
return matcherOrMatchers.flatMap((matcher) => matchers = matcherOrMatchers
getMiddlewareRegExpStrings(matcher, nextConfig) } else {
) matchers.push(matcherOrMatchers)
} }
const { i18n } = nextConfig const { i18n } = nextConfig
if (typeof matcherOrMatchers !== 'string') { let routes = matchers.map(
throw new Error( (m) => (typeof m === 'string' ? { source: m } : m) as Middleware
'`matcher` must be a path matcher or an array of path matchers' )
)
}
let matcher: string = matcherOrMatchers // check before we process the routes and after to ensure
// they are still valid
checkCustomRoutes(routes, 'middleware')
if (!matcher.startsWith('/')) { routes = routes.map((r) => {
throw new Error('`matcher`: path matcher must start with /') let { source } = r
}
const isRoot = matcher === '/'
if (i18n?.locales) { const isRoot = source === '/'
matcher = `/:nextInternalLocale([^/.]{1,})${isRoot ? '' : matcher}`
}
matcher = `/:nextData(_next/data/[^/]{1,})?${matcher}${ if (i18n?.locales && r.locale !== false) {
isRoot source = `/:nextInternalLocale([^/.]{1,})${isRoot ? '' : source}`
? `(${nextConfig.i18n ? '|\\.json|' : ''}/?index|/?index\\.json)?` }
: '(.json)?'
}`
if (nextConfig.basePath) { source = `/:nextData(_next/data/[^/]{1,})?${source}${
matcher = `${nextConfig.basePath}${matcher}` isRoot
} ? `(${nextConfig.i18n ? '|\\.json|' : ''}/?index|/?index\\.json)?`
const parsedPage = tryToParsePath(matcher) : '(.json)?'
}`
if (parsedPage.error) { if (nextConfig.basePath) {
throw new Error(`Invalid path matcher: ${matcher}`) source = `${nextConfig.basePath}${source}`
} }
const regexes = [parsedPage.regexStr].filter((x): x is string => !!x) return { ...r, source }
if (regexes.length < 1) { })
throw new Error("Can't parse matcher")
} else { checkCustomRoutes(routes, 'middleware')
return regexes
} return routes.map((r) => {
const { source, ...rest } = r
const parsedPage = tryToParsePath(source)
if (parsedPage.error || !parsedPage.regexStr) {
throw new Error(`Invalid source: ${source}`)
}
return {
...rest,
regexp: parsedPage.regexStr,
}
})
} }
function getMiddlewareConfig( function getMiddlewareConfig(
...@@ -139,15 +155,7 @@ function getMiddlewareConfig( ...@@ -139,15 +155,7 @@ function getMiddlewareConfig(
const result: Partial<MiddlewareConfig> = {} const result: Partial<MiddlewareConfig> = {}
if (config.matcher) { if (config.matcher) {
result.pathMatcher = new RegExp( result.matchers = getMiddlewareMatchers(config.matcher, nextConfig)
getMiddlewareRegExpStrings(config.matcher, nextConfig).join('|')
)
if (result.pathMatcher.source.length > 4096) {
throw new Error(
`generated matcher config must be less than 4096 characters.`
)
}
} }
return result return result
......
...@@ -4,6 +4,10 @@ import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader' ...@@ -4,6 +4,10 @@ import type { EdgeSSRLoaderQuery } from './webpack/loaders/next-edge-ssr-loader'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import type { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import type { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type {
MiddlewareConfig,
MiddlewareMatcher,
} from './analysis/get-page-static-info'
import type { LoadedEnvFiles } from '@next/env' import type { LoadedEnvFiles } from '@next/env'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path' import { posix, join } from 'path'
...@@ -42,6 +46,7 @@ import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' ...@@ -42,6 +46,7 @@ import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { serverComponentRegex } from './webpack/loaders/utils' import { serverComponentRegex } from './webpack/loaders/utils'
import { ServerRuntime } from '../types' import { ServerRuntime } from '../types'
import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
...@@ -163,7 +168,7 @@ export function getEdgeServerEntry(opts: { ...@@ -163,7 +168,7 @@ export function getEdgeServerEntry(opts: {
isServerComponent: boolean isServerComponent: boolean
page: string page: string
pages: { [page: string]: string } pages: { [page: string]: string }
middleware?: { pathMatcher?: RegExp } middleware?: Partial<MiddlewareConfig>
pagesType?: 'app' | 'pages' | 'root' pagesType?: 'app' | 'pages' | 'root'
appDirLoader?: string appDirLoader?: string
}) { }) {
...@@ -171,12 +176,9 @@ export function getEdgeServerEntry(opts: { ...@@ -171,12 +176,9 @@ export function getEdgeServerEntry(opts: {
const loaderParams: MiddlewareLoaderOptions = { const loaderParams: MiddlewareLoaderOptions = {
absolutePagePath: opts.absolutePagePath, absolutePagePath: opts.absolutePagePath,
page: opts.page, page: opts.page,
// pathMatcher can have special characters that break the loader params matchers: opts.middleware?.matchers
// parsing so we base64 encode/decode the string ? encodeMatchers(opts.middleware.matchers)
matcherRegexp: Buffer.from( : '',
(opts.middleware?.pathMatcher && opts.middleware.pathMatcher.source) ||
''
).toString('base64'),
} }
return `next-middleware-loader?${stringify(loaderParams)}!` return `next-middleware-loader?${stringify(loaderParams)}!`
...@@ -347,7 +349,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -347,7 +349,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
const server: webpack.EntryObject = {} const server: webpack.EntryObject = {}
const client: webpack.EntryObject = {} const client: webpack.EntryObject = {}
const nestedMiddleware: string[] = [] const nestedMiddleware: string[] = []
let middlewareRegex: string | undefined = undefined let middlewareMatchers: MiddlewareMatcher[] | undefined = undefined
const getEntryHandler = const getEntryHandler =
(mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') => (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') =>
...@@ -402,7 +404,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -402,7 +404,9 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
}) })
if (isMiddlewareFile(page)) { if (isMiddlewareFile(page)) {
middlewareRegex = staticInfo.middleware?.pathMatcher?.source || '.*' middlewareMatchers = staticInfo.middleware?.matchers ?? [
{ regexp: '.*' },
]
if (target === 'serverless') { if (target === 'serverless') {
throw new MiddlewareInServerlessTargetError() throw new MiddlewareInServerlessTargetError()
...@@ -493,7 +497,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) { ...@@ -493,7 +497,7 @@ export async function createEntrypoints(params: CreateEntrypointsParams) {
client, client,
server, server,
edgeServer, edgeServer,
middlewareRegex, middlewareMatchers,
} }
} }
......
...@@ -849,7 +849,7 @@ export default async function build( ...@@ -849,7 +849,7 @@ export default async function build(
runWebpackSpan, runWebpackSpan,
target, target,
appDir, appDir,
middlewareRegex: entrypoints.middlewareRegex, middlewareMatchers: entrypoints.middlewareMatchers,
} }
const configs = await runWebpackSpan const configs = await runWebpackSpan
......
...@@ -54,6 +54,7 @@ import type { ...@@ -54,6 +54,7 @@ import type {
SWC_TARGET_TRIPLE, SWC_TARGET_TRIPLE,
} from './webpack/plugins/telemetry-plugin' } from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace' import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import { withoutRSCExtensions } from './utils' import { withoutRSCExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist' import browserslist from 'next/dist/compiled/browserslist'
import loadJsConfig from './load-jsconfig' import loadJsConfig from './load-jsconfig'
...@@ -90,7 +91,7 @@ export function getDefineEnv({ ...@@ -90,7 +91,7 @@ export function getDefineEnv({
hasReactRoot, hasReactRoot,
isNodeServer, isNodeServer,
isEdgeServer, isEdgeServer,
middlewareRegex, middlewareMatchers,
hasServerComponents, hasServerComponents,
}: { }: {
dev?: boolean dev?: boolean
...@@ -100,7 +101,7 @@ export function getDefineEnv({ ...@@ -100,7 +101,7 @@ export function getDefineEnv({
hasReactRoot?: boolean hasReactRoot?: boolean
isNodeServer?: boolean isNodeServer?: boolean
isEdgeServer?: boolean isEdgeServer?: boolean
middlewareRegex?: string middlewareMatchers?: MiddlewareMatcher[]
config: NextConfigComplete config: NextConfigComplete
hasServerComponents?: boolean hasServerComponents?: boolean
}) { }) {
...@@ -144,8 +145,8 @@ export function getDefineEnv({ ...@@ -144,8 +145,8 @@ export function getDefineEnv({
isEdgeServer ? 'edge' : 'nodejs' isEdgeServer ? 'edge' : 'nodejs'
), ),
}), }),
'process.env.__NEXT_MIDDLEWARE_REGEX': JSON.stringify( 'process.env.__NEXT_MIDDLEWARE_MATCHERS': JSON.stringify(
middlewareRegex || '' middlewareMatchers || []
), ),
'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH': JSON.stringify( 'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH': JSON.stringify(
config.experimental.manualClientBasePath config.experimental.manualClientBasePath
...@@ -510,7 +511,7 @@ export default async function getBaseWebpackConfig( ...@@ -510,7 +511,7 @@ export default async function getBaseWebpackConfig(
runWebpackSpan, runWebpackSpan,
target = COMPILER_NAMES.server, target = COMPILER_NAMES.server,
appDir, appDir,
middlewareRegex, middlewareMatchers,
}: { }: {
buildId: string buildId: string
config: NextConfigComplete config: NextConfigComplete
...@@ -525,7 +526,7 @@ export default async function getBaseWebpackConfig( ...@@ -525,7 +526,7 @@ export default async function getBaseWebpackConfig(
runWebpackSpan: Span runWebpackSpan: Span
target?: string target?: string
appDir?: string appDir?: string
middlewareRegex?: string middlewareMatchers?: MiddlewareMatcher[]
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
const isClient = compilerType === COMPILER_NAMES.client const isClient = compilerType === COMPILER_NAMES.client
...@@ -1673,7 +1674,7 @@ export default async function getBaseWebpackConfig( ...@@ -1673,7 +1674,7 @@ export default async function getBaseWebpackConfig(
hasReactRoot, hasReactRoot,
isNodeServer, isNodeServer,
isEdgeServer, isEdgeServer,
middlewareRegex, middlewareMatchers,
hasServerComponents, hasServerComponents,
}) })
), ),
......
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
/** /**
...@@ -25,7 +26,7 @@ export interface RouteMeta { ...@@ -25,7 +26,7 @@ export interface RouteMeta {
export interface EdgeMiddlewareMeta { export interface EdgeMiddlewareMeta {
page: string page: string
matcherRegexp?: string matchers?: MiddlewareMatcher[]
} }
export interface EdgeSSRMeta { export interface EdgeSSRMeta {
......
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { getModuleBuildInfo } from './get-module-build-info' import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request' import { stringifyRequest } from '../stringify-request'
import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants' import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants'
...@@ -5,23 +6,32 @@ import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants' ...@@ -5,23 +6,32 @@ import { MIDDLEWARE_LOCATION_REGEXP } from '../../../lib/constants'
export type MiddlewareLoaderOptions = { export type MiddlewareLoaderOptions = {
absolutePagePath: string absolutePagePath: string
page: string page: string
matcherRegexp?: string matchers?: string
}
// matchers can have special characters that break the loader params
// parsing so we base64 encode/decode the string
export function encodeMatchers(matchers: MiddlewareMatcher[]) {
return Buffer.from(JSON.stringify(matchers)).toString('base64')
}
export function decodeMatchers(encodedMatchers: string) {
return JSON.parse(
Buffer.from(encodedMatchers, 'base64').toString()
) as MiddlewareMatcher[]
} }
export default function middlewareLoader(this: any) { export default function middlewareLoader(this: any) {
const { const {
absolutePagePath, absolutePagePath,
page, page,
matcherRegexp: base64MatcherRegex, matchers: encodedMatchers,
}: MiddlewareLoaderOptions = this.getOptions() }: MiddlewareLoaderOptions = this.getOptions()
const matcherRegexp = Buffer.from( const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined
base64MatcherRegex || '',
'base64'
).toString()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath) const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module) const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeMiddleware = { buildInfo.nextEdgeMiddleware = {
matcherRegexp, matchers,
page: page:
page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), '') || '/', page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), '') || '/',
} }
......
...@@ -3,6 +3,7 @@ import type { ...@@ -3,6 +3,7 @@ import type {
EdgeMiddlewareMeta, EdgeMiddlewareMeta,
} from '../loaders/get-module-build-info' } from '../loaders/get-module-build-info'
import type { EdgeSSRMeta } from '../loaders/get-module-build-info' import type { EdgeSSRMeta } from '../loaders/get-module-build-info'
import type { MiddlewareMatcher } from '../../analysis/get-page-static-info'
import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex' import { getNamedMiddlewareRegex } from '../../../shared/lib/router/utils/route-regex'
import { getModuleBuildInfo } from '../loaders/get-module-build-info' import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
...@@ -23,13 +24,13 @@ export interface EdgeFunctionDefinition { ...@@ -23,13 +24,13 @@ export interface EdgeFunctionDefinition {
files: string[] files: string[]
name: string name: string
page: string page: string
regexp: string matchers: MiddlewareMatcher[]
wasm?: AssetBinding[] wasm?: AssetBinding[]
assets?: AssetBinding[] assets?: AssetBinding[]
} }
export interface MiddlewareManifest { export interface MiddlewareManifest {
version: 1 version: 2
sortedMiddleware: string[] sortedMiddleware: string[]
middleware: { [page: string]: EdgeFunctionDefinition } middleware: { [page: string]: EdgeFunctionDefinition }
functions: { [page: string]: EdgeFunctionDefinition } functions: { [page: string]: EdgeFunctionDefinition }
...@@ -49,7 +50,7 @@ const middlewareManifest: MiddlewareManifest = { ...@@ -49,7 +50,7 @@ const middlewareManifest: MiddlewareManifest = {
sortedMiddleware: [], sortedMiddleware: [],
middleware: {}, middleware: {},
functions: {}, functions: {},
version: 1, version: 2,
} }
/** /**
...@@ -138,14 +139,16 @@ function getCreateAssets(params: { ...@@ -138,14 +139,16 @@ function getCreateAssets(params: {
const { namedRegex } = getNamedMiddlewareRegex(page, { const { namedRegex } = getNamedMiddlewareRegex(page, {
catchAll: !metadata.edgeSSR && !metadata.edgeApiFunction, catchAll: !metadata.edgeSSR && !metadata.edgeApiFunction,
}) })
const regexp = metadata?.edgeMiddleware?.matcherRegexp || namedRegex const matchers = metadata?.edgeMiddleware?.matchers ?? [
{ regexp: namedRegex },
]
const edgeFunctionDefinition: EdgeFunctionDefinition = { const edgeFunctionDefinition: EdgeFunctionDefinition = {
env: Array.from(metadata.env), env: Array.from(metadata.env),
files: getEntryFiles(entrypoint.getFiles(), metadata), files: getEntryFiles(entrypoint.getFiles(), metadata),
name: entrypoint.name, name: entrypoint.name,
page: page, page: page,
regexp, matchers,
wasm: Array.from(metadata.wasmBindings, ([name, filePath]) => ({ wasm: Array.from(metadata.wasmBindings, ([name, filePath]) => ({
name, name,
filePath, filePath,
......
import type { ComponentType } from 'react' import type { ComponentType } from 'react'
import type { RouteLoader } from './route-loader' import type { RouteLoader } from './route-loader'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import { addBasePath } from './add-base-path' import { addBasePath } from './add-base-path'
import { interpolateAs } from '../shared/lib/router/router' import { interpolateAs } from '../shared/lib/router/router'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
...@@ -11,7 +12,7 @@ import { createRouteLoader, getClientBuildManifest } from './route-loader' ...@@ -11,7 +12,7 @@ import { createRouteLoader, getClientBuildManifest } from './route-loader'
declare global { declare global {
interface Window { interface Window {
__DEV_MIDDLEWARE_MANIFEST?: { location?: string } __DEV_MIDDLEWARE_MATCHERS?: MiddlewareMatcher[]
__DEV_PAGES_MANIFEST?: { pages: string[] } __DEV_PAGES_MANIFEST?: { pages: string[] }
__SSG_MANIFEST_CB?: () => void __SSG_MANIFEST_CB?: () => void
__SSG_MANIFEST?: Set<string> __SSG_MANIFEST?: Set<string>
...@@ -30,7 +31,7 @@ export default class PageLoader { ...@@ -30,7 +31,7 @@ export default class PageLoader {
private assetPrefix: string private assetPrefix: string
private promisedSsgManifest: Promise<Set<string>> private promisedSsgManifest: Promise<Set<string>>
private promisedDevPagesManifest?: Promise<string[]> private promisedDevPagesManifest?: Promise<string[]>
private promisedMiddlewareManifest?: Promise<{ location: string }> private promisedMiddlewareMatchers?: Promise<MiddlewareMatcher[]>
public routeLoader: RouteLoader public routeLoader: RouteLoader
...@@ -80,32 +81,32 @@ export default class PageLoader { ...@@ -80,32 +81,32 @@ export default class PageLoader {
getMiddleware() { getMiddleware() {
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
const middlewareRegex = process.env.__NEXT_MIDDLEWARE_REGEX const middlewareMatchers = process.env.__NEXT_MIDDLEWARE_MATCHERS
window.__MIDDLEWARE_MANIFEST = middlewareRegex window.__MIDDLEWARE_MATCHERS = middlewareMatchers
? { location: middlewareRegex } ? (middlewareMatchers as any as MiddlewareMatcher[])
: undefined : undefined
return window.__MIDDLEWARE_MANIFEST return window.__MIDDLEWARE_MATCHERS
} else { } else {
if (window.__DEV_MIDDLEWARE_MANIFEST) { if (window.__DEV_MIDDLEWARE_MATCHERS) {
return window.__DEV_MIDDLEWARE_MANIFEST return window.__DEV_MIDDLEWARE_MATCHERS
} else { } else {
if (!this.promisedMiddlewareManifest) { if (!this.promisedMiddlewareMatchers) {
// TODO: Decide what should happen when fetching fails instead of asserting // TODO: Decide what should happen when fetching fails instead of asserting
// @ts-ignore // @ts-ignore
this.promisedMiddlewareManifest = fetch( this.promisedMiddlewareMatchers = fetch(
`${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json` `${this.assetPrefix}/_next/static/${this.buildId}/_devMiddlewareManifest.json`
) )
.then((res) => res.json()) .then((res) => res.json())
.then((manifest: { location?: string }) => { .then((matchers: MiddlewareMatcher[]) => {
window.__DEV_MIDDLEWARE_MANIFEST = manifest window.__DEV_MIDDLEWARE_MATCHERS = matchers
return manifest return matchers
}) })
.catch((err) => { .catch((err) => {
console.log(`Failed to fetch _devMiddlewareManifest`, err) console.log(`Failed to fetch _devMiddlewareManifest`, err)
}) })
} }
// TODO Remove this assertion as this could be undefined // TODO Remove this assertion as this could be undefined
return this.promisedMiddlewareManifest! return this.promisedMiddlewareMatchers!
} }
} }
} }
......
import type { ComponentType } from 'react' import type { ComponentType } from 'react'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
import { __unsafeCreateTrustedScriptURL } from './trusted-types' import { __unsafeCreateTrustedScriptURL } from './trusted-types'
import { requestIdleCallback } from './request-idle-callback' import { requestIdleCallback } from './request-idle-callback'
...@@ -13,7 +14,7 @@ declare global { ...@@ -13,7 +14,7 @@ declare global {
interface Window { interface Window {
__BUILD_MANIFEST?: Record<string, string[]> __BUILD_MANIFEST?: Record<string, string[]>
__BUILD_MANIFEST_CB?: Function __BUILD_MANIFEST_CB?: Function
__MIDDLEWARE_MANIFEST?: { location: string } __MIDDLEWARE_MATCHERS?: MiddlewareMatcher[]
__MIDDLEWARE_MANIFEST_CB?: Function __MIDDLEWARE_MANIFEST_CB?: Function
} }
} }
......
...@@ -52,6 +52,12 @@ export type Redirect = { ...@@ -52,6 +52,12 @@ export type Redirect = {
} }
) )
export type Middleware = {
source: string
locale?: false
has?: RouteHas[]
}
const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host']) const allowedHasTypes = new Set(['header', 'cookie', 'query', 'host'])
const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g
...@@ -111,9 +117,9 @@ function checkHeader(route: Header): string[] { ...@@ -111,9 +117,9 @@ function checkHeader(route: Header): string[] {
export type RouteType = 'rewrite' | 'redirect' | 'header' export type RouteType = 'rewrite' | 'redirect' | 'header'
function checkCustomRoutes( export function checkCustomRoutes(
routes: Redirect[] | Header[] | Rewrite[], routes: Redirect[] | Header[] | Rewrite[] | Middleware[],
type: RouteType type: RouteType | 'middleware'
): void { ): void {
if (!Array.isArray(routes)) { if (!Array.isArray(routes)) {
console.error( console.error(
...@@ -127,17 +133,20 @@ function checkCustomRoutes( ...@@ -127,17 +133,20 @@ function checkCustomRoutes(
let hadInvalidStatus = false let hadInvalidStatus = false
let hadInvalidHas = false let hadInvalidHas = false
const allowedKeys = new Set<string>(['source', 'basePath', 'locale', 'has']) const allowedKeys = new Set<string>(['source', 'locale', 'has'])
if (type === 'rewrite') { if (type === 'rewrite') {
allowedKeys.add('basePath')
allowedKeys.add('destination') allowedKeys.add('destination')
} }
if (type === 'redirect') { if (type === 'redirect') {
allowedKeys.add('basePath')
allowedKeys.add('statusCode') allowedKeys.add('statusCode')
allowedKeys.add('permanent') allowedKeys.add('permanent')
allowedKeys.add('destination') allowedKeys.add('destination')
} }
if (type === 'header') { if (type === 'header') {
allowedKeys.add('basePath')
allowedKeys.add('headers') allowedKeys.add('headers')
} }
...@@ -146,9 +155,11 @@ function checkCustomRoutes( ...@@ -146,9 +155,11 @@ function checkCustomRoutes(
console.error( console.error(
`The route ${JSON.stringify( `The route ${JSON.stringify(
route route
)} is not a valid object with \`source\` and \`${ )} is not a valid object with \`source\`${
type === 'header' ? 'headers' : 'destination' type !== 'middleware'
}\`` ? ` and \`${type === 'header' ? 'headers' : 'destination'}\``
: ''
}`
) )
numInvalidRoutes++ numInvalidRoutes++
continue continue
...@@ -175,7 +186,11 @@ function checkCustomRoutes( ...@@ -175,7 +186,11 @@ function checkCustomRoutes(
const invalidKeys = keys.filter((key) => !allowedKeys.has(key)) const invalidKeys = keys.filter((key) => !allowedKeys.has(key))
const invalidParts: string[] = [] const invalidParts: string[] = []
if (typeof route.basePath !== 'undefined' && route.basePath !== false) { if (
'basePath' in route &&
typeof route.basePath !== 'undefined' &&
route.basePath !== false
) {
invalidParts.push('`basePath` must be undefined or false') invalidParts.push('`basePath` must be undefined or false')
} }
...@@ -237,7 +252,7 @@ function checkCustomRoutes( ...@@ -237,7 +252,7 @@ function checkCustomRoutes(
if (type === 'header') { if (type === 'header') {
invalidParts.push(...checkHeader(route as Header)) invalidParts.push(...checkHeader(route as Header))
} else { } else if (type !== 'middleware') {
let _route = route as Rewrite | Redirect let _route = route as Rewrite | Redirect
if (!_route.destination) { if (!_route.destination) {
invalidParts.push('`destination` is missing') invalidParts.push('`destination` is missing')
......
...@@ -5,6 +5,7 @@ import type { DynamicRoutes, PageChecker, Route } from './router' ...@@ -5,6 +5,7 @@ import type { DynamicRoutes, PageChecker, Route } from './router'
import type { FontManifest } from './font-utils' import type { FontManifest } from './font-utils'
import type { LoadComponentsReturnType } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { RouteMatch } from '../shared/lib/router/utils/route-matcher' import type { RouteMatch } from '../shared/lib/router/utils/route-matcher'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from '../shared/lib/router/utils/route-matcher' import type { Params } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig, NextConfigComplete } from './config-shared' import type { NextConfig, NextConfigComplete } from './config-shared'
import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta' import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
...@@ -68,6 +69,7 @@ import { getLocaleRedirect } from '../shared/lib/i18n/get-locale-redirect' ...@@ -68,6 +69,7 @@ import { getLocaleRedirect } from '../shared/lib/i18n/get-locale-redirect'
import { getHostname } from '../shared/lib/get-hostname' import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url' import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -80,6 +82,12 @@ export interface RoutingItem { ...@@ -80,6 +82,12 @@ export interface RoutingItem {
re?: RegExp re?: RegExp
} }
export interface MiddlewareRoutingItem {
page: string
match: MiddlewareRouteMatch
matchers?: MiddlewareMatcher[]
}
export interface Options { export interface Options {
/** /**
* Object containing the configuration next.config.js * Object containing the configuration next.config.js
......
...@@ -9,7 +9,8 @@ import type { ParsedUrlQuery } from 'querystring' ...@@ -9,7 +9,8 @@ import type { ParsedUrlQuery } from 'querystring'
import type { Server as HTTPServer } from 'http' import type { Server as HTTPServer } from 'http'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { RoutingItem } from '../base-server' import type { MiddlewareRoutingItem, RoutingItem } from '../base-server'
import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-info'
import crypto from 'crypto' import crypto from 'crypto'
import fs from 'fs' import fs from 'fs'
...@@ -34,6 +35,7 @@ import { ...@@ -34,6 +35,7 @@ import {
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import Server, { WrappedBuildError } from '../next-server' import Server, { WrappedBuildError } from '../next-server'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { absolutePathToPage } from '../../shared/lib/page-path/absolute-path-to-page' import { absolutePathToPage } from '../../shared/lib/page-path/absolute-path-to-page'
import Router from '../router' import Router from '../router'
...@@ -60,10 +62,7 @@ import { ...@@ -60,10 +62,7 @@ import {
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import isError, { getProperError } from '../../lib/is-error' import isError, { getProperError } from '../../lib/is-error'
import { import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
getMiddlewareRegex,
getRouteRegex,
} from '../../shared/lib/router/utils/route-regex'
import { getSortedRoutes, isDynamicRoute } from '../../shared/lib/router/utils' import { getSortedRoutes, isDynamicRoute } from '../../shared/lib/router/utils'
import { runDependingOnPageType } from '../../build/entries' import { runDependingOnPageType } from '../../build/entries'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node' import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
...@@ -106,7 +105,7 @@ export default class DevServer extends Server { ...@@ -106,7 +105,7 @@ export default class DevServer extends Server {
private pagesDir: string private pagesDir: string
private appDir?: string private appDir?: string
private actualMiddlewareFile?: string private actualMiddlewareFile?: string
private middleware?: RoutingItem private middleware?: MiddlewareRoutingItem
private edgeFunctions?: RoutingItem[] private edgeFunctions?: RoutingItem[]
private verifyingTypeScript?: boolean private verifyingTypeScript?: boolean
private usingTypeScript?: boolean private usingTypeScript?: boolean
...@@ -305,11 +304,12 @@ export default class DevServer extends Server { ...@@ -305,11 +304,12 @@ export default class DevServer extends Server {
let enabledTypeScript = this.usingTypeScript let enabledTypeScript = this.usingTypeScript
wp.on('aggregated', async () => { wp.on('aggregated', async () => {
let middlewareMatcher: RegExp | undefined let middlewareMatchers: MiddlewareMatcher[] | undefined
const routedPages: string[] = [] const routedPages: string[] = []
const knownFiles = wp.getTimeInfoEntries() const knownFiles = wp.getTimeInfoEntries()
const appPaths: Record<string, string> = {} const appPaths: Record<string, string> = {}
const edgeRoutesSet = new Set<string>() const edgeRoutesSet = new Set<string>()
let envChange = false let envChange = false
let tsconfigChange = false let tsconfigChange = false
...@@ -369,9 +369,9 @@ export default class DevServer extends Server { ...@@ -369,9 +369,9 @@ export default class DevServer extends Server {
if (isMiddlewareFile(rootFile)) { if (isMiddlewareFile(rootFile)) {
this.actualMiddlewareFile = rootFile this.actualMiddlewareFile = rootFile
middlewareMatcher = middlewareMatchers = staticInfo.middleware?.matchers || [
staticInfo.middleware?.pathMatcher || new RegExp('.*') { regexp: '.*' },
edgeRoutesSet.add('/') ]
continue continue
} }
...@@ -536,31 +536,29 @@ export default class DevServer extends Server { ...@@ -536,31 +536,29 @@ export default class DevServer extends Server {
} }
this.appPathRoutes = appPaths this.appPathRoutes = appPaths
this.edgeFunctions = []
const edgeRoutes = Array.from(edgeRoutesSet) const edgeRoutes = Array.from(edgeRoutesSet)
getSortedRoutes(edgeRoutes).forEach((page) => { this.edgeFunctions = getSortedRoutes(edgeRoutes).map((page) => {
let appPath = this.getOriginalAppPath(page) const appPath = this.getOriginalAppPath(page)
if (typeof appPath === 'string') { if (typeof appPath === 'string') {
page = appPath page = appPath
} }
const isRootMiddleware = page === '/' && !!middlewareMatcher const edgeRegex = getRouteRegex(page)
return {
const middlewareRegex = isRootMiddleware match: getRouteMatcher(edgeRegex),
? { re: middlewareMatcher!, groups: {} }
: getMiddlewareRegex(page, { catchAll: false })
const routeItem = {
match: getRouteMatcher(middlewareRegex),
page, page,
re: middlewareRegex.re, re: edgeRegex.re,
}
if (isRootMiddleware) {
this.middleware = routeItem
} else {
this.edgeFunctions!.push(routeItem)
} }
}) })
this.middleware = middlewareMatchers
? {
match: getMiddlewareRouteMatcher(middlewareMatchers),
page: '/',
matchers: middlewareMatchers,
}
: undefined
try { try {
// we serve a separate manifest with all pages for the client in // we serve a separate manifest with all pages for the client in
// dev mode so that we can match a page after a rewrite on the client // dev mode so that we can match a page after a rewrite on the client
...@@ -828,6 +826,7 @@ export default class DevServer extends Server { ...@@ -828,6 +826,7 @@ export default class DevServer extends Server {
response: BaseNextResponse response: BaseNextResponse
parsedUrl: ParsedUrl parsedUrl: ParsedUrl
parsed: UrlWithParsedQuery parsed: UrlWithParsedQuery
middlewareList: MiddlewareRoutingItem[]
}) { }) {
try { try {
const result = await super.runMiddleware({ const result = await super.runMiddleware({
...@@ -1158,17 +1157,7 @@ export default class DevServer extends Server { ...@@ -1158,17 +1157,7 @@ export default class DevServer extends Server {
fn: async (_req, res) => { fn: async (_req, res) => {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', 'application/json; charset=utf-8')
res res.body(JSON.stringify(this.getMiddleware()?.matchers ?? [])).send()
.body(
JSON.stringify(
this.middleware
? {
location: this.middleware.re!.source,
}
: {}
)
)
.send()
return { return {
finished: true, finished: true,
} }
......
...@@ -22,6 +22,7 @@ import type { ...@@ -22,6 +22,7 @@ import type {
Params, Params,
RouteMatch, RouteMatch,
} from '../shared/lib/router/utils/route-matcher' } from '../shared/lib/router/utils/route-matcher'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { NextConfig } from './config-shared' import type { NextConfig } from './config-shared'
import type { DynamicRoutes, PageChecker } from './router' import type { DynamicRoutes, PageChecker } from './router'
...@@ -71,6 +72,7 @@ import BaseServer, { ...@@ -71,6 +72,7 @@ import BaseServer, {
Options, Options,
FindComponentsResult, FindComponentsResult,
prepareServerlessUrl, prepareServerlessUrl,
MiddlewareRoutingItem,
RoutingItem, RoutingItem,
NoFallbackError, NoFallbackError,
RequestContext, RequestContext,
...@@ -86,6 +88,7 @@ import { relativizeURL } from '../shared/lib/router/utils/relativize-url' ...@@ -86,6 +88,7 @@ import { relativizeURL } from '../shared/lib/router/utils/relativize-url'
import { prepareDestination } from '../shared/lib/router/utils/prepare-destination' import { prepareDestination } from '../shared/lib/router/utils/prepare-destination'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { getCustomRoute, stringifyQuery } from './server-route-utils' import { getCustomRoute, stringifyQuery } from './server-route-utils'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring' import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
...@@ -123,28 +126,55 @@ export interface NodeRequestHandler { ...@@ -123,28 +126,55 @@ export interface NodeRequestHandler {
const MiddlewareMatcherCache = new WeakMap< const MiddlewareMatcherCache = new WeakMap<
MiddlewareManifest['middleware'][string], MiddlewareManifest['middleware'][string],
MiddlewareRouteMatch
>()
const EdgeMatcherCache = new WeakMap<
MiddlewareManifest['functions'][string],
RouteMatch RouteMatch
>() >()
function getMiddlewareMatcher( function getMiddlewareMatcher(
info: MiddlewareManifest['middleware'][string] info: MiddlewareManifest['middleware'][string]
): RouteMatch { ): MiddlewareRouteMatch {
const stored = MiddlewareMatcherCache.get(info) const stored = MiddlewareMatcherCache.get(info)
if (stored) { if (stored) {
return stored return stored
} }
if (typeof info.regexp !== 'string' || !info.regexp) { if (!Array.isArray(info.matchers)) {
throw new Error( throw new Error(
`Invariant: invalid regexp for middleware ${JSON.stringify(info)}` `Invariant: invalid matchers for middleware ${JSON.stringify(info)}`
) )
} }
const matcher = getRouteMatcher({ re: new RegExp(info.regexp), groups: {} }) const matcher = getMiddlewareRouteMatcher(info.matchers)
MiddlewareMatcherCache.set(info, matcher) MiddlewareMatcherCache.set(info, matcher)
return matcher return matcher
} }
function getEdgeMatcher(
info: MiddlewareManifest['functions'][string]
): RouteMatch {
const stored = EdgeMatcherCache.get(info)
if (stored) {
return stored
}
if (!Array.isArray(info.matchers) || info.matchers.length !== 1) {
throw new Error(
`Invariant: invalid matchers for middleware ${JSON.stringify(info)}`
)
}
const matcher = getRouteMatcher({
re: new RegExp(info.matchers[0].regexp),
groups: {},
})
EdgeMatcherCache.set(info, matcher)
return matcher
}
export default class NextNodeServer extends BaseServer { export default class NextNodeServer extends BaseServer {
private imageResponseCache?: ResponseCache private imageResponseCache?: ResponseCache
...@@ -1491,7 +1521,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1491,7 +1521,7 @@ export default class NextNodeServer extends BaseServer {
} }
/** Returns the middleware routing item if there is one. */ /** Returns the middleware routing item if there is one. */
protected getMiddleware(): RoutingItem | undefined { protected getMiddleware(): MiddlewareRoutingItem | undefined {
const manifest = this.getMiddlewareManifest() const manifest = this.getMiddlewareManifest()
const middleware = manifest?.middleware?.['/'] const middleware = manifest?.middleware?.['/']
if (!middleware) { if (!middleware) {
...@@ -1511,7 +1541,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1511,7 +1541,7 @@ export default class NextNodeServer extends BaseServer {
} }
return Object.keys(manifest.functions).map((page) => ({ return Object.keys(manifest.functions).map((page) => ({
match: getMiddlewareMatcher(manifest.functions[page]), match: getEdgeMatcher(manifest.functions[page]),
page, page,
})) }))
} }
...@@ -1637,10 +1667,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1637,10 +1667,6 @@ export default class NextNodeServer extends BaseServer {
} }
} }
const allHeaders = new Headers()
let result: FetchEventResult | null = null
const method = (params.request.method || 'GET').toUpperCase()
const middleware = this.getMiddleware() const middleware = this.getMiddleware()
if (!middleware) { if (!middleware) {
return { finished: false } return { finished: false }
...@@ -1649,52 +1675,54 @@ export default class NextNodeServer extends BaseServer { ...@@ -1649,52 +1675,54 @@ export default class NextNodeServer extends BaseServer {
return { finished: false } return { finished: false }
} }
if (middleware && middleware.match(normalizedPathname)) { await this.ensureMiddleware()
await this.ensureMiddleware() const middlewareInfo = this.getEdgeFunctionInfo({
const middlewareInfo = this.getEdgeFunctionInfo({ page: middleware.page,
page: middleware.page, middleware: true,
middleware: true, })
})
if (!middlewareInfo) { if (!middlewareInfo) {
throw new MiddlewareNotFoundError() throw new MiddlewareNotFoundError()
} }
result = await run({ const method = (params.request.method || 'GET').toUpperCase()
distDir: this.distDir,
name: middlewareInfo.name, const result = await run({
paths: middlewareInfo.paths, distDir: this.distDir,
env: middlewareInfo.env, name: middlewareInfo.name,
edgeFunctionEntry: middlewareInfo, paths: middlewareInfo.paths,
request: { env: middlewareInfo.env,
headers: params.request.headers, edgeFunctionEntry: middlewareInfo,
method, request: {
nextConfig: { headers: params.request.headers,
basePath: this.nextConfig.basePath, method,
i18n: this.nextConfig.i18n, nextConfig: {
trailingSlash: this.nextConfig.trailingSlash, basePath: this.nextConfig.basePath,
}, i18n: this.nextConfig.i18n,
url: url, trailingSlash: this.nextConfig.trailingSlash,
page: page,
body: getRequestMeta(params.request, '__NEXT_CLONABLE_BODY'),
}, },
useCache: !this.nextConfig.experimental.runtime, url: url,
onWarning: params.onWarning, page: page,
}) body: getRequestMeta(params.request, '__NEXT_CLONABLE_BODY'),
},
useCache: !this.nextConfig.experimental.runtime,
onWarning: params.onWarning,
})
for (let [key, value] of result.response.headers) { const allHeaders = new Headers()
if (key !== 'x-middleware-next') {
allHeaders.append(key, value)
}
}
if (!this.renderOpts.dev) { for (let [key, value] of result.response.headers) {
result.waitUntil.catch((error) => { if (key !== 'x-middleware-next') {
console.error(`Uncaught: middleware waitUntil errored`, error) allHeaders.append(key, value)
})
} }
} }
if (!this.renderOpts.dev) {
result.waitUntil.catch((error) => {
console.error(`Uncaught: middleware waitUntil errored`, error)
})
}
if (!result) { if (!result) {
this.render404(params.request, params.response, params.parsed) this.render404(params.request, params.response, params.parsed)
return { finished: true } return { finished: true }
...@@ -1734,7 +1762,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1734,7 +1762,7 @@ export default class NextNodeServer extends BaseServer {
const normalizedPathname = removeTrailingSlash( const normalizedPathname = removeTrailingSlash(
parsed.pathname || '' parsed.pathname || ''
) )
if (!middleware.match(normalizedPathname)) { if (!middleware.match(normalizedPathname, req, parsedUrl.query)) {
return { finished: false } return { finished: false }
} }
......
...@@ -91,21 +91,27 @@ interface MiddlewareEffectParams<T extends FetchDataOutput> { ...@@ -91,21 +91,27 @@ interface MiddlewareEffectParams<T extends FetchDataOutput> {
router: Router router: Router
} }
function matchesMiddleware<T extends FetchDataOutput>( export async function matchesMiddleware<T extends FetchDataOutput>(
options: MiddlewareEffectParams<T> options: MiddlewareEffectParams<T>
): Promise<boolean> { ): Promise<boolean> {
return Promise.resolve(options.router.pageLoader.getMiddleware()).then( const matchers = await Promise.resolve(
(middleware) => { options.router.pageLoader.getMiddleware()
const { pathname: asPathname } = parsePath(options.asPath) )
const cleanedAs = hasBasePath(asPathname) if (!matchers) return false
? removeBasePath(asPathname)
: asPathname const { pathname: asPathname } = parsePath(options.asPath)
// remove basePath first since path prefix has to be in the order of `/${basePath}/${locale}`
const regex = middleware?.location const cleanedAs = hasBasePath(asPathname)
return ( ? removeBasePath(asPathname)
!!regex && new RegExp(regex).test(addLocale(cleanedAs, options.locale)) : asPathname
) const asWithBasePathAndLocale = addBasePath(
} addLocale(cleanedAs, options.locale)
)
// Check only path match on client. Matching "has" should be done on server
// where we can access more info such as headers, HttpOnly cookie, etc.
return matchers.some((m) =>
new RegExp(m.regexp).test(asWithBasePathAndLocale)
) )
} }
......
import type { BaseNextRequest } from '../../../../server/base-http'
import type { MiddlewareMatcher } from '../../../../build/analysis/get-page-static-info'
import type { Params } from './route-matcher'
import { matchHas } from './prepare-destination'
export interface MiddlewareRouteMatch {
(
pathname: string | null | undefined,
request: BaseNextRequest,
query: Params
): boolean
}
export function getMiddlewareRouteMatcher(
matchers: MiddlewareMatcher[]
): MiddlewareRouteMatch {
return (
pathname: string | null | undefined,
req: BaseNextRequest,
query: Params
) => {
for (const matcher of matchers) {
const routeMatch = new RegExp(matcher.regexp).exec(pathname!)
if (!routeMatch) {
continue
}
if (matcher.has) {
const hasParams = matchHas(req, matcher.has, query)
if (!hasParams) {
continue
}
}
return true
}
return false
}
}
...@@ -144,36 +144,7 @@ export function getNamedRouteRegex(normalizedRoute: string) { ...@@ -144,36 +144,7 @@ export function getNamedRouteRegex(normalizedRoute: string) {
} }
/** /**
* From a middleware normalized route this function generates a regular * Generates a named regexp.
* expression for it. Temporarly we are using this to generate Edge Function
* routes too. In such cases the route should not include a trailing catch-all.
* For these cases the option `catchAll` should be set to false.
*/
export function getMiddlewareRegex(
normalizedRoute: string,
options?: {
catchAll?: boolean
}
): RouteRegex {
const { parameterizedRoute, groups } = getParametrizedRoute(normalizedRoute)
const { catchAll = true } = options ?? {}
if (parameterizedRoute === '/') {
let catchAllRegex = catchAll ? '.*' : ''
return {
groups: {},
re: new RegExp(`^/${catchAllRegex}$`),
}
}
let catchAllGroupedRegex = catchAll ? '(?:(/.*)?)' : ''
return {
groups: groups,
re: new RegExp(`^${parameterizedRoute}${catchAllGroupedRegex}$`),
}
}
/**
* A server version for getMiddlewareRegex that generates a named regexp.
* This is intended to be using for build time only. * This is intended to be using for build time only.
*/ */
export function getNamedMiddlewareRegex( export function getNamedMiddlewareRegex(
......
import { NextResponse } from 'next/server'
export default function middleware(request) {
const nextUrl = request.nextUrl.clone()
nextUrl.pathname = '/'
const res = NextResponse.rewrite(nextUrl)
res.headers.set('X-From-Middleware', 'true')
return res
}
export const config = {
matcher: [
{
source: '/hello',
},
],
}
export default (props) => (
<>
<h1>home</h1>
<div id="from-middleware">{props.fromMiddleware}</div>
</>
)
export async function getServerSideProps({ res }) {
return {
props: {
fromMiddleware: res.getHeader('x-from-middleware') || null,
},
}
}
import Link from 'next/link'
export default (props) => (
<ul>
<li>
<Link href="/hello">
<a id="hello">/hello</a>
</Link>
</li>
</ul>
)
/* eslint-env jest */
/* eslint-disable jest/no-standalone-expect */
import { join } from 'path'
import webdriver from 'next-webdriver'
import { fetchViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
const itif = (condition: boolean) => (condition ? it : it.skip)
const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy'
describe('Middleware custom matchers basePath', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(join(__dirname, '../app')),
})
})
afterAll(() => next.destroy())
// FIXME
// See https://linear.app/vercel/issue/EC-170/middleware-rewrite-of-nextjs-with-basepath-does-not-work-on-vercel
itif(!isModeDeploy)('should match', async () => {
for (const path of [
'/docs/hello',
`/docs/_next/data/${next.buildId}/hello.json`,
]) {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
}
})
it.each(['/hello', '/invalid/docs/hello'])(
'should not match',
async (path) => {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(404)
}
)
// FIXME:
// See https://linear.app/vercel/issue/EC-160/header-value-set-on-middleware-is-not-propagated-on-client-request-of
itif(!isModeDeploy)('should match has query on client routing', async () => {
const browser = await webdriver(next.url, '/docs/routes')
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementById('hello').click()
const fromMiddleware = await browser.elementById('from-middleware').text()
expect(fromMiddleware).toBe('true')
const noReload = await browser.eval('window.__TEST_NO_RELOAD')
expect(noReload).toBe(true)
})
})
import { NextResponse } from 'next/server'
export default function middleware(request) {
const nextUrl = request.nextUrl.clone()
nextUrl.pathname = '/'
const res = NextResponse.rewrite(nextUrl)
res.headers.set('X-From-Middleware', 'true')
return res
}
export const config = {
matcher: [
{
source: '/hello',
},
{
source: '/nl-NL/about',
locale: false,
},
],
}
module.exports = {
i18n: {
locales: ['en', 'nl-NL'],
defaultLocale: 'en',
},
}
export default (props) => (
<>
<h1>home</h1>
<div id="from-middleware">{props.fromMiddleware}</div>
</>
)
export async function getServerSideProps({ res }) {
return {
props: {
fromMiddleware: res.getHeader('x-from-middleware') || null,
},
}
}
import Link from 'next/link'
export default (props) => (
<ul>
<li>
<Link href="/hello">
<a id="hello">/hello</a>
</Link>
</li>
<li>
<Link href="/en/hello">
<a id="en_hello">/en/hello</a>
</Link>
</li>
<li>
<Link href="/nl-NL/hello">
<a id="nl-NL_hello">/nl-NL/hello</a>
</Link>
</li>
<li>
<Link href="/nl-NL/about">
<a id="nl-NL_about">/nl-NL/about</a>
</Link>
</li>
</ul>
)
/* eslint-env jest */
/* eslint-disable jest/no-standalone-expect */
import { join } from 'path'
import webdriver from 'next-webdriver'
import { fetchViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
const itif = (condition: boolean) => (condition ? it : it.skip)
const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy'
describe('Middleware custom matchers i18n', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(join(__dirname, '../app')),
})
})
afterAll(() => next.destroy())
it.each(['/hello', '/en/hello', '/nl-NL/hello', '/nl-NL/about'])(
'should match',
async (path) => {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
}
)
it.each(['/invalid/hello', '/hello/invalid', '/about', '/en/about'])(
'should not match',
async (path) => {
const res = await fetchViaHTTP(next.url, path)
expect(res.status).toBe(404)
}
)
// FIXME:
// See https://linear.app/vercel/issue/EC-160/header-value-set-on-middleware-is-not-propagated-on-client-request-of
itif(!isModeDeploy).each(['hello', 'en_hello', 'nl-NL_hello', 'nl-NL_about'])(
'should match has query on client routing',
async (id) => {
const browser = await webdriver(next.url, '/routes')
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementById(id).click()
const fromMiddleware = await browser.elementById('from-middleware').text()
expect(fromMiddleware).toBe('true')
const noReload = await browser.eval('window.__TEST_NO_RELOAD')
expect(noReload).toBe(true)
}
)
})
import { NextResponse } from 'next/server'
export default function middleware(request) {
const res = NextResponse.rewrite(new URL('/', request.url))
res.headers.set('X-From-Middleware', 'true')
return res
}
export const config = {
matcher: [
{ source: '/source-match' },
{
source: '/has-match-1',
has: [
{
type: 'header',
key: 'x-my-header',
value: '(?<myHeader>.*)',
},
],
},
{
source: '/has-match-2',
has: [
{
type: 'query',
key: 'my-query',
},
],
},
{
source: '/has-match-3',
has: [
{
type: 'cookie',
key: 'loggedIn',
value: '(?<loggedIn>true)',
},
],
},
{
source: '/has-match-4',
has: [
{
type: 'host',
value: 'example.com',
},
],
},
{
source: '/has-match-5',
has: [
{
type: 'header',
key: 'hasParam',
value: 'with-params',
},
],
},
],
}
export default (props) => (
<>
<h1>home</h1>
<div id="from-middleware">{props.fromMiddleware}</div>
</>
)
export async function getServerSideProps({ res }) {
return {
props: {
fromMiddleware: res.getHeader('x-from-middleware') || null,
},
}
}
import Link from 'next/link'
export default (props) => (
<ul>
<li>
<Link href="/has-match-2?my-query=hellooo">
<a id="has-match-2">has-match-2</a>
</Link>
</li>
<li>
<Link href="/has-match-3">
<a id="has-match-3">has-match-3</a>
</Link>
</li>
</ul>
)
/* eslint-env jest */
/* eslint-disable jest/no-standalone-expect */
import { join } from 'path'
import webdriver from 'next-webdriver'
import { fetchViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
const itif = (condition: boolean) => (condition ? it : it.skip)
const isModeDeploy = process.env.NEXT_TEST_MODE === 'deploy'
describe('Middleware custom matchers', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(join(__dirname, '../app')),
})
})
afterAll(() => next.destroy())
const runTests = () => {
it('should match source path', async () => {
const res = await fetchViaHTTP(next.url, '/source-match')
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
})
it('should match has header', async () => {
const res = await fetchViaHTTP(next.url, '/has-match-1', undefined, {
headers: {
'x-my-header': 'hello world!!',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
const res2 = await fetchViaHTTP(next.url, '/has-match-1')
expect(res2.status).toBe(404)
})
it('should match has query', async () => {
const res = await fetchViaHTTP(next.url, '/has-match-2', {
'my-query': 'hellooo',
})
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
const res2 = await fetchViaHTTP(next.url, '/has-match-2')
expect(res2.status).toBe(404)
})
it('should match has cookie', async () => {
const res = await fetchViaHTTP(next.url, '/has-match-3', undefined, {
headers: {
cookie: 'loggedIn=true',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
const res2 = await fetchViaHTTP(next.url, '/has-match-3', undefined, {
headers: {
cookie: 'loggedIn=false',
},
})
expect(res2.status).toBe(404)
})
// Cannot modify host when testing with real deployment
itif(!isModeDeploy)('should match has host', async () => {
const res1 = await fetchViaHTTP(next.url, '/has-match-4')
expect(res1.status).toBe(404)
const res = await fetchViaHTTP(next.url, '/has-match-4', undefined, {
headers: {
host: 'example.com',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
const res2 = await fetchViaHTTP(next.url, '/has-match-4', undefined, {
headers: {
host: 'example.org',
},
})
expect(res2.status).toBe(404)
})
it('should match has header value', async () => {
const res = await fetchViaHTTP(next.url, '/has-match-5', undefined, {
headers: {
hasParam: 'with-params',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBeDefined()
const res2 = await fetchViaHTTP(next.url, '/has-match-5', undefined, {
headers: {
hasParam: 'without-params',
},
})
expect(res2.status).toBe(404)
})
// FIXME: Test fails on Vercel deployment for now.
// See https://linear.app/vercel/issue/EC-160/header-value-set-on-middleware-is-not-propagated-on-client-request-of
itif(!isModeDeploy)(
'should match has query on client routing',
async () => {
const browser = await webdriver(next.url, '/routes')
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementById('has-match-2').click()
const fromMiddleware = await browser
.elementById('from-middleware')
.text()
expect(fromMiddleware).toBe('true')
const noReload = await browser.eval('window.__TEST_NO_RELOAD')
expect(noReload).toBe(true)
}
)
itif(!isModeDeploy)(
'should match has cookie on client routing',
async () => {
const browser = await webdriver(next.url, '/routes')
await browser.addCookie({ name: 'loggedIn', value: 'true' })
await browser.refresh()
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementById('has-match-3').click()
const fromMiddleware = await browser
.elementById('from-middleware')
.text()
expect(fromMiddleware).toBe('true')
const noReload = await browser.eval('window.__TEST_NO_RELOAD')
expect(noReload).toBe(true)
}
)
}
runTests()
})
...@@ -99,8 +99,8 @@ describe('Middleware Runtime', () => { ...@@ -99,8 +99,8 @@ describe('Middleware Runtime', () => {
next.url, next.url,
`/_next/static/${next.buildId}/_devMiddlewareManifest.json` `/_next/static/${next.buildId}/_devMiddlewareManifest.json`
) )
const { location } = await res.json() const matchers = await res.json()
expect(location).toBe('.*') expect(matchers).toEqual([{ regexp: '.*' }])
}) })
} }
...@@ -119,7 +119,7 @@ describe('Middleware Runtime', () => { ...@@ -119,7 +119,7 @@ describe('Middleware Runtime', () => {
files: ['server/edge-runtime-webpack.js', 'server/middleware.js'], files: ['server/edge-runtime-webpack.js', 'server/middleware.js'],
name: 'middleware', name: 'middleware',
page: '/', page: '/',
regexp: '^/.*$', matchers: [{ regexp: '^/.*$' }],
wasm: [], wasm: [],
assets: [], assets: [],
}, },
......
...@@ -94,20 +94,19 @@ describe('Middleware can set the matcher in its config', () => { ...@@ -94,20 +94,19 @@ describe('Middleware can set the matcher in its config', () => {
expect(response.headers.get('X-From-Middleware')).toBe('true') expect(response.headers.get('X-From-Middleware')).toBe('true')
}) })
it('should load matches in client manifest correctly', async () => { it('should load matches in client matchers correctly', async () => {
const browser = await webdriver(next.url, '/') const browser = await webdriver(next.url, '/')
await check(async () => { await check(async () => {
const manifest = await browser.eval( const matchers = await browser.eval(
(global as any).isNextDev (global as any).isNextDev
? 'window.__DEV_MIDDLEWARE_MANIFEST' ? 'window.__DEV_MIDDLEWARE_MATCHERS'
: 'window.__MIDDLEWARE_MANIFEST' : 'window.__MIDDLEWARE_MATCHERS'
) )
const { location } = manifest return matchers &&
return location && matchers.some((m) => m.regexp.includes('with-middleware')) &&
location.includes('with-middleware') && matchers.some((m) => m.regexp.includes('another-middleware'))
location.includes('another-middleware')
? 'success' ? 'success'
: 'failed' : 'failed'
}, 'success') }, 'success')
......
...@@ -59,7 +59,7 @@ describe('Middleware Runtime trailing slash', () => { ...@@ -59,7 +59,7 @@ describe('Middleware Runtime trailing slash', () => {
name: 'middleware', name: 'middleware',
env: [], env: [],
page: '/', page: '/',
regexp: '^/.*$', matchers: [{ regexp: '^/.*$' }],
wasm: [], wasm: [],
assets: [], assets: [],
}, },
......
...@@ -67,7 +67,7 @@ describe('Switchable runtime', () => { ...@@ -67,7 +67,7 @@ describe('Switchable runtime', () => {
`/_next/static/${next.buildId}/_devMiddlewareManifest.json` `/_next/static/${next.buildId}/_devMiddlewareManifest.json`
) )
const devMiddlewareManifest = await res.json() const devMiddlewareManifest = await res.json()
expect(devMiddlewareManifest).toEqual({}) expect(devMiddlewareManifest).toEqual([])
}) })
it('should sort edge SSR routes correctly', async () => { it('should sort edge SSR routes correctly', async () => {
...@@ -184,7 +184,7 @@ describe('Switchable runtime', () => { ...@@ -184,7 +184,7 @@ describe('Switchable runtime', () => {
], ],
name: 'pages/api/hello', name: 'pages/api/hello',
page: '/api/hello', page: '/api/hello',
regexp: '^/api/hello$', matchers: [{ regexp: '^/api/hello$' }],
wasm: [], wasm: [],
}, },
'/api/edge': { '/api/edge': {
...@@ -195,7 +195,7 @@ describe('Switchable runtime', () => { ...@@ -195,7 +195,7 @@ describe('Switchable runtime', () => {
], ],
name: 'pages/api/edge', name: 'pages/api/edge',
page: '/api/edge', page: '/api/edge',
regexp: '^/api/edge$', matchers: [{ regexp: '^/api/edge$' }],
wasm: [], wasm: [],
}, },
}, },
...@@ -328,7 +328,7 @@ describe('Switchable runtime', () => { ...@@ -328,7 +328,7 @@ describe('Switchable runtime', () => {
], ],
name: 'pages/api/hello', name: 'pages/api/hello',
page: '/api/hello', page: '/api/hello',
regexp: '^/api/hello$', matchers: [{ regexp: '^/api/hello$' }],
wasm: [], wasm: [],
}, },
'/api/edge': { '/api/edge': {
...@@ -339,7 +339,7 @@ describe('Switchable runtime', () => { ...@@ -339,7 +339,7 @@ describe('Switchable runtime', () => {
], ],
name: 'pages/api/edge', name: 'pages/api/edge',
page: '/api/edge', page: '/api/edge',
regexp: '^/api/edge$', matchers: [{ regexp: '^/api/edge$' }],
wasm: [], wasm: [],
}, },
}, },
......
...@@ -986,7 +986,7 @@ const runTests = (isDev = false) => { ...@@ -986,7 +986,7 @@ const runTests = (isDev = false) => {
host: '1', host: '1',
}) })
const res2 = await fetchViaHTTP(appPort, '/has-rewrite-3') const res2 = await fetchViaHTTP(appPort, '/has-rewrite-4')
expect(res2.status).toBe(404) expect(res2.status).toBe(404)
}) })
......
...@@ -143,10 +143,6 @@ const runTests = () => { ...@@ -143,10 +143,6 @@ const runTests = () => {
`\`destination\` is missing for route {"source":"/hello","permanent":false}` `\`destination\` is missing for route {"source":"/hello","permanent":false}`
) )
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello","permanent":false}`
)
expect(stderr).toContain( expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}` `\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
) )
...@@ -163,14 +159,6 @@ const runTests = () => { ...@@ -163,14 +159,6 @@ const runTests = () => {
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}` `\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
) )
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain( expect(stderr).toContain(
`\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}` `\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}`
) )
......
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import { fetchViaHTTP, findPort, launchApp, nextBuild } from 'next-test-utils'
let appDir = join(__dirname, '..')
const middlewarePath = join(appDir, 'middleware.js')
const writeMiddleware = async (matchers) => {
await fs.writeFile(
middlewarePath,
`
import { NextResponse } from 'next/server'
export default function middleware() {
return NextResponse.next()
}
export const config = {
matcher: ${JSON.stringify(matchers)},
}
`
)
}
let getStderr
const runTests = () => {
it('should error when source length is exceeded', async () => {
await writeMiddleware([{ source: `/${Array(4096).join('a')}` }])
const stderr = await getStderr()
expect(stderr).toContain(
'`source` exceeds max built length of 4096 for route {"source":"/aaaaaaaaaaaaaaaaaa'
)
})
it('should error during next build for invalid matchers', async () => {
await writeMiddleware([
{
// missing source
},
{
// invalid source
source: 123,
},
// missing forward slash in source
'hello',
{
// extra field
source: '/hello',
destination: '/not-allowed',
},
// invalid objects
null,
// invalid has items
{
source: '/hello',
has: [
{
type: 'cookiee',
key: 'loggedIn',
},
],
},
{
source: '/hello',
has: [
{
type: 'headerr',
},
{
type: 'queryr',
key: 'hello',
},
],
},
{
source: '/hello',
basePath: false,
},
{
source: '/hello',
locale: true,
},
])
const stderr = await getStderr()
expect(stderr).toContain(`\`source\` is missing for route {}`)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123}`
)
expect(stderr).toContain(
`\`source\` does not start with / for route {"source":"hello"}`
)
expect(stderr).toContain(
`invalid field: destination for route {"source":"/hello","destination":"/not-allowed"}`
)
expect(stderr).toContain(
`The route null is not a valid object with \`source\``
)
expect(stderr).toContain('Invalid `has` item:')
expect(stderr).toContain(
`invalid type "cookiee" for {"type":"cookiee","key":"loggedIn"}`
)
expect(stderr).toContain(
`invalid \`has\` item found for route {"source":"/hello","has":[{"type":"cookiee","key":"loggedIn"}]}`
)
expect(stderr).toContain('Invalid `has` items:')
expect(stderr).toContain(
`invalid type "headerr", invalid key "undefined" for {"type":"headerr"}`
)
expect(stderr).toContain(
`invalid type "queryr" for {"type":"queryr","key":"hello"}`
)
expect(stderr).toContain(
`invalid \`has\` items found for route {"source":"/hello","has":[{"type":"headerr"},{"type":"queryr","key":"hello"}]}`
)
expect(stderr).toContain(`Valid \`has\` object shape is {`)
expect(stderr).toContain(
`invalid field: basePath for route {"source":"/hello","basePath":false}`
)
expect(stderr).toContain(
'`locale` must be undefined or false for route {"source":"/hello","locale":true}'
)
})
}
describe('Errors on invalid custom middleware matchers', () => {
afterAll(() => fs.remove(middlewarePath))
describe('dev mode', () => {
beforeAll(() => {
getStderr = async () => {
let stderr = ''
const port = await findPort()
await launchApp(appDir, port, {
onStderr(msg) {
stderr += msg
},
})
await fetchViaHTTP(port, '/')
// suppress error
.catch(() => {})
return stderr
}
})
runTests()
})
describe('production mode', () => {
beforeAll(() => {
getStderr = async () => {
const { stderr } = await nextBuild(appDir, [], { stderr: true })
return stderr
}
})
runTests()
})
})
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