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

Add handling fo beforeFiles, afterFiles, and fallback rewrites (#23407)

This adds support for returning an object from `rewrites` in `next.config.js` with `beforeFiles`, `afterFiles`, and `fallback` to allow specifying rewrites at different stages of routing. The existing support for returning an array for rewrites is still supported and behaves the same way. The documentation has been updated to include information on these new stages that can be rewritten and removes the outdated note of rewrites not being able to override pages. 



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added

## Feature

- [ ] 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
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.

## Documentation / Examples

- [ ] Make sure the linting passes
parent dee70f02
...@@ -43,6 +43,11 @@ module.exports = { ...@@ -43,6 +43,11 @@ module.exports = {
- `source` is the incoming request path pattern. - `source` is the incoming request path pattern.
- `headers` is an array of header objects with the `key` and `value` properties. - `headers` is an array of header objects with the `key` and `value` properties.
- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
Headers are checked before the filesystem which includes pages and `/public` files.
## Header Overriding Behavior ## Header Overriding Behavior
......
...@@ -38,6 +38,11 @@ module.exports = { ...@@ -38,6 +38,11 @@ module.exports = {
- `source` is the incoming request path pattern. - `source` is the incoming request path pattern.
- `destination` is the path you want to route to. - `destination` is the path you want to route to.
- `permanent` if the redirect is permanent or not. - `permanent` if the redirect is permanent or not.
- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
Redirects are checked before the filesystem which includes pages and `/public` files.
## Path Matching ## Path Matching
......
...@@ -17,8 +17,6 @@ Rewrites allow you to map an incoming request path to a different destination pa ...@@ -17,8 +17,6 @@ Rewrites allow you to map an incoming request path to a different destination pa
Rewrites are only available on the Node.js environment and do not affect client-side routing. Rewrites are only available on the Node.js environment and do not affect client-side routing.
Rewrites are not able to override public files or routes in the pages directory as these have higher priority than rewrites. For example, if you have `pages/index.js` you are not able to rewrite `/` to another location unless you rename the `pages/index.js` file.
To use rewrites you can use the `rewrites` key in `next.config.js`: To use rewrites you can use the `rewrites` key in `next.config.js`:
```js ```js
...@@ -36,8 +34,48 @@ module.exports = { ...@@ -36,8 +34,48 @@ module.exports = {
`rewrites` is an async function that expects an array to be returned holding objects with `source` and `destination` properties: `rewrites` is an async function that expects an array to be returned holding objects with `source` and `destination` properties:
- `source` is the incoming request path pattern. - `source`: `String` - is the incoming request path pattern.
- `destination` is the path you want to route to. - `destination`: `String` is the path you want to route to.
- `basePath`: `false` or `undefined` - if false the basePath won't be included when matching, can be used for external rewrites only.
- `locale`: `false` or `undefined` - whether the locale should not be included when matching.
- `has` is an array of [has objects](#header-cookie-and-query-matching) with the `type`, `key` and `value` properties.
Rewrites are applied after checking the filesystem (pages and `/public` files) and before dynamic routes by default. This behavior can be changed by instead returning an object instead of an array from the `rewrites` function:
```js
module.exports = {
async rewrites() {
return {
beforeFiles: [
// These rewrites are checked after headers/redirects
// and before pages/public files which allows overriding
// page files
{
source: '/some-page',
destination: '/somewhere-else',
has: [{ type: 'query', key: 'overrideMe' }],
},
],
afterFiles: [
// These rewrites are checked after pages/public files
// are checked but before dynamic routes
{
source: '/non-existent',
destination: '/somewhere-else',
},
],
fallback: [
// These rewrites are checked after both pages/public files
// and dynamic routes are checked
{
source: '/:path*',
destination: 'https://my-old-site.com',
},
],
}
},
}
```
## Rewrite parameters ## Rewrite parameters
......
...@@ -17,9 +17,11 @@ import { ...@@ -17,9 +17,11 @@ import {
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, { import loadCustomRoutes, {
CustomRoutes,
getRedirectStatus, getRedirectStatus,
normalizeRouteRegex, normalizeRouteRegex,
Redirect, Redirect,
Rewrite,
RouteType, RouteType,
} from '../lib/load-custom-routes' } from '../lib/load-custom-routes'
import { nonNullable } from '../lib/non-nullable' import { nonNullable } from '../lib/non-nullable'
...@@ -51,6 +53,7 @@ import { ...@@ -51,6 +53,7 @@ import {
import { __ApiPreviewProps } from '../next-server/server/api-utils' import { __ApiPreviewProps } from '../next-server/server/api-utils'
import loadConfig, { import loadConfig, {
isTargetLikeServerless, isTargetLikeServerless,
NextConfig,
} from '../next-server/server/config' } from '../next-server/server/config'
import { BuildManifest } from '../next-server/server/get-page-files' import { BuildManifest } from '../next-server/server/get-page-files'
import '../next-server/server/node-polyfill-fetch' import '../next-server/server/node-polyfill-fetch'
...@@ -125,19 +128,21 @@ export default async function build( ...@@ -125,19 +128,21 @@ export default async function build(
.traceChild('load-dotenv') .traceChild('load-dotenv')
.traceFn(() => loadEnvConfig(dir, false, Log)) .traceFn(() => loadEnvConfig(dir, false, Log))
const config = await nextBuildSpan const config: NextConfig = await nextBuildSpan
.traceChild('load-next-config') .traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)) .traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf))
const { target } = config const { target } = config
const buildId = await nextBuildSpan const buildId: string = await nextBuildSpan
.traceChild('generate-buildid') .traceChild('generate-buildid')
.traceAsyncFn(() => generateBuildId(config.generateBuildId, nanoid)) .traceAsyncFn(() => generateBuildId(config.generateBuildId, nanoid))
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
const { headers, rewrites, redirects } = await nextBuildSpan const customRoutes: CustomRoutes = await nextBuildSpan
.traceChild('load-custom-routes') .traceChild('load-custom-routes')
.traceAsyncFn(() => loadCustomRoutes(config)) .traceAsyncFn(() => loadCustomRoutes(config))
const { headers, rewrites, redirects } = customRoutes
if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) { if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
const cacheDir = path.join(distDir, 'cache') const cacheDir = path.join(distDir, 'cache')
const hasCache = await fileExists(cacheDir) const hasCache = await fileExists(cacheDir)
...@@ -354,7 +359,13 @@ export default async function build( ...@@ -354,7 +359,13 @@ export default async function build(
pages404: boolean pages404: boolean
basePath: string basePath: string
redirects: Array<ReturnType<typeof buildCustomRoute>> redirects: Array<ReturnType<typeof buildCustomRoute>>
rewrites: Array<ReturnType<typeof buildCustomRoute>> rewrites:
| Array<ReturnType<typeof buildCustomRoute>>
| {
beforeFiles: Array<ReturnType<typeof buildCustomRoute>>
afterFiles: Array<ReturnType<typeof buildCustomRoute>>
fallback: Array<ReturnType<typeof buildCustomRoute>>
}
headers: Array<ReturnType<typeof buildCustomRoute>> headers: Array<ReturnType<typeof buildCustomRoute>>
dynamicRoutes: Array<{ dynamicRoutes: Array<{
page: string page: string
...@@ -384,7 +395,6 @@ export default async function build( ...@@ -384,7 +395,6 @@ export default async function build(
pages404: true, pages404: true,
basePath: config.basePath, basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')), redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
rewrites: rewrites.map((r: any) => buildCustomRoute(r, 'rewrite')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')), headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes: getSortedRoutes(pageKeys) dynamicRoutes: getSortedRoutes(pageKeys)
.filter(isDynamicRoute) .filter(isDynamicRoute)
...@@ -401,6 +411,29 @@ export default async function build( ...@@ -401,6 +411,29 @@ export default async function build(
i18n: config.i18n || undefined, i18n: config.i18n || undefined,
})) }))
if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
routesManifest.rewrites = rewrites.afterFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
)
} else {
routesManifest.rewrites = {
beforeFiles: rewrites.beforeFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
),
afterFiles: rewrites.afterFiles.map((r: any) =>
buildCustomRoute(r, 'rewrite')
),
fallback: rewrites.fallback.map((r: any) =>
buildCustomRoute(r, 'rewrite')
),
}
}
const combinedRewrites: Rewrite[] = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
...rewrites.fallback,
]
const distDirCreated = await nextBuildSpan const distDirCreated = await nextBuildSpan
.traceChild('create-dist-dir') .traceChild('create-dist-dir')
.traceAsyncFn(async () => { .traceAsyncFn(async () => {
...@@ -1380,11 +1413,12 @@ export default async function build( ...@@ -1380,11 +1413,12 @@ export default async function build(
(staticPages.size + ssgPages.size + serverPropsPages.size), (staticPages.size + ssgPages.size + serverPropsPages.size),
hasStatic404: useStatic404, hasStatic404: useStatic404,
hasReportWebVitals: namedExports?.includes('reportWebVitals') ?? false, hasReportWebVitals: namedExports?.includes('reportWebVitals') ?? false,
rewritesCount: rewrites.length, rewritesCount: combinedRewrites.length,
headersCount: headers.length, headersCount: headers.length,
redirectsCount: redirects.length - 1, // reduce one for trailing slash redirectsCount: redirects.length - 1, // reduce one for trailing slash
headersWithHasCount: headers.filter((r: any) => !!r.has).length, headersWithHasCount: headers.filter((r: any) => !!r.has).length,
rewritesWithHasCount: rewrites.filter((r: any) => !!r.has).length, rewritesWithHasCount: combinedRewrites.filter((r: any) => !!r.has)
.length,
redirectsWithHasCount: redirects.filter((r: any) => !!r.has).length, redirectsWithHasCount: redirects.filter((r: any) => !!r.has).length,
}) })
) )
......
...@@ -351,12 +351,18 @@ export function printCustomRoutes({ ...@@ -351,12 +351,18 @@ export function printCustomRoutes({
if (redirects.length) { if (redirects.length) {
printRoutes(redirects, 'Redirects') printRoutes(redirects, 'Redirects')
} }
if (rewrites.length) {
printRoutes(rewrites, 'Rewrites')
}
if (headers.length) { if (headers.length) {
printRoutes(headers, 'Headers') printRoutes(headers, 'Headers')
} }
const combinedRewrites = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
...rewrites.fallback,
]
if (combinedRewrites.length) {
printRoutes(combinedRewrites, 'Rewrites')
}
} }
type ComputeManifestShape = { type ComputeManifestShape = {
......
...@@ -16,7 +16,6 @@ import { ...@@ -16,7 +16,6 @@ import {
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version' import { getPackageVersion } from '../lib/get-package-version'
import { Rewrite } from '../lib/load-custom-routes'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import { import {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -61,6 +60,7 @@ import WebpackConformancePlugin, { ...@@ -61,6 +60,7 @@ import WebpackConformancePlugin, {
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin' import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { NextConfig } from '../next-server/server/config' import { NextConfig } from '../next-server/server/config'
import { relative as relativePath, join as pathJoin } from 'path' import { relative as relativePath, join as pathJoin } from 'path'
import { CustomRoutes } from '../lib/load-custom-routes.js'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -201,13 +201,16 @@ export default async function getBaseWebpackConfig( ...@@ -201,13 +201,16 @@ export default async function getBaseWebpackConfig(
target?: string target?: string
reactProductionProfiling?: boolean reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints entrypoints: WebpackEntrypoints
rewrites: Rewrite[] rewrites: CustomRoutes['rewrites']
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
let plugins: PluginMetaData[] = [] let plugins: PluginMetaData[] = []
let babelPresetPlugins: { dir: string; config: any }[] = [] let babelPresetPlugins: { dir: string; config: any }[] = []
const hasRewrites = rewrites.length > 0 const hasRewrites =
rewrites.beforeFiles.length > 0 ||
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0
if (config.experimental.plugins) { if (config.experimental.plugins) {
plugins = await collectPlugins(dir, config.env, config.plugins) plugins = await collectPlugins(dir, config.env, config.plugins)
......
...@@ -106,9 +106,19 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -106,9 +106,19 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler' import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const combinedRewrites = Array.isArray(routesManifest.rewrites)
? routesManifest.rewrites
: []
if (!Array.isArray(routesManifest.rewrites)) {
combinedRewrites.push(...routesManifest.rewrites.beforeFiles)
combinedRewrites.push(...routesManifest.rewrites.afterFiles)
combinedRewrites.push(...routesManifest.rewrites.fallback)
}
const apiHandler = getApiHandler({ const apiHandler = getApiHandler({
pageModule: require("${absolutePagePath}"), pageModule: require("${absolutePagePath}"),
rewrites: routesManifest.rewrites, rewrites: combinedRewrites,
i18n: ${i18n || 'undefined'}, i18n: ${i18n || 'undefined'},
page: "${page}", page: "${page}",
basePath: "${basePath}", basePath: "${basePath}",
...@@ -160,6 +170,16 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -160,6 +170,16 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {} export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App export const _app = App
const combinedRewrites = Array.isArray(routesManifest.rewrites)
? routesManifest.rewrites
: []
if (!Array.isArray(routesManifest.rewrites)) {
combinedRewrites.push(...routesManifest.rewrites.beforeFiles)
combinedRewrites.push(...routesManifest.rewrites.afterFiles)
combinedRewrites.push(...routesManifest.rewrites.fallback)
}
const { renderReqToHTML, render } = getPageHandler({ const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod, pageModule: compMod,
pageComponent: Component, pageComponent: Component,
...@@ -183,7 +203,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -183,7 +203,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
rewrites: routesManifest.rewrites, rewrites: combinedRewrites,
i18n: ${i18n || 'undefined'}, i18n: ${i18n || 'undefined'},
page: "${page}", page: "${page}",
buildId: "${buildId}", buildId: "${buildId}",
......
...@@ -18,6 +18,7 @@ import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin' ...@@ -18,6 +18,7 @@ import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes' import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../next-server/lib/router/utils' import { getSortedRoutes } from '../../../next-server/lib/router/utils'
import { spans } from './profiling-plugin' import { spans } from './profiling-plugin'
import { CustomRoutes } from '../../../lib/load-custom-routes'
type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> } type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }
...@@ -28,7 +29,7 @@ export type ClientBuildManifest = Record<string, string[]> ...@@ -28,7 +29,7 @@ export type ClientBuildManifest = Record<string, string[]>
function generateClientManifest( function generateClientManifest(
compiler: any, compiler: any,
assetMap: BuildManifest, assetMap: BuildManifest,
rewrites: Rewrite[] rewrites: CustomRoutes['rewrites']
): string { ): string {
const compilerSpan = spans.get(compiler) const compilerSpan = spans.get(compiler)
const genClientManifestSpan = compilerSpan?.traceChild( const genClientManifestSpan = compilerSpan?.traceChild(
...@@ -78,25 +79,37 @@ function getEntrypointFiles(entrypoint: any): string[] { ...@@ -78,25 +79,37 @@ function getEntrypointFiles(entrypoint: any): string[] {
) )
} }
const processRoute = (r: Rewrite) => {
const rewrite = { ...r }
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite.destination.startsWith('/')) {
delete (rewrite as any).destination
}
return rewrite
}
// This plugin creates a build-manifest.json for all assets that are being output // This plugin creates a build-manifest.json for all assets that are being output
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production // It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin { export default class BuildManifestPlugin {
private buildId: string private buildId: string
private rewrites: Rewrite[] private rewrites: CustomRoutes['rewrites']
constructor(options: { buildId: string; rewrites: Rewrite[] }) { constructor(options: {
buildId: string
rewrites: CustomRoutes['rewrites']
}) {
this.buildId = options.buildId this.buildId = options.buildId
this.rewrites = options.rewrites.map((r) => { this.rewrites = {
const rewrite = { ...r } beforeFiles: [],
afterFiles: [],
// omit external rewrite destinations since these aren't fallback: [],
// handled client-side }
if (!rewrite.destination.startsWith('/')) { this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute)
delete (rewrite as any).destination this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute)
} this.rewrites.fallback = options.rewrites.fallback.map(processRoute)
return rewrite
})
} }
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
......
...@@ -117,11 +117,9 @@ export default class PageLoader { ...@@ -117,11 +117,9 @@ export default class PageLoader {
} }
/** /**
* @param {string} href the route href (file-system path) * @param {string} route - the route (file-system path)
*/ */
_isSsg(href: string): Promise<boolean> { _isSsg(route: string): Promise<boolean> {
const { pathname: hrefPathname } = parseRelativeUrl(href)
const route = normalizeRoute(hrefPathname)
return this.promisedSsgManifest!.then((s: ClientSsgManifest) => return this.promisedSsgManifest!.then((s: ClientSsgManifest) =>
s.has(route) s.has(route)
) )
......
...@@ -191,7 +191,7 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> { ...@@ -191,7 +191,7 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
// Mandatory because this is not concurrent safe: // Mandatory because this is not concurrent safe:
const cb = self.__BUILD_MANIFEST_CB const cb = self.__BUILD_MANIFEST_CB
self.__BUILD_MANIFEST_CB = () => { self.__BUILD_MANIFEST_CB = () => {
resolve(self.__BUILD_MANIFEST) resolve(self.__BUILD_MANIFEST!)
cb && cb() cb && cb()
} }
}) })
......
...@@ -38,7 +38,12 @@ export type Header = { ...@@ -38,7 +38,12 @@ export type Header = {
} }
// internal type used for validation (not user facing) // internal type used for validation (not user facing)
export type Redirect = Rewrite & { export type Redirect = {
source: string
destination: string
basePath?: false
locale?: false
has?: RouteHas[]
statusCode?: number statusCode?: number
permanent?: boolean permanent?: boolean
} }
...@@ -175,20 +180,18 @@ function checkCustomRoutes( ...@@ -175,20 +180,18 @@ function checkCustomRoutes(
let hadInvalidStatus = false let hadInvalidStatus = false
let hadInvalidHas = false let hadInvalidHas = false
const isRedirect = type === 'redirect' const allowedKeys = new Set<string>(['source', 'basePath', 'locale', 'has'])
let allowedKeys: Set<string>
if (type === 'rewrite') {
if (type === 'rewrite' || isRedirect) { allowedKeys.add('destination')
allowedKeys = new Set([ }
'source', if (type === 'redirect') {
'destination', allowedKeys.add('statusCode')
'basePath', allowedKeys.add('permanent')
'locale', allowedKeys.add('destination')
...(isRedirect ? ['statusCode', 'permanent'] : []), }
'has', if (type === 'header') {
]) allowedKeys.add('headers')
} else {
allowedKeys = new Set(['source', 'headers', 'basePath', 'locale', 'has'])
} }
for (const route of routes) { for (const route of routes) {
...@@ -431,7 +434,11 @@ function checkCustomRoutes( ...@@ -431,7 +434,11 @@ function checkCustomRoutes(
export interface CustomRoutes { export interface CustomRoutes {
headers: Header[] headers: Header[]
rewrites: Rewrite[] rewrites: {
fallback: Rewrite[]
afterFiles: Rewrite[]
beforeFiles: Rewrite[]
}
redirects: Redirect[] redirects: Redirect[]
} }
...@@ -522,11 +529,41 @@ async function loadRedirects(config: NextConfig) { ...@@ -522,11 +529,41 @@ async function loadRedirects(config: NextConfig) {
async function loadRewrites(config: NextConfig) { async function loadRewrites(config: NextConfig) {
if (typeof config.rewrites !== 'function') { if (typeof config.rewrites !== 'function') {
return [] return {
beforeFiles: [],
afterFiles: [],
fallback: [],
}
}
const _rewrites = await config.rewrites()
let beforeFiles: Rewrite[] = []
let afterFiles: Rewrite[] = []
let fallback: Rewrite[] = []
if (
!Array.isArray(_rewrites) &&
typeof _rewrites === 'object' &&
Object.keys(_rewrites).every(
(key) =>
key === 'beforeFiles' || key === 'afterFiles' || key === 'fallback'
)
) {
beforeFiles = _rewrites.beforeFiles || []
afterFiles = _rewrites.afterFiles || []
fallback = _rewrites.fallback || []
} else {
afterFiles = _rewrites as any
}
checkCustomRoutes(beforeFiles, 'rewrite')
checkCustomRoutes(afterFiles, 'rewrite')
checkCustomRoutes(fallback, 'rewrite')
return {
beforeFiles: processRoutes(beforeFiles, config, 'rewrite'),
afterFiles: processRoutes(afterFiles, config, 'rewrite'),
fallback: processRoutes(fallback, config, 'rewrite'),
} }
let rewrites = await config.rewrites()
checkCustomRoutes(rewrites, 'rewrite')
return processRoutes(rewrites, config, 'rewrite')
} }
async function loadHeaders(config: NextConfig) { async function loadHeaders(config: NextConfig) {
......
...@@ -338,18 +338,11 @@ function prepareUrlAs(router: NextRouter, url: Url, as?: Url) { ...@@ -338,18 +338,11 @@ function prepareUrlAs(router: NextRouter, url: Url, as?: Url) {
} }
} }
function resolveDynamicRoute( function resolveDynamicRoute(pathname: string, pages: string[]) {
parsedHref: UrlObject, const cleanPathname = removePathTrailingSlash(denormalizePagePath(pathname!))
pages: string[],
applyBasePath = true
) {
const { pathname } = parsedHref
const cleanPathname = removePathTrailingSlash(
denormalizePagePath(applyBasePath ? delBasePath(pathname!) : pathname!)
)
if (cleanPathname === '/404' || cleanPathname === '/_error') { if (cleanPathname === '/404' || cleanPathname === '/_error') {
return parsedHref return pathname
} }
// handle resolving href for dynamic routes // handle resolving href for dynamic routes
...@@ -357,13 +350,12 @@ function resolveDynamicRoute( ...@@ -357,13 +350,12 @@ function resolveDynamicRoute(
// eslint-disable-next-line array-callback-return // eslint-disable-next-line array-callback-return
pages.some((page) => { pages.some((page) => {
if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname!)) { if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname!)) {
parsedHref.pathname = applyBasePath ? addBasePath(page) : page pathname = page
return true return true
} }
}) })
} }
parsedHref.pathname = removePathTrailingSlash(parsedHref.pathname!) return removePathTrailingSlash(pathname)
return parsedHref
} }
export type BaseRouter = { export type BaseRouter = {
...@@ -946,20 +938,6 @@ export default class Router implements BaseRouter { ...@@ -946,20 +938,6 @@ export default class Router implements BaseRouter {
return false return false
} }
parsed = resolveDynamicRoute(parsed, pages) as typeof parsed
if (parsed.pathname !== pathname) {
pathname = parsed.pathname
url = formatWithValidation(parsed)
}
// url and as should always be prefixed with basePath by this
// point by either next/link or router.push/replace so strip the
// basePath from the pathname to match the pages dir 1-to-1
pathname = pathname
? removePathTrailingSlash(delBasePath(pathname))
: pathname
// If asked to change the current URL we should reload the current page // If asked to change the current URL we should reload the current page
// (not location.reload() but reload getInitialProps and other Next.js stuffs) // (not location.reload() but reload getInitialProps and other Next.js stuffs)
// We also need to set the method = replaceState always // We also need to set the method = replaceState always
...@@ -969,33 +947,48 @@ export default class Router implements BaseRouter { ...@@ -969,33 +947,48 @@ export default class Router implements BaseRouter {
method = 'replaceState' method = 'replaceState'
} }
let route = removePathTrailingSlash(pathname)
// we need to resolve the as value using rewrites for dynamic SSG // we need to resolve the as value using rewrites for dynamic SSG
// pages to allow building the data URL correctly // pages to allow building the data URL correctly
let resolvedAs = as let resolvedAs = as
if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) { // url and as should always be prefixed with basePath by this
const rewritesResult = resolveRewrites( // point by either next/link or router.push/replace so strip the
addBasePath(addLocale(delBasePath(as), this.locale)), // basePath from the pathname to match the pages dir 1-to-1
pages, pathname = pathname
rewrites, ? removePathTrailingSlash(delBasePath(pathname))
query, : pathname
(p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!,
this.locales
)
resolvedAs = rewritesResult.asPath
if (rewritesResult.matchedPage && rewritesResult.resolvedHref) { if (pathname !== '/_error') {
// if this directly matches a page we need to update the href to if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
// allow the correct page chunk to be loaded const rewritesResult = resolveRewrites(
route = rewritesResult.resolvedHref addBasePath(addLocale(delBasePath(as), this.locale)),
pathname = rewritesResult.resolvedHref pages,
parsed.pathname = pathname rewrites,
url = formatWithValidation(parsed) query,
(p: string) => resolveDynamicRoute(p, pages),
this.locales
)
resolvedAs = rewritesResult.asPath
if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
// if this directly matches a page we need to update the href to
// allow the correct page chunk to be loaded
pathname = rewritesResult.resolvedHref
parsed.pathname = pathname
url = formatWithValidation(parsed)
}
} else {
parsed.pathname = resolveDynamicRoute(pathname, pages)
if (parsed.pathname !== pathname) {
pathname = parsed.pathname
url = formatWithValidation(parsed)
}
} }
} }
const route = removePathTrailingSlash(pathname)
if (!isLocalURL(as)) { if (!isLocalURL(as)) {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
throw new Error( throw new Error(
...@@ -1089,7 +1082,10 @@ export default class Router implements BaseRouter { ...@@ -1089,7 +1082,10 @@ export default class Router implements BaseRouter {
// it's not // it's not
if (destination.startsWith('/')) { if (destination.startsWith('/')) {
const parsedHref = parseRelativeUrl(destination) const parsedHref = parseRelativeUrl(destination)
resolveDynamicRoute(parsedHref, pages, false) parsedHref.pathname = resolveDynamicRoute(
parsedHref.pathname,
pages
)
if (pages.includes(parsedHref.pathname)) { if (pages.includes(parsedHref.pathname)) {
const { url: newUrl, as: newAs } = prepareUrlAs( const { url: newUrl, as: newAs } = prepareUrlAs(
...@@ -1483,39 +1479,38 @@ export default class Router implements BaseRouter { ...@@ -1483,39 +1479,38 @@ export default class Router implements BaseRouter {
} }
const pages = await this.pageLoader.getPageList() const pages = await this.pageLoader.getPageList()
parsed = resolveDynamicRoute(parsed, pages, false) as typeof parsed
if (parsed.pathname !== pathname) {
pathname = parsed.pathname
url = formatWithValidation(parsed)
}
let route = removePathTrailingSlash(pathname)
let resolvedAs = asPath let resolvedAs = asPath
if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) { if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {
let rewrites: any[] let rewrites: any
;({ __rewrites: rewrites } = await getClientBuildManifest()) ;({ __rewrites: rewrites } = await getClientBuildManifest())
const rewritesResult = resolveRewrites( const rewritesResult = resolveRewrites(
addBasePath(addLocale(delBasePath(asPath), this.locale)), addBasePath(addLocale(asPath, this.locale)),
pages, pages,
rewrites, rewrites,
parsed.query, parsed.query,
(p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!, (p: string) => resolveDynamicRoute(p, pages),
this.locales this.locales
) )
resolvedAs = delLocale(delBasePath(rewritesResult.asPath), this.locale)
if (rewritesResult.matchedPage && rewritesResult.resolvedHref) { if (rewritesResult.matchedPage && rewritesResult.resolvedHref) {
// if this directly matches a page we need to update the href to // if this directly matches a page we need to update the href to
// allow the correct page chunk to be loaded // allow the correct page chunk to be loaded
route = rewritesResult.resolvedHref
pathname = rewritesResult.resolvedHref pathname = rewritesResult.resolvedHref
parsed.pathname = pathname parsed.pathname = pathname
url = formatWithValidation(parsed) url = formatWithValidation(parsed)
resolvedAs = rewritesResult.asPath }
} else {
parsed.pathname = resolveDynamicRoute(parsed.pathname, pages)
if (parsed.pathname !== pathname) {
pathname = parsed.pathname
url = formatWithValidation(parsed)
} }
} }
const route = removePathTrailingSlash(pathname)
// Prefetch is not supported in development mode because it would trigger on-demand-entries // Prefetch is not supported in development mode because it would trigger on-demand-entries
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
...@@ -1523,7 +1518,7 @@ export default class Router implements BaseRouter { ...@@ -1523,7 +1518,7 @@ export default class Router implements BaseRouter {
} }
await Promise.all([ await Promise.all([
this.pageLoader._isSsg(url).then((isSsg: boolean) => { this.pageLoader._isSsg(route).then((isSsg: boolean) => {
return isSsg return isSsg
? this._getStaticData( ? this._getStaticData(
this.pageLoader.getDataHref( this.pageLoader.getDataHref(
......
...@@ -12,7 +12,11 @@ const customRouteMatcher = pathMatch(true) ...@@ -12,7 +12,11 @@ const customRouteMatcher = pathMatch(true)
export default function resolveRewrites( export default function resolveRewrites(
asPath: string, asPath: string,
pages: string[], pages: string[],
rewrites: Rewrite[], rewrites: {
beforeFiles: Rewrite[]
afterFiles: Rewrite[]
fallback: Rewrite[]
},
query: ParsedUrlQuery, query: ParsedUrlQuery,
resolveHref: (path: string) => string, resolveHref: (path: string) => string,
locales?: string[] locales?: string[]
...@@ -29,72 +33,110 @@ export default function resolveRewrites( ...@@ -29,72 +33,110 @@ export default function resolveRewrites(
) )
let resolvedHref let resolvedHref
if (!pages.includes(fsPathname)) { const handleRewrite = (rewrite: Rewrite) => {
for (const rewrite of rewrites) { const matcher = customRouteMatcher(rewrite.source)
const matcher = customRouteMatcher(rewrite.source) let params = matcher(parsedAs.pathname)
let params = matcher(parsedAs.pathname)
if (rewrite.has && params) {
if (rewrite.has && params) { const hasParams = matchHas(
const hasParams = matchHas( {
{ headers: {
headers: { host: document.location.hostname,
host: document.location.hostname, },
}, cookies: Object.fromEntries(
cookies: Object.fromEntries( document.cookie.split('; ').map((item) => {
document.cookie.split('; ').map((item) => { const [key, ...value] = item.split('=')
const [key, ...value] = item.split('=') return [key, value.join('=')]
return [key, value.join('=')] })
}) ),
), } as any,
} as any, rewrite.has,
rewrite.has, parsedAs.query
parsedAs.query )
)
if (hasParams) {
if (hasParams) { Object.assign(params, hasParams)
Object.assign(params, hasParams) } else {
} else { params = false
params = false
}
} }
}
if (params) { if (params) {
if (!rewrite.destination) { if (!rewrite.destination) {
// this is a proxied rewrite which isn't handled on the client // this is a proxied rewrite which isn't handled on the client
break return true
} }
const destRes = prepareDestination( const destRes = prepareDestination(
rewrite.destination, rewrite.destination,
params, params,
query, query,
true true
) )
parsedAs = destRes.parsedDestination parsedAs = destRes.parsedDestination
asPath = destRes.newUrl asPath = destRes.newUrl
Object.assign(query, destRes.parsedDestination.query) Object.assign(query, destRes.parsedDestination.query)
fsPathname = removePathTrailingSlash( fsPathname = removePathTrailingSlash(
normalizeLocalePath(delBasePath(asPath), locales).pathname normalizeLocalePath(delBasePath(asPath), locales).pathname
) )
if (pages.includes(fsPathname)) { if (pages.includes(fsPathname)) {
// check if we now match a page as this means we are done // check if we now match a page as this means we are done
// resolving the rewrites // resolving the rewrites
matchedPage = true matchedPage = true
resolvedHref = fsPathname resolvedHref = fsPathname
return true
}
// check if we match a dynamic-route, if so we break the rewrites chain
resolvedHref = resolveHref(fsPathname)
if (resolvedHref !== asPath && pages.includes(resolvedHref)) {
matchedPage = true
return true
}
}
}
let finished = false
for (let i = 0; i < rewrites.beforeFiles.length; i++) {
const rewrite = rewrites.beforeFiles[i]
if (handleRewrite(rewrite)) {
finished = true
break
}
}
if (!pages.includes(fsPathname)) {
if (!finished) {
for (let i = 0; i < rewrites.afterFiles.length; i++) {
const rewrite = rewrites.afterFiles[i]
if (handleRewrite(rewrite)) {
finished = true
break break
} }
}
}
// check if we match a dynamic-route, if so we break the rewrites chain // check dynamic route before processing fallback rewrites
resolvedHref = resolveHref(fsPathname) if (!finished) {
resolvedHref = resolveHref(fsPathname)
matchedPage = pages.includes(resolvedHref)
finished = matchedPage
}
if (resolvedHref !== asPath && pages.includes(resolvedHref)) { if (!finished) {
matchedPage = true for (let i = 0; i < rewrites.fallback.length; i++) {
const rewrite = rewrites.fallback[i]
if (handleRewrite(rewrite)) {
finished = true
break break
} }
} }
} }
} }
return { return {
asPath, asPath,
parsedAs, parsedAs,
......
...@@ -18,15 +18,47 @@ export type NextConfig = { [key: string]: any } & { ...@@ -18,15 +18,47 @@ export type NextConfig = { [key: string]: any } & {
} | null } | null
headers?: () => Promise<Header[]> headers?: () => Promise<Header[]>
rewrites?: () => Promise<Rewrite[]> rewrites?: () => Promise<
| Rewrite[]
| {
beforeFiles: Rewrite[]
afterFiles: Rewrite[]
fallback: Rewrite[]
}
>
redirects?: () => Promise<Redirect[]> redirects?: () => Promise<Redirect[]>
trailingSlash?: boolean trailingSlash?: boolean
future: { future: {
strictPostcssConfiguration: boolean strictPostcssConfiguration?: boolean
excludeDefaultMomentLocales: boolean excludeDefaultMomentLocales?: boolean
webpack5: boolean webpack5?: boolean
}
experimental: {
cpus?: number
plugins?: boolean
profiling?: boolean
sprFlushToDisk?: boolean
reactMode?: 'legacy' | 'concurrent' | 'blocking'
workerThreads?: boolean
pageEnv?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean
optimizeCss?: boolean
scrollRestoration?: boolean
scriptLoader?: boolean
stats?: boolean
externalDir?: boolean
serialWebpackBuild?: boolean
babelMultiThread?: boolean
conformance?: boolean
amp?: {
optimizer?: any
validator?: string
skipValidation?: boolean
}
} }
} }
......
...@@ -205,12 +205,12 @@ export default class Server { ...@@ -205,12 +205,12 @@ export default class Server {
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
images: JSON.stringify(this.nextConfig.images), images: JSON.stringify(this.nextConfig.images),
optimizeFonts: this.nextConfig.experimental.optimizeFonts && !dev, optimizeFonts: !!this.nextConfig.experimental.optimizeFonts && !dev,
fontManifest: fontManifest:
this.nextConfig.experimental.optimizeFonts && !dev this.nextConfig.experimental.optimizeFonts && !dev
? requireFontManifest(this.distDir, this._isLikeServerless) ? requireFontManifest(this.distDir, this._isLikeServerless)
: null, : null,
optimizeImages: this.nextConfig.experimental.optimizeImages, optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss, optimizeCss: this.nextConfig.experimental.optimizeCss,
domainLocales: this.nextConfig.i18n?.domains, domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir, distDir: this.distDir,
...@@ -361,12 +361,18 @@ export default class Server { ...@@ -361,12 +361,18 @@ export default class Server {
} }
const pageIsDynamic = isDynamicRoute(matchedPathnameNoExt) const pageIsDynamic = isDynamicRoute(matchedPathnameNoExt)
const combinedRewrites: Rewrite[] = []
combinedRewrites.push(...this.customRoutes.rewrites.beforeFiles)
combinedRewrites.push(...this.customRoutes.rewrites.afterFiles)
combinedRewrites.push(...this.customRoutes.rewrites.fallback)
const utils = getUtils({ const utils = getUtils({
pageIsDynamic, pageIsDynamic,
page: matchedPathnameNoExt, page: matchedPathnameNoExt,
i18n: this.nextConfig.i18n, i18n: this.nextConfig.i18n,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
rewrites: this.customRoutes.rewrites, rewrites: combinedRewrites,
}) })
utils.handleRewrites(req, parsedUrl) utils.handleRewrites(req, parsedUrl)
...@@ -594,7 +600,22 @@ export default class Server { ...@@ -594,7 +600,22 @@ export default class Server {
} }
protected getCustomRoutes(): CustomRoutes { protected getCustomRoutes(): CustomRoutes {
return require(join(this.distDir, ROUTES_MANIFEST)) const customRoutes = require(join(this.distDir, ROUTES_MANIFEST))
let rewrites: CustomRoutes['rewrites']
// rewrites can be stored as an array when an array is
// returned in next.config.js so massage them into
// the expected object format
if (Array.isArray(customRoutes.rewrites)) {
rewrites = {
beforeFiles: [],
afterFiles: customRoutes.rewrites,
fallback: [],
}
} else {
rewrites = customRoutes.rewrites
}
return Object.assign(customRoutes, { rewrites })
} }
private _cachedPreviewManifest: PrerenderManifest | undefined private _cachedPreviewManifest: PrerenderManifest | undefined
...@@ -613,7 +634,11 @@ export default class Server { ...@@ -613,7 +634,11 @@ export default class Server {
protected generateRoutes(): { protected generateRoutes(): {
basePath: string basePath: string
headers: Route[] headers: Route[]
rewrites: Route[] rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
fsRoutes: Route[] fsRoutes: Route[]
redirects: Route[] redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
...@@ -875,7 +900,7 @@ export default class Server { ...@@ -875,7 +900,7 @@ export default class Server {
} as Route } as Route
}) })
const rewrites = this.customRoutes.rewrites.map((rewrite) => { const buildRewrite = (rewrite: Rewrite) => {
const rewriteRoute = getCustomRoute(rewrite, 'rewrite') const rewriteRoute = getCustomRoute(rewrite, 'rewrite')
return { return {
...rewriteRoute, ...rewriteRoute,
...@@ -923,7 +948,19 @@ export default class Server { ...@@ -923,7 +948,19 @@ export default class Server {
} }
}, },
} as Route } as Route
}) }
let beforeFiles: Route[] = []
let afterFiles: Route[] = []
let fallback: Route[] = []
if (Array.isArray(this.customRoutes.rewrites)) {
afterFiles = this.customRoutes.rewrites.map(buildRewrite)
} else {
beforeFiles = this.customRoutes.rewrites.beforeFiles.map(buildRewrite)
afterFiles = this.customRoutes.rewrites.afterFiles.map(buildRewrite)
fallback = this.customRoutes.rewrites.fallback.map(buildRewrite)
}
const catchAllRoute: Route = { const catchAllRoute: Route = {
match: route('/:path*'), match: route('/:path*'),
...@@ -978,7 +1015,11 @@ export default class Server { ...@@ -978,7 +1015,11 @@ export default class Server {
return { return {
headers, headers,
fsRoutes, fsRoutes,
rewrites, rewrites: {
beforeFiles,
afterFiles,
fallback,
},
redirects, redirects,
catchAllRoute, catchAllRoute,
useFileSystemPublicRoutes, useFileSystemPublicRoutes,
......
...@@ -51,8 +51,12 @@ export default class Router { ...@@ -51,8 +51,12 @@ export default class Router {
basePath: string basePath: string
headers: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
rewrites: Route[]
redirects: Route[] redirects: Route[]
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
catchAllRoute: Route catchAllRoute: Route
pageChecker: PageChecker pageChecker: PageChecker
dynamicRoutes: DynamicRoutes dynamicRoutes: DynamicRoutes
...@@ -63,7 +67,11 @@ export default class Router { ...@@ -63,7 +67,11 @@ export default class Router {
basePath = '', basePath = '',
headers = [], headers = [],
fsRoutes = [], fsRoutes = [],
rewrites = [], rewrites = {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
redirects = [], redirects = [],
catchAllRoute, catchAllRoute,
dynamicRoutes = [], dynamicRoutes = [],
...@@ -74,7 +82,11 @@ export default class Router { ...@@ -74,7 +82,11 @@ export default class Router {
basePath: string basePath: string
headers: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
rewrites: Route[] rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
redirects: Route[] redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
...@@ -122,6 +134,53 @@ export default class Router { ...@@ -122,6 +134,53 @@ export default class Router {
let parsedUrlUpdated = parsedUrl let parsedUrlUpdated = parsedUrl
const applyCheckTrue = async (checkParsedUrl: UrlWithParsedQuery) => {
const originalFsPathname = checkParsedUrl.pathname
const fsPathname = replaceBasePath(this.basePath, originalFsPathname!)
for (const fsRoute of this.fsRoutes) {
const fsParams = fsRoute.match(fsPathname)
if (fsParams) {
checkParsedUrl.pathname = fsPathname
const fsResult = await fsRoute.fn(req, res, fsParams, checkParsedUrl)
if (fsResult.finished) {
return true
}
checkParsedUrl.pathname = originalFsPathname
}
}
let matchedPage = await memoizedPageChecker(fsPathname)
// If we didn't match a page check dynamic routes
if (!matchedPage) {
for (const dynamicRoute of this.dynamicRoutes) {
if (dynamicRoute.match(fsPathname)) {
matchedPage = true
}
}
}
// Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) {
checkParsedUrl.pathname = fsPathname
const pageParams = this.catchAllRoute.match(checkParsedUrl.pathname)
await this.catchAllRoute.fn(
req,
res,
pageParams as Params,
checkParsedUrl
)
return true
}
}
/* /*
Desired routes order Desired routes order
- headers - headers
...@@ -133,6 +192,7 @@ export default class Router { ...@@ -133,6 +192,7 @@ export default class Router {
const allRoutes = [ const allRoutes = [
...this.headers, ...this.headers,
...this.redirects, ...this.redirects,
...this.rewrites.beforeFiles,
...this.fsRoutes, ...this.fsRoutes,
// We only check the catch-all route if public page routes hasn't been // We only check the catch-all route if public page routes hasn't been
// disabled // disabled
...@@ -164,7 +224,29 @@ export default class Router { ...@@ -164,7 +224,29 @@ export default class Router {
} as Route, } as Route,
] ]
: []), : []),
...this.rewrites, ...this.rewrites.afterFiles,
...(this.rewrites.fallback.length
? [
{
type: 'route',
name: 'dynamic route/page check',
requireBasePath: false,
match: route('/:path*'),
fn: async (
_checkerReq,
_checkerRes,
_params,
parsedCheckerUrl
) => {
return {
finished: await applyCheckTrue(parsedCheckerUrl),
}
},
} as Route,
...this.rewrites.fallback,
]
: []),
// We only check the catch-all route if public page routes hasn't been // We only check the catch-all route if public page routes hasn't been
// disabled // disabled
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []), ...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
...@@ -283,55 +365,7 @@ export default class Router { ...@@ -283,55 +365,7 @@ export default class Router {
// check filesystem // check filesystem
if (testRoute.check === true) { if (testRoute.check === true) {
const originalFsPathname = parsedUrlUpdated.pathname if (await applyCheckTrue(parsedUrlUpdated)) {
const fsPathname = replaceBasePath(this.basePath, originalFsPathname!)
for (const fsRoute of this.fsRoutes) {
const fsParams = fsRoute.match(fsPathname)
if (fsParams) {
parsedUrlUpdated.pathname = fsPathname
const fsResult = await fsRoute.fn(
req,
res,
fsParams,
parsedUrlUpdated
)
if (fsResult.finished) {
return true
}
parsedUrlUpdated.pathname = originalFsPathname
}
}
let matchedPage = await memoizedPageChecker(fsPathname)
// If we didn't match a page check dynamic routes
if (!matchedPage) {
for (const dynamicRoute of this.dynamicRoutes) {
if (dynamicRoute.match(fsPathname)) {
matchedPage = true
}
}
}
// Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) {
parsedUrlUpdated.pathname = fsPathname
const pageParams = this.catchAllRoute.match(
parsedUrlUpdated.pathname
)
await this.catchAllRoute.fn(
req,
res,
pageParams as Params,
parsedUrlUpdated
)
return true return true
} }
} }
......
...@@ -26,9 +26,9 @@ import getRouteFromEntrypoint from '../next-server/server/get-route-from-entrypo ...@@ -26,9 +26,9 @@ import getRouteFromEntrypoint from '../next-server/server/get-route-from-entrypo
import { isWriteable } from '../build/is-writeable' import { isWriteable } from '../build/is-writeable'
import { ClientPagesLoaderOptions } from '../build/webpack/loaders/next-client-pages-loader' import { ClientPagesLoaderOptions } from '../build/webpack/loaders/next-client-pages-loader'
import { stringify } from 'querystring' import { stringify } from 'querystring'
import { Rewrite } from '../lib/load-custom-routes'
import { difference } from '../build/utils' import { difference } from '../build/utils'
import { NextConfig } from '../next-server/server/config' import { NextConfig } from '../next-server/server/config'
import { CustomRoutes } from '../lib/load-custom-routes'
export async function renderScriptError( export async function renderScriptError(
res: ServerResponse, res: ServerResponse,
...@@ -143,7 +143,7 @@ export default class HotReloader { ...@@ -143,7 +143,7 @@ export default class HotReloader {
private onDemandEntries: any private onDemandEntries: any
private previewProps: __ApiPreviewProps private previewProps: __ApiPreviewProps
private watcher: any private watcher: any
private rewrites: Rewrite[] private rewrites: CustomRoutes['rewrites']
constructor( constructor(
dir: string, dir: string,
...@@ -158,7 +158,7 @@ export default class HotReloader { ...@@ -158,7 +158,7 @@ export default class HotReloader {
pagesDir: string pagesDir: string
buildId: string buildId: string
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
rewrites: Rewrite[] rewrites: CustomRoutes['rewrites']
} }
) { ) {
this.buildId = buildId this.buildId = buildId
......
...@@ -272,7 +272,14 @@ export default class DevServer extends Server { ...@@ -272,7 +272,14 @@ export default class DevServer extends Server {
// reload router // reload router
const { redirects, rewrites, headers } = this.customRoutes const { redirects, rewrites, headers } = this.customRoutes
if (redirects.length || rewrites.length || headers.length) {
if (
rewrites.beforeFiles.length ||
rewrites.afterFiles.length ||
rewrites.fallback.length ||
redirects.length ||
headers.length
) {
this.router = new Router(this.generateRoutes()) this.router = new Router(this.generateRoutes())
} }
...@@ -281,7 +288,7 @@ export default class DevServer extends Server { ...@@ -281,7 +288,7 @@ export default class DevServer extends Server {
config: this.nextConfig, config: this.nextConfig,
previewProps: this.getPreviewProps(), previewProps: this.getPreviewProps(),
buildId: this.buildId, buildId: this.buildId,
rewrites: this.customRoutes.rewrites, rewrites,
}) })
await super.prepare() await super.prepare()
await this.addExportPathMapRoutes() await this.addExportPathMapRoutes()
...@@ -415,7 +422,11 @@ export default class DevServer extends Server { ...@@ -415,7 +422,11 @@ export default class DevServer extends Server {
// override production loading of routes-manifest // override production loading of routes-manifest
protected getCustomRoutes(): CustomRoutes { protected getCustomRoutes(): CustomRoutes {
// actual routes will be loaded asynchronously during .prepare() // actual routes will be loaded asynchronously during .prepare()
return { redirects: [], rewrites: [], headers: [] } return {
redirects: [],
rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },
headers: [],
}
} }
private _devCachedPreviewProps: __ApiPreviewProps | undefined private _devCachedPreviewProps: __ApiPreviewProps | undefined
......
...@@ -95,7 +95,7 @@ describe('Build Output', () => { ...@@ -95,7 +95,7 @@ describe('Build Output', () => {
expect(indexSize.endsWith('B')).toBe(true) expect(indexSize.endsWith('B')).toBe(true)
// should be no bigger than 64.8 kb // should be no bigger than 64.8 kb
expect(parseFloat(indexFirstLoad)).toBeCloseTo(65.4, 1) expect(parseFloat(indexFirstLoad)).toBeCloseTo(65.3, 1)
expect(indexFirstLoad.endsWith('kB')).toBe(true) expect(indexFirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0) expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0)
...@@ -104,7 +104,7 @@ describe('Build Output', () => { ...@@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad)).toBeCloseTo(68.5, 0) expect(parseFloat(err404FirstLoad)).toBeCloseTo(68.5, 0)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll)).toBeCloseTo(65.1, 1) expect(parseFloat(sharedByAll)).toBeCloseTo(65, 1)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) { if (_appSize.endsWith('kB')) {
......
module.exports = { module.exports = {
// target: 'serverless', // target: 'serverless',
async rewrites() { async rewrites() {
return [ return {
...(process.env.ADD_NOOP_REWRITE === 'true' afterFiles: [
? [ ...(process.env.ADD_NOOP_REWRITE === 'true'
? [
{
source: '/:path*',
destination: '/:path*',
},
]
: []),
{
source: '/rewriting-to-auto-export',
destination: '/auto-export/hello',
},
{
source: '/to-another',
destination: '/another/one',
},
{
source: '/nav',
destination: '/404',
},
{
source: '/hello-world',
destination: '/static/hello.txt',
},
{
source: '/',
destination: '/another',
},
{
source: '/another',
destination: '/multi-rewrites',
},
{
source: '/first',
destination: '/hello',
},
{
source: '/second',
destination: '/hello-again',
},
{
source: '/to-hello',
destination: '/hello',
},
{
source: '/blog/post-1',
destination: '/blog/post-2',
},
{
source: '/test/:path',
destination: '/:path',
},
{
source: '/test-overwrite/:something/:another',
destination: '/params/this-should-be-the-value',
},
{
source: '/params/:something',
destination: '/with-params',
},
{
source: '/query-rewrite/:section/:name',
destination: '/with-params?first=:section&second=:name',
},
{
source: '/hidden/_next/:path*',
destination: '/_next/:path*',
},
{
source: '/proxy-me/:path*',
destination: 'http://localhost:__EXTERNAL_PORT__/:path*',
},
{
source: '/api-hello',
destination: '/api/hello',
},
{
source: '/api-hello-regex/:first(.*)',
destination: '/api/hello?name=:first*',
},
{
source: '/api-hello-param/:name',
destination: '/api/hello?hello=:name',
},
{
source: '/api-dynamic-param/:name',
destination: '/api/dynamic/:name?hello=:name',
},
{
source: '/:path/post-321',
destination: '/with-params',
},
{
source: '/unnamed-params/nested/(.*)/:test/(.*)',
destination: '/with-params',
},
{
source: '/catchall-rewrite/:path*',
destination: '/with-params',
},
{
source: '/catchall-query/:path*',
destination: '/with-params?another=:path*',
},
{
source: '/has-rewrite-1',
has: [
{ {
source: '/:path*', type: 'header',
destination: '/:path*', key: 'x-my-header',
value: '(?<myHeader>.*)',
}, },
] ],
: []), destination: '/with-params?myHeader=:myHeader',
{ },
source: '/rewriting-to-auto-export', {
destination: '/auto-export/hello', source: '/has-rewrite-2',
}, has: [
{ {
source: '/to-another', type: 'query',
destination: '/another/one', key: 'my-query',
}, },
{ ],
source: '/nav', destination: '/with-params?value=:myquery',
destination: '/404', },
}, {
{ source: '/has-rewrite-3',
source: '/hello-world', has: [
destination: '/static/hello.txt', {
}, type: 'cookie',
{ key: 'loggedIn',
source: '/', value: 'true',
destination: '/another', },
}, ],
{ destination: '/with-params?authorized=1',
source: '/another', },
destination: '/multi-rewrites', {
}, source: '/has-rewrite-4',
{ has: [
source: '/first', {
destination: '/hello', type: 'host',
}, value: 'example.com',
{ },
source: '/second', ],
destination: '/hello-again', destination: '/with-params?host=1',
}, },
{ ],
source: '/to-hello', beforeFiles: [
destination: '/hello', {
}, source: '/hello',
{ has: [
source: '/blog/post-1', {
destination: '/blog/post-2', type: 'query',
}, key: 'overrideMe',
{ },
source: '/test/:path', ],
destination: '/:path', destination: '/with-params?overridden=1',
}, },
{ ],
source: '/test-overwrite/:something/:another', }
destination: '/params/this-should-be-the-value',
},
{
source: '/params/:something',
destination: '/with-params',
},
{
source: '/query-rewrite/:section/:name',
destination: '/with-params?first=:section&second=:name',
},
{
source: '/hidden/_next/:path*',
destination: '/_next/:path*',
},
{
source: '/proxy-me/:path*',
destination: 'http://localhost:__EXTERNAL_PORT__/:path*',
},
{
source: '/api-hello',
destination: '/api/hello',
},
{
source: '/api-hello-regex/:first(.*)',
destination: '/api/hello?name=:first*',
},
{
source: '/api-hello-param/:name',
destination: '/api/hello?hello=:name',
},
{
source: '/api-dynamic-param/:name',
destination: '/api/dynamic/:name?hello=:name',
},
{
source: '/:path/post-321',
destination: '/with-params',
},
{
source: '/unnamed-params/nested/(.*)/:test/(.*)',
destination: '/with-params',
},
{
source: '/catchall-rewrite/:path*',
destination: '/with-params',
},
{
source: '/catchall-query/:path*',
destination: '/with-params?another=:path*',
},
{
source: '/has-rewrite-1',
has: [
{
type: 'header',
key: 'x-my-header',
value: '(?<myHeader>.*)',
},
],
destination: '/with-params?myHeader=:myHeader',
},
{
source: '/has-rewrite-2',
has: [
{
type: 'query',
key: 'my-query',
},
],
destination: '/with-params?value=:myquery',
},
{
source: '/has-rewrite-3',
has: [
{
type: 'cookie',
key: 'loggedIn',
value: 'true',
},
],
destination: '/with-params?authorized=1',
},
{
source: '/has-rewrite-4',
has: [
{
type: 'host',
value: 'example.com',
},
],
destination: '/with-params?host=1',
},
]
}, },
async redirects() { async redirects() {
return [ return [
......
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