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
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'
export const route = pathMatch()
......@@ -32,39 +34,91 @@ export type DynamicRoutes = Array<{ page: string; match: RouteMatch }>
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 {
routes: Route[]
headers: Route[]
fsRoutes: Route[]
rewrites: Route[]
redirects: Route[]
catchAllRoute: Route
pageChecker: PageChecker
dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean
constructor({
routes = [],
headers = [],
fsRoutes = [],
rewrites = [],
redirects = [],
catchAllRoute,
dynamicRoutes = [],
pageChecker,
useFileSystemPublicRoutes,
}: {
routes: Route[]
headers: Route[]
fsRoutes: Route[]
rewrites: Route[]
redirects: Route[]
catchAllRoute: Route
dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker
useFileSystemPublicRoutes: boolean
}) {
this.routes = routes
this.headers = headers
this.fsRoutes = fsRoutes
this.rewrites = rewrites
this.redirects = redirects
this.pageChecker = pageChecker
this.catchAllRoute = catchAllRoute
this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
}
setDynamicRoutes(routes: DynamicRoutes = []) {
this.dynamicRoutes = routes
}
add(route: Route) {
this.routes.unshift(route)
addFsRoute(route: Route) {
this.fsRoutes.unshift(route)
}
async execute(
......@@ -85,7 +139,47 @@ export default class Router {
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)
// Check if the match function matched
......
......@@ -106,7 +106,7 @@ export default class DevServer extends Server {
const { page, query = {} } = exportPathMap[path]
// 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),
type: 'route',
name: `${path} exportpathmap route`,
......@@ -336,13 +336,7 @@ export default class DevServer extends Server {
}
generateRoutes() {
const {
routes,
fsRoutes,
catchAllRoute,
dynamicRoutes,
pageChecker,
} = super.generateRoutes()
const { fsRoutes, ...otherRoutes } = super.generateRoutes()
// 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
......@@ -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
......
......@@ -7,6 +7,10 @@ module.exports = {
source: '/to-another',
destination: '/another/one',
},
{
source: '/nav',
destination: '/404',
},
{
source: '/hello-world',
destination: '/static/hello.txt',
......@@ -71,6 +75,10 @@ module.exports = {
source: '/api-hello-param/:name',
destination: '/api/hello?name=:name',
},
{
source: '/:path/post-321',
destination: '/with-params',
},
]
},
async redirects() {
......@@ -150,6 +158,11 @@ module.exports = {
destination: '/:0',
permanent: false,
},
{
source: '/redirect-override',
destination: '/thank-you-next',
permanent: false,
},
]
},
......@@ -181,6 +194,15 @@ module.exports = {
},
],
},
{
source: '/:path*',
headers: [
{
key: 'x-something',
value: 'applied-everywhere',
},
],
},
]
},
},
......
......@@ -45,6 +45,14 @@ const runTests = (isDev = false) => {
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 () => {
const res1 = await fetchViaHTTP(appPort, '/redir-chain1', undefined, {
redirect: 'manual',
......@@ -159,6 +167,22 @@ const runTests = (isDev = false) => {
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 () => {
const browser = await webdriver(appPort, '/nav')
await browser.elementByCss('#to-hello').click()
......@@ -401,6 +425,12 @@ const runTests = (isDev = false) => {
source: '/named-like-unnamed/:0',
statusCode: 307,
},
{
destination: '/thank-you-next',
regex: normalizeRegEx('^\\/redirect-override$'),
source: '/redirect-override',
statusCode: 307,
},
],
headers: [
{
......@@ -431,6 +461,18 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/my-headers(?:\\/(.*))$'),
source: '/my-headers/(.*)',
},
{
headers: [
{
key: 'x-something',
value: 'applied-everywhere',
},
],
regex: normalizeRegEx(
'^(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$'
),
source: '/:path*',
},
],
rewrites: [
{
......@@ -438,6 +480,11 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/to-another$'),
source: '/to-another',
},
{
destination: '/404',
regex: '^\\/nav$',
source: '/nav',
},
{
source: '/hello-world',
destination: '/static/hello.txt',
......@@ -526,6 +573,11 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/api-hello-param(?:\\/([^\\/]+?))$'),
source: '/api-hello-param/:name',
},
{
destination: '/with-params',
regex: normalizeRegEx('^(?:\\/([^\\/]+?))\\/post-321$'),
source: '/:path/post-321',
},
],
dynamicRoutes: [
{
......
......@@ -19,7 +19,7 @@ let app
const runTests = () => {
it('should show error for invalid mulit-match', async () => {
await renderViaHTTP(appPort, '/hello')
await renderViaHTTP(appPort, '/random')
expect(stderr).toContain(
'To use a multi-match in the destination you must add'
)
......@@ -27,7 +27,7 @@ const runTests = () => {
})
}
describe('Custom routes', () => {
describe('Custom routes invalid multi-match', () => {
describe('dev mode', () => {
beforeAll(async () => {
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