Unverified Commit 4def88c3 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update next-server routes order for expected priority (#10326)

* Update next-server routes order for expected priority

* Update router to allow disabling page routes

* Fix headers having check: true behavior when they should not
Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
parent 14f33dd5
...@@ -3,7 +3,6 @@ import fs from 'fs' ...@@ -3,7 +3,6 @@ import fs from 'fs'
import Proxy from 'http-proxy' import Proxy from 'http-proxy'
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { join, resolve, sep } from 'path' import { join, resolve, sep } from 'path'
import { compile as compilePathToRegex } from 'path-to-regexp'
import { parse as parseQs, ParsedUrlQuery } from 'querystring' import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url' import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url'
...@@ -40,6 +39,7 @@ import Router, { ...@@ -40,6 +39,7 @@ import Router, {
Route, Route,
DynamicRoutes, DynamicRoutes,
PageChecker, PageChecker,
prepareDestination,
} from './router' } from './router'
import { sendHTML } from './send-html' import { sendHTML } from './send-html'
import { serveStatic } from './serve-static' import { serveStatic } from './serve-static'
...@@ -284,10 +284,13 @@ export default class Server { ...@@ -284,10 +284,13 @@ export default class Server {
} }
protected generateRoutes(): { protected generateRoutes(): {
routes: Route[] headers: Route[]
rewrites: Route[]
fsRoutes: Route[] fsRoutes: Route[]
redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
} { } {
this.customRoutes = this.getCustomRoutes() this.customRoutes = this.getCustomRoutes()
...@@ -316,6 +319,10 @@ export default class Server { ...@@ -316,6 +319,10 @@ export default class Server {
] ]
: [] : []
let headers: Route[] = []
let rewrites: Route[] = []
let redirects: Route[] = []
const fsRoutes: Route[] = [ const fsRoutes: Route[] = [
{ {
match: route('/_next/static/:path*'), match: route('/_next/static/:path*'),
...@@ -412,27 +419,25 @@ export default class Server { ...@@ -412,27 +419,25 @@ export default class Server {
...publicRoutes, ...publicRoutes,
...staticFilesRoute, ...staticFilesRoute,
] ]
const routes: Route[] = []
if (this.customRoutes) { if (this.customRoutes) {
const { redirects, rewrites, headers } = this.customRoutes
const getCustomRoute = ( const getCustomRoute = (
r: Rewrite | Redirect | Header, r: Rewrite | Redirect | Header,
type: RouteType type: RouteType
) => ({ ) =>
({
...r, ...r,
type, type,
matcher: getCustomRouteMatcher(r.source), match: getCustomRouteMatcher(r.source),
}) name: type,
fn: async (req, res, params, parsedUrl) => ({ finished: false }),
} as Route & Rewrite & Header)
// Headers come very first // Headers come very first
routes.push( headers = this.customRoutes.headers.map(r => {
...headers.map(r => {
const route = getCustomRoute(r, 'header') const route = getCustomRoute(r, 'header')
return { return {
check: true, match: route.match,
match: route.matcher,
type: route.type, type: route.type,
name: `${route.type} ${route.source} header route`, name: `${route.type} ${route.source} header route`,
fn: async (_req, res, _params, _parsedUrl) => { fn: async (_req, res, _params, _parsedUrl) => {
...@@ -443,64 +448,21 @@ export default class Server { ...@@ -443,64 +448,21 @@ export default class Server {
}, },
} as Route } as Route
}) })
)
const customRoutes = [ redirects = this.customRoutes.redirects.map(redirect => {
...redirects.map(r => getCustomRoute(r, 'redirect')), const route = getCustomRoute(redirect, 'redirect')
...rewrites.map(r => getCustomRoute(r, 'rewrite')),
]
routes.push(
...customRoutes.map(route => {
return { return {
check: true,
match: route.matcher,
type: route.type, type: route.type,
statusCode: (route as Redirect).statusCode, match: route.match,
name: `${route.type} ${route.source} route`, statusCode: route.statusCode,
fn: async (req, res, params, _parsedUrl) => { name: `Redirect route`,
const parsedDestination = parseUrl(route.destination, true) fn: async (_req, res, params, _parsedUrl) => {
const destQuery = parsedDestination.query const { parsedDestination } = prepareDestination(
let destinationCompiler = compilePathToRegex( route.destination,
`${parsedDestination.pathname!}${parsedDestination.hash || ''}` params
)
let newUrl
Object.keys(destQuery).forEach(key => {
const val = destQuery[key]
if (
typeof val === 'string' &&
val.startsWith(':') &&
params[val.substr(1)]
) {
destQuery[key] = params[val.substr(1)]
}
})
try {
newUrl = destinationCompiler(params)
} catch (err) {
if (
err.message.match(
/Expected .*? to not repeat, but got an array/
)
) {
throw new Error(
`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://err.sh/zeit/next.js/invalid-multi-match`
) )
} const updatedDestination = formatUrl(parsedDestination)
throw err
}
const parsedNewUrl = parseUrl(newUrl)
const updatedDestination = formatUrl({
...parsedDestination,
pathname: parsedNewUrl.pathname,
hash: parsedNewUrl.hash,
search: undefined,
})
if (route.type === 'redirect') {
res.setHeader('Location', updatedDestination) res.setHeader('Location', updatedDestination)
res.statusCode = getRedirectStatus(route as Redirect) res.statusCode = getRedirectStatus(route as Redirect)
...@@ -514,28 +476,41 @@ export default class Server { ...@@ -514,28 +476,41 @@ export default class Server {
return { return {
finished: true, finished: true,
} }
} else { },
} as Route
})
rewrites = this.customRoutes.rewrites.map(rewrite => {
const route = getCustomRoute(rewrite, 'rewrite')
return {
check: true,
type: route.type,
name: `Rewrite route`,
match: route.match,
fn: async (req, res, params, _parsedUrl) => {
const { newUrl, parsedDestination } = prepareDestination(
route.destination,
params
)
// external rewrite, proxy it // external rewrite, proxy it
if (parsedDestination.protocol) { if (parsedDestination.protocol) {
const target = formatUrl(parsedDestination)
const proxy = new Proxy({ const proxy = new Proxy({
target: updatedDestination, target,
changeOrigin: true, changeOrigin: true,
ignorePath: true, ignorePath: true,
}) })
proxy.web(req, res) proxy.web(req, res)
proxy.on('error', (err: Error) => { proxy.on('error', (err: Error) => {
console.error( console.error(`Error occurred proxying ${target}`, err)
`Error occurred proxying ${updatedDestination}`,
err
)
}) })
return { return {
finished: true, finished: true,
} }
} }
;(req as any)._nextDidRewrite = true ;(req as any)._nextDidRewrite = true
}
return { return {
finished: false, finished: false,
...@@ -545,34 +520,8 @@ export default class Server { ...@@ -545,34 +520,8 @@ export default class Server {
}, },
} as Route } as Route
}) })
)
} }
const catchPublicDirectoryRoute: Route = {
match: route('/:path*'),
type: 'route',
name: 'Catch public directory route',
fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
// Used in development to check public directory paths
if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
return {
finished: true,
}
}
return {
finished: false,
}
},
}
routes.push(catchPublicDirectoryRoute)
const catchAllRoute: Route = { const catchAllRoute: Route = {
match: route('/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
...@@ -602,20 +551,19 @@ export default class Server { ...@@ -602,20 +551,19 @@ export default class Server {
}, },
} }
if (this.nextConfig.useFileSystemPublicRoutes) { const { useFileSystemPublicRoutes } = this.nextConfig
this.dynamicRoutes = this.getDynamicRoutes()
// It's very important to keep this route's param optional. if (useFileSystemPublicRoutes) {
// (but it should support as many params as needed, separated by '/') this.dynamicRoutes = this.getDynamicRoutes()
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617
routes.push(catchAllRoute)
} }
return { return {
routes, headers,
fsRoutes, fsRoutes,
rewrites,
redirects,
catchAllRoute, catchAllRoute,
useFileSystemPublicRoutes,
dynamicRoutes: this.dynamicRoutes, dynamicRoutes: this.dynamicRoutes,
pageChecker: this.hasPage.bind(this), pageChecker: this.hasPage.bind(this),
} }
......
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import { UrlWithParsedQuery } from 'url' import { parse as parseUrl, UrlWithParsedQuery } from 'url'
import { compile as compilePathToRegex } from 'path-to-regexp'
import { stringify as stringifyQs } from 'querystring'
import pathMatch from './lib/path-match' import pathMatch from './lib/path-match'
export const route = pathMatch() export const route = pathMatch()
...@@ -32,39 +34,91 @@ export type DynamicRoutes = Array<{ page: string; match: RouteMatch }> ...@@ -32,39 +34,91 @@ export type DynamicRoutes = Array<{ page: string; match: RouteMatch }>
export type PageChecker = (pathname: string) => Promise<boolean> export type PageChecker = (pathname: string) => Promise<boolean>
export const prepareDestination = (destination: string, params: Params) => {
const parsedDestination = parseUrl(destination, true)
const destQuery = parsedDestination.query
let destinationCompiler = compilePathToRegex(
`${parsedDestination.pathname!}${parsedDestination.hash || ''}`
)
let newUrl
Object.keys(destQuery).forEach(key => {
const val = destQuery[key]
if (
typeof val === 'string' &&
val.startsWith(':') &&
params[val.substr(1)]
) {
destQuery[key] = params[val.substr(1)]
}
})
try {
newUrl = destinationCompiler(params)
const [pathname, hash] = newUrl.split('#')
parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
parsedDestination.search = stringifyQs(parsedDestination.query)
parsedDestination.path = `${pathname}${parsedDestination.search}`
} catch (err) {
if (err.message.match(/Expected .*? to not repeat, but got an array/)) {
throw new Error(
`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://err.sh/zeit/next.js/invalid-multi-match`
)
}
throw err
}
return {
newUrl,
parsedDestination,
}
}
export default class Router { export default class Router {
routes: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
rewrites: Route[]
redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
pageChecker: PageChecker pageChecker: PageChecker
dynamicRoutes: DynamicRoutes dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean
constructor({ constructor({
routes = [], headers = [],
fsRoutes = [], fsRoutes = [],
rewrites = [],
redirects = [],
catchAllRoute, catchAllRoute,
dynamicRoutes = [], dynamicRoutes = [],
pageChecker, pageChecker,
useFileSystemPublicRoutes,
}: { }: {
routes: Route[] headers: Route[]
fsRoutes: Route[] fsRoutes: Route[]
rewrites: Route[]
redirects: Route[]
catchAllRoute: Route catchAllRoute: Route
dynamicRoutes: DynamicRoutes | undefined dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker pageChecker: PageChecker
useFileSystemPublicRoutes: boolean
}) { }) {
this.routes = routes this.headers = headers
this.fsRoutes = fsRoutes this.fsRoutes = fsRoutes
this.rewrites = rewrites
this.redirects = redirects
this.pageChecker = pageChecker this.pageChecker = pageChecker
this.catchAllRoute = catchAllRoute this.catchAllRoute = catchAllRoute
this.dynamicRoutes = dynamicRoutes this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
} }
setDynamicRoutes(routes: DynamicRoutes = []) { setDynamicRoutes(routes: DynamicRoutes = []) {
this.dynamicRoutes = routes this.dynamicRoutes = routes
} }
add(route: Route) { addFsRoute(route: Route) {
this.routes.unshift(route) this.fsRoutes.unshift(route)
} }
async execute( async execute(
...@@ -85,7 +139,47 @@ export default class Router { ...@@ -85,7 +139,47 @@ export default class Router {
let parsedUrlUpdated = parsedUrl let parsedUrlUpdated = parsedUrl
for (const route of [...this.fsRoutes, ...this.routes]) { /*
Desired routes order
- headers
- redirects
- Check filesystem (including pages), if nothing found continue
- User rewrites (checking filesystem and pages each match)
*/
const routes = [
...this.headers,
...this.redirects,
...this.fsRoutes,
// We only check the catch-all route if public page routes hasn't been
// disabled
...(this.useFileSystemPublicRoutes
? [
{
type: 'route',
name: 'Page checker',
match: route('/:path*'),
fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl
if (!pathname) {
return { finished: false }
}
if (await this.pageChecker(pathname)) {
return this.catchAllRoute.fn(req, res, params, parsedUrl)
}
return { finished: false }
},
} as Route,
]
: []),
...this.rewrites,
// We only check the catch-all route if public page routes hasn't been
// disabled
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
]
for (const route of routes) {
const newParams = route.match(parsedUrlUpdated.pathname) const newParams = route.match(parsedUrlUpdated.pathname)
// Check if the match function matched // Check if the match function matched
......
...@@ -106,7 +106,7 @@ export default class DevServer extends Server { ...@@ -106,7 +106,7 @@ export default class DevServer extends Server {
const { page, query = {} } = exportPathMap[path] const { page, query = {} } = exportPathMap[path]
// We use unshift so that we're sure the routes is defined before Next's default routes // We use unshift so that we're sure the routes is defined before Next's default routes
this.router.add({ this.router.addFsRoute({
match: route(path), match: route(path),
type: 'route', type: 'route',
name: `${path} exportpathmap route`, name: `${path} exportpathmap route`,
...@@ -336,13 +336,7 @@ export default class DevServer extends Server { ...@@ -336,13 +336,7 @@ export default class DevServer extends Server {
} }
generateRoutes() { generateRoutes() {
const { const { fsRoutes, ...otherRoutes } = super.generateRoutes()
routes,
fsRoutes,
catchAllRoute,
dynamicRoutes,
pageChecker,
} = super.generateRoutes()
// In development we expose all compiled files for react-error-overlay's line show feature // In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes // We use unshift so that we're sure the routes is defined before Next's default routes
...@@ -359,7 +353,30 @@ export default class DevServer extends Server { ...@@ -359,7 +353,30 @@ export default class DevServer extends Server {
}, },
}) })
return { routes, fsRoutes, catchAllRoute, dynamicRoutes, pageChecker } fsRoutes.push({
match: route('/:path*'),
type: 'route',
name: 'Catchall public directory route',
fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
// Used in development to check public directory paths
if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
return {
finished: true,
}
}
return {
finished: false,
}
},
})
return { fsRoutes, ...otherRoutes }
} }
// In development public files are not added to the router but handled as a fallback instead // In development public files are not added to the router but handled as a fallback instead
......
...@@ -7,6 +7,10 @@ module.exports = { ...@@ -7,6 +7,10 @@ module.exports = {
source: '/to-another', source: '/to-another',
destination: '/another/one', destination: '/another/one',
}, },
{
source: '/nav',
destination: '/404',
},
{ {
source: '/hello-world', source: '/hello-world',
destination: '/static/hello.txt', destination: '/static/hello.txt',
...@@ -71,6 +75,10 @@ module.exports = { ...@@ -71,6 +75,10 @@ module.exports = {
source: '/api-hello-param/:name', source: '/api-hello-param/:name',
destination: '/api/hello?name=:name', destination: '/api/hello?name=:name',
}, },
{
source: '/:path/post-321',
destination: '/with-params',
},
] ]
}, },
async redirects() { async redirects() {
...@@ -150,6 +158,11 @@ module.exports = { ...@@ -150,6 +158,11 @@ module.exports = {
destination: '/:0', destination: '/:0',
permanent: false, permanent: false,
}, },
{
source: '/redirect-override',
destination: '/thank-you-next',
permanent: false,
},
] ]
}, },
...@@ -181,6 +194,15 @@ module.exports = { ...@@ -181,6 +194,15 @@ module.exports = {
}, },
], ],
}, },
{
source: '/:path*',
headers: [
{
key: 'x-something',
value: 'applied-everywhere',
},
],
},
] ]
}, },
}, },
......
...@@ -45,6 +45,14 @@ const runTests = (isDev = false) => { ...@@ -45,6 +45,14 @@ const runTests = (isDev = false) => {
expect(html).toMatch(/multi-rewrites/) expect(html).toMatch(/multi-rewrites/)
}) })
it('should not match dynamic route immediately after applying header', async () => {
const res = await fetchViaHTTP(appPort, '/blog/post-321')
expect(res.headers.get('x-something')).toBe('applied-everywhere')
const $ = cheerio.load(await res.text())
expect(JSON.parse($('p').text()).path).toBe('blog')
})
it('should handle chained redirects successfully', async () => { it('should handle chained redirects successfully', async () => {
const res1 = await fetchViaHTTP(appPort, '/redir-chain1', undefined, { const res1 = await fetchViaHTTP(appPort, '/redir-chain1', undefined, {
redirect: 'manual', redirect: 'manual',
...@@ -159,6 +167,22 @@ const runTests = (isDev = false) => { ...@@ -159,6 +167,22 @@ const runTests = (isDev = false) => {
expect(html).toMatch(/second/) expect(html).toMatch(/second/)
}) })
// current routes order do not allow rewrites to override page
// but allow redirects to
it('should not allow rewrite to override page file', async () => {
const html = await renderViaHTTP(appPort, '/nav')
expect(html).toContain('to-hello')
})
it('show allow redirect to override the page', async () => {
const res = await fetchViaHTTP(appPort, '/redirect-override', undefined, {
redirect: 'manual',
})
const { pathname } = url.parse(res.headers.get('location') || '')
expect(res.status).toBe(307)
expect(pathname).toBe('/thank-you-next')
})
it('should work successfully on the client', async () => { it('should work successfully on the client', async () => {
const browser = await webdriver(appPort, '/nav') const browser = await webdriver(appPort, '/nav')
await browser.elementByCss('#to-hello').click() await browser.elementByCss('#to-hello').click()
...@@ -401,6 +425,12 @@ const runTests = (isDev = false) => { ...@@ -401,6 +425,12 @@ const runTests = (isDev = false) => {
source: '/named-like-unnamed/:0', source: '/named-like-unnamed/:0',
statusCode: 307, statusCode: 307,
}, },
{
destination: '/thank-you-next',
regex: normalizeRegEx('^\\/redirect-override$'),
source: '/redirect-override',
statusCode: 307,
},
], ],
headers: [ headers: [
{ {
...@@ -431,6 +461,18 @@ const runTests = (isDev = false) => { ...@@ -431,6 +461,18 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/my-headers(?:\\/(.*))$'), regex: normalizeRegEx('^\\/my-headers(?:\\/(.*))$'),
source: '/my-headers/(.*)', source: '/my-headers/(.*)',
}, },
{
headers: [
{
key: 'x-something',
value: 'applied-everywhere',
},
],
regex: normalizeRegEx(
'^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$'
),
source: '/:path*',
},
], ],
rewrites: [ rewrites: [
{ {
...@@ -438,6 +480,11 @@ const runTests = (isDev = false) => { ...@@ -438,6 +480,11 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/to-another$'), regex: normalizeRegEx('^\\/to-another$'),
source: '/to-another', source: '/to-another',
}, },
{
destination: '/404',
regex: '^\\/nav$',
source: '/nav',
},
{ {
source: '/hello-world', source: '/hello-world',
destination: '/static/hello.txt', destination: '/static/hello.txt',
...@@ -526,6 +573,11 @@ const runTests = (isDev = false) => { ...@@ -526,6 +573,11 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/api-hello-param(?:\\/([^\\/]+?))$'), regex: normalizeRegEx('^\\/api-hello-param(?:\\/([^\\/]+?))$'),
source: '/api-hello-param/:name', source: '/api-hello-param/:name',
}, },
{
destination: '/with-params',
regex: normalizeRegEx('^(?:\\/([^\\/]+?))\\/post-321$'),
source: '/:path/post-321',
},
], ],
dynamicRoutes: [ dynamicRoutes: [
{ {
......
...@@ -19,7 +19,7 @@ let app ...@@ -19,7 +19,7 @@ let app
const runTests = () => { const runTests = () => {
it('should show error for invalid mulit-match', async () => { it('should show error for invalid mulit-match', async () => {
await renderViaHTTP(appPort, '/hello') await renderViaHTTP(appPort, '/random')
expect(stderr).toContain( expect(stderr).toContain(
'To use a multi-match in the destination you must add' 'To use a multi-match in the destination you must add'
) )
...@@ -27,7 +27,7 @@ const runTests = () => { ...@@ -27,7 +27,7 @@ const runTests = () => {
}) })
} }
describe('Custom routes', () => { describe('Custom routes invalid multi-match', () => {
describe('dev mode', () => { describe('dev mode', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
......
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