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 = {
- `source` is the incoming request path pattern.
- `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
......
......@@ -38,6 +38,11 @@ module.exports = {
- `source` is the incoming request path pattern.
- `destination` is the path you want to route to.
- `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
......
......@@ -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 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`:
```js
......@@ -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:
- `source` is the incoming request path pattern.
- `destination` is the path you want to route to.
- `source`: `String` - is the incoming request path pattern.
- `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
......
......@@ -17,9 +17,11 @@ import {
import { fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, {
CustomRoutes,
getRedirectStatus,
normalizeRouteRegex,
Redirect,
Rewrite,
RouteType,
} from '../lib/load-custom-routes'
import { nonNullable } from '../lib/non-nullable'
......@@ -51,6 +53,7 @@ import {
import { __ApiPreviewProps } from '../next-server/server/api-utils'
import loadConfig, {
isTargetLikeServerless,
NextConfig,
} from '../next-server/server/config'
import { BuildManifest } from '../next-server/server/get-page-files'
import '../next-server/server/node-polyfill-fetch'
......@@ -125,19 +128,21 @@ export default async function build(
.traceChild('load-dotenv')
.traceFn(() => loadEnvConfig(dir, false, Log))
const config = await nextBuildSpan
const config: NextConfig = await nextBuildSpan
.traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf))
const { target } = config
const buildId = await nextBuildSpan
const buildId: string = await nextBuildSpan
.traceChild('generate-buildid')
.traceAsyncFn(() => generateBuildId(config.generateBuildId, nanoid))
const distDir = path.join(dir, config.distDir)
const { headers, rewrites, redirects } = await nextBuildSpan
const customRoutes: CustomRoutes = await nextBuildSpan
.traceChild('load-custom-routes')
.traceAsyncFn(() => loadCustomRoutes(config))
const { headers, rewrites, redirects } = customRoutes
if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
const cacheDir = path.join(distDir, 'cache')
const hasCache = await fileExists(cacheDir)
......@@ -354,7 +359,13 @@ export default async function build(
pages404: boolean
basePath: string
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>>
dynamicRoutes: Array<{
page: string
......@@ -384,7 +395,6 @@ export default async function build(
pages404: true,
basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
rewrites: rewrites.map((r: any) => buildCustomRoute(r, 'rewrite')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes: getSortedRoutes(pageKeys)
.filter(isDynamicRoute)
......@@ -401,6 +411,29 @@ export default async function build(
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
.traceChild('create-dist-dir')
.traceAsyncFn(async () => {
......@@ -1380,11 +1413,12 @@ export default async function build(
(staticPages.size + ssgPages.size + serverPropsPages.size),
hasStatic404: useStatic404,
hasReportWebVitals: namedExports?.includes('reportWebVitals') ?? false,
rewritesCount: rewrites.length,
rewritesCount: combinedRewrites.length,
headersCount: headers.length,
redirectsCount: redirects.length - 1, // reduce one for trailing slash
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,
})
)
......
......@@ -351,12 +351,18 @@ export function printCustomRoutes({
if (redirects.length) {
printRoutes(redirects, 'Redirects')
}
if (rewrites.length) {
printRoutes(rewrites, 'Rewrites')
}
if (headers.length) {
printRoutes(headers, 'Headers')
}
const combinedRewrites = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
...rewrites.fallback,
]
if (combinedRewrites.length) {
printRoutes(combinedRewrites, 'Rewrites')
}
}
type ComputeManifestShape = {
......
......@@ -16,7 +16,6 @@ import {
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version'
import { Rewrite } from '../lib/load-custom-routes'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import {
CLIENT_STATIC_FILES_RUNTIME_MAIN,
......@@ -61,6 +60,7 @@ import WebpackConformancePlugin, {
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { NextConfig } from '../next-server/server/config'
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
......@@ -201,13 +201,16 @@ export default async function getBaseWebpackConfig(
target?: string
reactProductionProfiling?: boolean
entrypoints: WebpackEntrypoints
rewrites: Rewrite[]
rewrites: CustomRoutes['rewrites']
}
): Promise<webpack.Configuration> {
let plugins: PluginMetaData[] = []
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) {
plugins = await collectPlugins(dir, config.env, config.plugins)
......
......@@ -106,9 +106,19 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
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({
pageModule: require("${absolutePagePath}"),
rewrites: routesManifest.rewrites,
rewrites: combinedRewrites,
i18n: ${i18n || 'undefined'},
page: "${page}",
basePath: "${basePath}",
......@@ -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 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({
pageModule: compMod,
pageComponent: Component,
......@@ -183,7 +203,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
buildManifest,
reactLoadableManifest,
rewrites: routesManifest.rewrites,
rewrites: combinedRewrites,
i18n: ${i18n || 'undefined'},
page: "${page}",
buildId: "${buildId}",
......
......@@ -18,6 +18,7 @@ import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
import { Rewrite } from '../../../lib/load-custom-routes'
import { getSortedRoutes } from '../../../next-server/lib/router/utils'
import { spans } from './profiling-plugin'
import { CustomRoutes } from '../../../lib/load-custom-routes'
type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> }
......@@ -28,7 +29,7 @@ export type ClientBuildManifest = Record<string, string[]>
function generateClientManifest(
compiler: any,
assetMap: BuildManifest,
rewrites: Rewrite[]
rewrites: CustomRoutes['rewrites']
): string {
const compilerSpan = spans.get(compiler)
const genClientManifestSpan = compilerSpan?.traceChild(
......@@ -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
// It has a mapping of "entry" filename to real filename. Because the real filename can be hashed in production
export default class BuildManifestPlugin {
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.rewrites = options.rewrites.map((r) => {
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.rewrites = {
beforeFiles: [],
afterFiles: [],
fallback: [],
}
this.rewrites.beforeFiles = options.rewrites.beforeFiles.map(processRoute)
this.rewrites.afterFiles = options.rewrites.afterFiles.map(processRoute)
this.rewrites.fallback = options.rewrites.fallback.map(processRoute)
}
createAssets(compiler: any, compilation: any, assets: any) {
......
......@@ -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> {
const { pathname: hrefPathname } = parseRelativeUrl(href)
const route = normalizeRoute(hrefPathname)
_isSsg(route: string): Promise<boolean> {
return this.promisedSsgManifest!.then((s: ClientSsgManifest) =>
s.has(route)
)
......
......@@ -191,7 +191,7 @@ export function getClientBuildManifest(): Promise<ClientBuildManifest> {
// Mandatory because this is not concurrent safe:
const cb = self.__BUILD_MANIFEST_CB
self.__BUILD_MANIFEST_CB = () => {
resolve(self.__BUILD_MANIFEST)
resolve(self.__BUILD_MANIFEST!)
cb && cb()
}
})
......
......@@ -38,7 +38,12 @@ export type Header = {
}
// 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
permanent?: boolean
}
......@@ -175,20 +180,18 @@ function checkCustomRoutes(
let hadInvalidStatus = false
let hadInvalidHas = false
const isRedirect = type === 'redirect'
let allowedKeys: Set<string>
if (type === 'rewrite' || isRedirect) {
allowedKeys = new Set([
'source',
'destination',
'basePath',
'locale',
...(isRedirect ? ['statusCode', 'permanent'] : []),
'has',
])
} else {
allowedKeys = new Set(['source', 'headers', 'basePath', 'locale', 'has'])
const allowedKeys = new Set<string>(['source', 'basePath', 'locale', 'has'])
if (type === 'rewrite') {
allowedKeys.add('destination')
}
if (type === 'redirect') {
allowedKeys.add('statusCode')
allowedKeys.add('permanent')
allowedKeys.add('destination')
}
if (type === 'header') {
allowedKeys.add('headers')
}
for (const route of routes) {
......@@ -431,7 +434,11 @@ function checkCustomRoutes(
export interface CustomRoutes {
headers: Header[]
rewrites: Rewrite[]
rewrites: {
fallback: Rewrite[]
afterFiles: Rewrite[]
beforeFiles: Rewrite[]
}
redirects: Redirect[]
}
......@@ -522,11 +529,41 @@ async function loadRedirects(config: NextConfig) {
async function loadRewrites(config: NextConfig) {
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) {
......
......@@ -338,18 +338,11 @@ function prepareUrlAs(router: NextRouter, url: Url, as?: Url) {
}
}
function resolveDynamicRoute(
parsedHref: UrlObject,
pages: string[],
applyBasePath = true
) {
const { pathname } = parsedHref
const cleanPathname = removePathTrailingSlash(
denormalizePagePath(applyBasePath ? delBasePath(pathname!) : pathname!)
)
function resolveDynamicRoute(pathname: string, pages: string[]) {
const cleanPathname = removePathTrailingSlash(denormalizePagePath(pathname!))
if (cleanPathname === '/404' || cleanPathname === '/_error') {
return parsedHref
return pathname
}
// handle resolving href for dynamic routes
......@@ -357,13 +350,12 @@ function resolveDynamicRoute(
// eslint-disable-next-line array-callback-return
pages.some((page) => {
if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname!)) {
parsedHref.pathname = applyBasePath ? addBasePath(page) : page
pathname = page
return true
}
})
}
parsedHref.pathname = removePathTrailingSlash(parsedHref.pathname!)
return parsedHref
return removePathTrailingSlash(pathname)
}
export type BaseRouter = {
......@@ -946,20 +938,6 @@ export default class Router implements BaseRouter {
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
// (not location.reload() but reload getInitialProps and other Next.js stuffs)
// We also need to set the method = replaceState always
......@@ -969,33 +947,48 @@ export default class Router implements BaseRouter {
method = 'replaceState'
}
let route = removePathTrailingSlash(pathname)
// we need to resolve the as value using rewrites for dynamic SSG
// pages to allow building the data URL correctly
let resolvedAs = as
if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
const rewritesResult = resolveRewrites(
addBasePath(addLocale(delBasePath(as), this.locale)),
pages,
rewrites,
query,
(p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!,
this.locales
)
resolvedAs = rewritesResult.asPath
// 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 (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
route = rewritesResult.resolvedHref
pathname = rewritesResult.resolvedHref
parsed.pathname = pathname
url = formatWithValidation(parsed)
if (pathname !== '/_error') {
if (process.env.__NEXT_HAS_REWRITES && as.startsWith('/')) {
const rewritesResult = resolveRewrites(
addBasePath(addLocale(delBasePath(as), this.locale)),
pages,
rewrites,
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 (process.env.NODE_ENV !== 'production') {
throw new Error(
......@@ -1089,7 +1082,10 @@ export default class Router implements BaseRouter {
// it's not
if (destination.startsWith('/')) {
const parsedHref = parseRelativeUrl(destination)
resolveDynamicRoute(parsedHref, pages, false)
parsedHref.pathname = resolveDynamicRoute(
parsedHref.pathname,
pages
)
if (pages.includes(parsedHref.pathname)) {
const { url: newUrl, as: newAs } = prepareUrlAs(
......@@ -1483,39 +1479,38 @@ export default class Router implements BaseRouter {
}
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
if (process.env.__NEXT_HAS_REWRITES && asPath.startsWith('/')) {
let rewrites: any[]
let rewrites: any
;({ __rewrites: rewrites } = await getClientBuildManifest())
const rewritesResult = resolveRewrites(
addBasePath(addLocale(delBasePath(asPath), this.locale)),
addBasePath(addLocale(asPath, this.locale)),
pages,
rewrites,
parsed.query,
(p: string) => resolveDynamicRoute({ pathname: p }, pages).pathname!,
(p: string) => resolveDynamicRoute(p, pages),
this.locales
)
resolvedAs = delLocale(delBasePath(rewritesResult.asPath), this.locale)
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
route = rewritesResult.resolvedHref
pathname = rewritesResult.resolvedHref
parsed.pathname = pathname
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
if (process.env.NODE_ENV !== 'production') {
......@@ -1523,7 +1518,7 @@ export default class Router implements BaseRouter {
}
await Promise.all([
this.pageLoader._isSsg(url).then((isSsg: boolean) => {
this.pageLoader._isSsg(route).then((isSsg: boolean) => {
return isSsg
? this._getStaticData(
this.pageLoader.getDataHref(
......
......@@ -12,7 +12,11 @@ const customRouteMatcher = pathMatch(true)
export default function resolveRewrites(
asPath: string,
pages: string[],
rewrites: Rewrite[],
rewrites: {
beforeFiles: Rewrite[]
afterFiles: Rewrite[]
fallback: Rewrite[]
},
query: ParsedUrlQuery,
resolveHref: (path: string) => string,
locales?: string[]
......@@ -29,72 +33,110 @@ export default function resolveRewrites(
)
let resolvedHref
if (!pages.includes(fsPathname)) {
for (const rewrite of rewrites) {
const matcher = customRouteMatcher(rewrite.source)
let params = matcher(parsedAs.pathname)
if (rewrite.has && params) {
const hasParams = matchHas(
{
headers: {
host: document.location.hostname,
},
cookies: Object.fromEntries(
document.cookie.split('; ').map((item) => {
const [key, ...value] = item.split('=')
return [key, value.join('=')]
})
),
} as any,
rewrite.has,
parsedAs.query
)
if (hasParams) {
Object.assign(params, hasParams)
} else {
params = false
}
const handleRewrite = (rewrite: Rewrite) => {
const matcher = customRouteMatcher(rewrite.source)
let params = matcher(parsedAs.pathname)
if (rewrite.has && params) {
const hasParams = matchHas(
{
headers: {
host: document.location.hostname,
},
cookies: Object.fromEntries(
document.cookie.split('; ').map((item) => {
const [key, ...value] = item.split('=')
return [key, value.join('=')]
})
),
} as any,
rewrite.has,
parsedAs.query
)
if (hasParams) {
Object.assign(params, hasParams)
} else {
params = false
}
}
if (params) {
if (!rewrite.destination) {
// this is a proxied rewrite which isn't handled on the client
break
}
const destRes = prepareDestination(
rewrite.destination,
params,
query,
true
)
parsedAs = destRes.parsedDestination
asPath = destRes.newUrl
Object.assign(query, destRes.parsedDestination.query)
fsPathname = removePathTrailingSlash(
normalizeLocalePath(delBasePath(asPath), locales).pathname
)
if (pages.includes(fsPathname)) {
// check if we now match a page as this means we are done
// resolving the rewrites
matchedPage = true
resolvedHref = fsPathname
if (params) {
if (!rewrite.destination) {
// this is a proxied rewrite which isn't handled on the client
return true
}
const destRes = prepareDestination(
rewrite.destination,
params,
query,
true
)
parsedAs = destRes.parsedDestination
asPath = destRes.newUrl
Object.assign(query, destRes.parsedDestination.query)
fsPathname = removePathTrailingSlash(
normalizeLocalePath(delBasePath(asPath), locales).pathname
)
if (pages.includes(fsPathname)) {
// check if we now match a page as this means we are done
// resolving the rewrites
matchedPage = true
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
}
}
}
// check if we match a dynamic-route, if so we break the rewrites chain
resolvedHref = resolveHref(fsPathname)
// check dynamic route before processing fallback rewrites
if (!finished) {
resolvedHref = resolveHref(fsPathname)
matchedPage = pages.includes(resolvedHref)
finished = matchedPage
}
if (resolvedHref !== asPath && pages.includes(resolvedHref)) {
matchedPage = true
if (!finished) {
for (let i = 0; i < rewrites.fallback.length; i++) {
const rewrite = rewrites.fallback[i]
if (handleRewrite(rewrite)) {
finished = true
break
}
}
}
}
return {
asPath,
parsedAs,
......
......@@ -18,15 +18,47 @@ export type NextConfig = { [key: string]: any } & {
} | null
headers?: () => Promise<Header[]>
rewrites?: () => Promise<Rewrite[]>
rewrites?: () => Promise<
| Rewrite[]
| {
beforeFiles: Rewrite[]
afterFiles: Rewrite[]
fallback: Rewrite[]
}
>
redirects?: () => Promise<Redirect[]>
trailingSlash?: boolean
future: {
strictPostcssConfiguration: boolean
excludeDefaultMomentLocales: boolean
webpack5: boolean
strictPostcssConfiguration?: boolean
excludeDefaultMomentLocales?: 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 {
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath,
images: JSON.stringify(this.nextConfig.images),
optimizeFonts: this.nextConfig.experimental.optimizeFonts && !dev,
optimizeFonts: !!this.nextConfig.experimental.optimizeFonts && !dev,
fontManifest:
this.nextConfig.experimental.optimizeFonts && !dev
? requireFontManifest(this.distDir, this._isLikeServerless)
: null,
optimizeImages: this.nextConfig.experimental.optimizeImages,
optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss,
domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir,
......@@ -361,12 +361,18 @@ export default class Server {
}
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({
pageIsDynamic,
page: matchedPathnameNoExt,
i18n: this.nextConfig.i18n,
basePath: this.nextConfig.basePath,
rewrites: this.customRoutes.rewrites,
rewrites: combinedRewrites,
})
utils.handleRewrites(req, parsedUrl)
......@@ -594,7 +600,22 @@ export default class Server {
}
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
......@@ -613,7 +634,11 @@ export default class Server {
protected generateRoutes(): {
basePath: string
headers: Route[]
rewrites: Route[]
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
fsRoutes: Route[]
redirects: Route[]
catchAllRoute: Route
......@@ -875,7 +900,7 @@ export default class Server {
} as Route
})
const rewrites = this.customRoutes.rewrites.map((rewrite) => {
const buildRewrite = (rewrite: Rewrite) => {
const rewriteRoute = getCustomRoute(rewrite, 'rewrite')
return {
...rewriteRoute,
......@@ -923,7 +948,19 @@ export default class Server {
}
},
} 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 = {
match: route('/:path*'),
......@@ -978,7 +1015,11 @@ export default class Server {
return {
headers,
fsRoutes,
rewrites,
rewrites: {
beforeFiles,
afterFiles,
fallback,
},
redirects,
catchAllRoute,
useFileSystemPublicRoutes,
......
......@@ -51,8 +51,12 @@ export default class Router {
basePath: string
headers: Route[]
fsRoutes: Route[]
rewrites: Route[]
redirects: Route[]
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
catchAllRoute: Route
pageChecker: PageChecker
dynamicRoutes: DynamicRoutes
......@@ -63,7 +67,11 @@ export default class Router {
basePath = '',
headers = [],
fsRoutes = [],
rewrites = [],
rewrites = {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
redirects = [],
catchAllRoute,
dynamicRoutes = [],
......@@ -74,7 +82,11 @@ export default class Router {
basePath: string
headers: Route[]
fsRoutes: Route[]
rewrites: Route[]
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
}
redirects: Route[]
catchAllRoute: Route
dynamicRoutes: DynamicRoutes | undefined
......@@ -122,6 +134,53 @@ export default class Router {
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
- headers
......@@ -133,6 +192,7 @@ export default class Router {
const allRoutes = [
...this.headers,
...this.redirects,
...this.rewrites.beforeFiles,
...this.fsRoutes,
// We only check the catch-all route if public page routes hasn't been
// disabled
......@@ -164,7 +224,29 @@ export default class Router {
} 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
// disabled
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
......@@ -283,55 +365,7 @@ export default class Router {
// check filesystem
if (testRoute.check === true) {
const originalFsPathname = parsedUrlUpdated.pathname
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
)
if (await applyCheckTrue(parsedUrlUpdated)) {
return true
}
}
......
......@@ -26,9 +26,9 @@ import getRouteFromEntrypoint from '../next-server/server/get-route-from-entrypo
import { isWriteable } from '../build/is-writeable'
import { ClientPagesLoaderOptions } from '../build/webpack/loaders/next-client-pages-loader'
import { stringify } from 'querystring'
import { Rewrite } from '../lib/load-custom-routes'
import { difference } from '../build/utils'
import { NextConfig } from '../next-server/server/config'
import { CustomRoutes } from '../lib/load-custom-routes'
export async function renderScriptError(
res: ServerResponse,
......@@ -143,7 +143,7 @@ export default class HotReloader {
private onDemandEntries: any
private previewProps: __ApiPreviewProps
private watcher: any
private rewrites: Rewrite[]
private rewrites: CustomRoutes['rewrites']
constructor(
dir: string,
......@@ -158,7 +158,7 @@ export default class HotReloader {
pagesDir: string
buildId: string
previewProps: __ApiPreviewProps
rewrites: Rewrite[]
rewrites: CustomRoutes['rewrites']
}
) {
this.buildId = buildId
......
......@@ -272,7 +272,14 @@ export default class DevServer extends Server {
// reload router
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())
}
......@@ -281,7 +288,7 @@ export default class DevServer extends Server {
config: this.nextConfig,
previewProps: this.getPreviewProps(),
buildId: this.buildId,
rewrites: this.customRoutes.rewrites,
rewrites,
})
await super.prepare()
await this.addExportPathMapRoutes()
......@@ -415,7 +422,11 @@ export default class DevServer extends Server {
// override production loading of routes-manifest
protected getCustomRoutes(): CustomRoutes {
// actual routes will be loaded asynchronously during .prepare()
return { redirects: [], rewrites: [], headers: [] }
return {
redirects: [],
rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },
headers: [],
}
}
private _devCachedPreviewProps: __ApiPreviewProps | undefined
......
......@@ -95,7 +95,7 @@ describe('Build Output', () => {
expect(indexSize.endsWith('B')).toBe(true)
// 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(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0)
......@@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad)).toBeCloseTo(68.5, 0)
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)
if (_appSize.endsWith('kB')) {
......
module.exports = {
// target: 'serverless',
async rewrites() {
return [
...(process.env.ADD_NOOP_REWRITE === 'true'
? [
return {
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*',
destination: '/:path*',
type: 'header',
key: 'x-my-header',
value: '(?<myHeader>.*)',
},
]
: []),
{
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: [
{
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',
},
]
],
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',
},
],
beforeFiles: [
{
source: '/hello',
has: [
{
type: 'query',
key: 'overrideMe',
},
],
destination: '/with-params?overridden=1',
},
],
}
},
async redirects() {
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