Commit b9865ba3 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Add checking filesystem after each rewrite (#9568)

* Add check: true behavior to custom routes

* Update adding dev routes

* Add checking of pages and dynamic routes for check: true

* Fix hasPage binding

* Add tests for check: true behavior

* Update regex checking

* Make changes based on review

* Update to handle rewrites in serverless loader

* Update to not change req.url

* Make sure to always parse dynamic route params

* Export all of pathToRegexp from path-match
Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
parent 5c3f9ba7
...@@ -184,6 +184,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -184,6 +184,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
const mappedPages = createPagesMapping(pagePaths, config.pageExtensions) const mappedPages = createPagesMapping(pagePaths, config.pageExtensions)
const entrypoints = createEntrypoints(mappedPages, target, buildId, config) const entrypoints = createEntrypoints(mappedPages, target, buildId, config)
const pageKeys = Object.keys(mappedPages)
const dynamicRoutes = pageKeys.filter(page => isDynamicRoute(page))
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
if (hasPublicDir) { if (hasPublicDir) {
...@@ -216,6 +218,47 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -216,6 +218,47 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
} }
const buildCustomRoute = (
r: {
source: string
statusCode?: number
},
isRedirect = false
) => {
const keys: any[] = []
const routeRegex = pathToRegexp(r.source, keys, {
strict: true,
sensitive: false,
delimiter: '/', // default is `/#?`, but Next does not pass query info
})
return {
...r,
...(isRedirect
? {
statusCode: r.statusCode || DEFAULT_REDIRECT_STATUS,
}
: {}),
regex: routeRegex.source,
regexKeys: keys.map(k => k.name),
}
}
await mkdirp(distDir)
await fsWriteFile(
path.join(distDir, ROUTES_MANIFEST),
JSON.stringify({
version: 1,
redirects: redirects.map(r => buildCustomRoute(r, true)),
rewrites: rewrites.map(r => buildCustomRoute(r)),
dynamicRoutes: getSortedRoutes(dynamicRoutes).map(page => ({
page,
regex: getRouteRegex(page).re.source,
})),
}),
'utf8'
)
const configs = await Promise.all([ const configs = await Promise.all([
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
tracer, tracer,
...@@ -335,7 +378,6 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -335,7 +378,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
prefixText: 'Automatically optimizing pages', prefixText: 'Automatically optimizing pages',
}) })
const pageKeys = Object.keys(mappedPages)
const manifestPath = path.join( const manifestPath = path.join(
distDir, distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY, isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
...@@ -492,7 +534,6 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -492,7 +534,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
await writeBuildId(distDir, buildId) await writeBuildId(distDir, buildId)
const dynamicRoutes = pageKeys.filter(page => isDynamicRoute(page))
if (config.experimental.catchAllRouting !== true) { if (config.experimental.catchAllRouting !== true) {
if (dynamicRoutes.some(page => /\/\[\.{3}[^/]+?\](?=\/|$)/.test(page))) { if (dynamicRoutes.some(page => /\/\[\.{3}[^/]+?\](?=\/|$)/.test(page))) {
throw new Error( throw new Error(
...@@ -638,46 +679,6 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -638,46 +679,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8') await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8')
} }
const buildCustomRoute = (
r: {
source: string
statusCode?: number
},
isRedirect = false
) => {
const keys: any[] = []
const routeRegex = pathToRegexp(r.source, keys, {
strict: true,
sensitive: false,
delimiter: '/', // default is `/#?`, but Next does not pass query info
})
return {
...r,
...(isRedirect
? {
statusCode: r.statusCode || DEFAULT_REDIRECT_STATUS,
}
: {}),
regex: routeRegex.source,
regexKeys: keys.map(k => k.name),
}
}
await fsWriteFile(
path.join(distDir, ROUTES_MANIFEST),
JSON.stringify({
version: 1,
redirects: redirects.map(r => buildCustomRoute(r, true)),
rewrites: rewrites.map(r => buildCustomRoute(r)),
dynamicRoutes: getSortedRoutes(dynamicRoutes).map(page => ({
page,
regex: getRouteRegex(page).re.source,
})),
}),
'utf8'
)
if (postBuildSpinner) postBuildSpinner.stopAndPersist() if (postBuildSpinner) postBuildSpinner.stopAndPersist()
console.log() console.log()
......
...@@ -3,6 +3,7 @@ import { join } from 'path' ...@@ -3,6 +3,7 @@ import { join } from 'path'
import { parse } from 'querystring' import { parse } from 'querystring'
import { import {
BUILD_MANIFEST, BUILD_MANIFEST,
ROUTES_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
} from '../../../next-server/lib/constants' } from '../../../next-server/lib/constants'
import { isDynamicRoute } from '../../../next-server/lib/router/utils' import { isDynamicRoute } from '../../../next-server/lib/router/utils'
...@@ -42,33 +43,107 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -42,33 +43,107 @@ const nextServerlessLoader: loader.Loader = function() {
/\\/g, /\\/g,
'/' '/'
) )
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')
const escapedBuildId = buildId.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') const escapedBuildId = buildId.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&')
const pageIsDynamicRoute = isDynamicRoute(page)
if (page.match(API_ROUTE)) { const dynamicRouteImports = pageIsDynamicRoute
return ` ? `
${ import { getRouteMatcher } from 'next/dist/next-server/lib/router/utils/route-matcher';
isDynamicRoute(page)
? `
import { getRouteMatcher } from 'next/dist/next-server/lib/router/utils/route-matcher';
import { getRouteRegex } from 'next/dist/next-server/lib/router/utils/route-regex'; import { getRouteRegex } from 'next/dist/next-server/lib/router/utils/route-regex';
` `
: `` : ''
const dynamicRouteMatcher = pageIsDynamicRoute
? `
const dynamicRouteMatcher = getRouteMatcher(getRouteRegex("${page}"))
`
: ''
const rewriteImports = `
import { rewrites } from '${routesManifest}'
import pathMatch, { pathToRegexp } from 'next/dist/next-server/server/lib/path-match'
`
const handleRewrites = `
const getCustomRouteMatcher = pathMatch(true)
function handleRewrites(parsedUrl) {
for (const rewrite of rewrites) {
const matcher = getCustomRouteMatcher(rewrite.source)
const params = matcher(parsedUrl.pathname)
if (params) {
parsedUrl.query = {
...parsedUrl.query,
...params
}
const parsedDest = parse(rewrite.destination)
const destCompiler = pathToRegexp.compile(
\`\${parsedDest.pathname}\${parsedDest.hash || ''}\`
)
const newUrl = destCompiler(params)
const parsedNewUrl = parse(newUrl)
parsedUrl.pathname = parsedNewUrl.pathname
parsedUrl.hash = parsedNewUrl.hash
if (parsedUrl.pathname === '${page}'){
break
}
${
pageIsDynamicRoute
? `
const dynamicParams = dynamicRouteMatcher(parsedUrl.pathname);\
if (dynamicParams) {
parsedUrl.query = {
...parsedUrl.query,
...dynamicParams
}
break
}
`
: ''
}
}
}
return parsedUrl
} }
`
if (page.match(API_ROUTE)) {
return `
${dynamicRouteImports}
import { parse } from 'url' import { parse } from 'url'
import { apiResolver } from 'next/dist/next-server/server/api-utils' import { apiResolver } from 'next/dist/next-server/server/api-utils'
import initServer from 'next-plugin-loader?middleware=on-init-server!' import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
${rewriteImports}
${dynamicRouteMatcher}
${handleRewrites}
export default async (req, res) => { export default async (req, res) => {
try { try {
await initServer() await initServer()
const parsedUrl = parse(req.url, true)
const params = ${ const params = ${
isDynamicRoute(page) pageIsDynamicRoute
? `getRouteMatcher(getRouteRegex('${page}'))(parse(req.url).pathname)` ? `dynamicRouteMatcher(parsedUrl.pathname)`
: `{}` : `{}`
} }
const resolver = require('${absolutePagePath}') const resolver = require('${absolutePagePath}')
apiResolver(req, res, params, resolver, onError) apiResolver(
req,
res,
Object.assign({}, parsedUrl.query, params ),
resolver,
onError
)
} catch (err) { } catch (err) {
console.error(err) console.error(err)
await onError(err) await onError(err)
...@@ -85,23 +160,24 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -85,23 +160,24 @@ const nextServerlessLoader: loader.Loader = function() {
import {sendHTML} from 'next/dist/next-server/server/send-html'; import {sendHTML} from 'next/dist/next-server/server/send-html';
import initServer from 'next-plugin-loader?middleware=on-init-server!' import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
${
isDynamicRoute(page)
? `import {getRouteMatcher, getRouteRegex} from 'next/dist/next-server/lib/router/utils';`
: ''
}
import buildManifest from '${buildManifest}'; import buildManifest from '${buildManifest}';
import reactLoadableManifest from '${reactLoadableManifest}'; import reactLoadableManifest from '${reactLoadableManifest}';
import Document from '${absoluteDocumentPath}'; import Document from '${absoluteDocumentPath}';
import Error from '${absoluteErrorPath}'; import Error from '${absoluteErrorPath}';
import App from '${absoluteAppPath}'; import App from '${absoluteAppPath}';
import * as ComponentInfo from '${absolutePagePath}'; import * as ComponentInfo from '${absolutePagePath}';
${dynamicRouteImports}
${rewriteImports}
const Component = ComponentInfo.default const Component = ComponentInfo.default
export default Component export default Component
export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's'] export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's']
export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's'] export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's']
export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's'] export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's']
${dynamicRouteMatcher}
${handleRewrites}
export const config = ComponentInfo['confi' + 'g'] || {} export const config = ComponentInfo['confi' + 'g'] || {}
export const _app = App export const _app = App
export async function renderReqToHTML(req, res, fromExport, _renderOpts, _params) { export async function renderReqToHTML(req, res, fromExport, _renderOpts, _params) {
...@@ -127,7 +203,8 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -127,7 +203,8 @@ const nextServerlessLoader: loader.Loader = function() {
.replace(new RegExp('/_next/data/${escapedBuildId}/'), '/') .replace(new RegExp('/_next/data/${escapedBuildId}/'), '/')
.replace(/\\.json$/, '') .replace(/\\.json$/, '')
} }
const parsedUrl = parse(req.url, true) const parsedUrl = handleRewrites(parse(req.url, true))
const renderOpts = Object.assign( const renderOpts = Object.assign(
{ {
Component, Component,
...@@ -140,8 +217,8 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -140,8 +217,8 @@ const nextServerlessLoader: loader.Loader = function() {
try { try {
${page === '/_error' ? `res.statusCode = 404` : ''} ${page === '/_error' ? `res.statusCode = 404` : ''}
${ ${
isDynamicRoute(page) pageIsDynamicRoute
? `const params = fromExport && !unstable_getStaticProps ? {} : getRouteMatcher(getRouteRegex("${page}"))(parsedUrl.pathname) || {};` ? `const params = fromExport && !unstable_getStaticProps ? {} : dynamicRouteMatcher(parsedUrl.pathname) || {};`
: `const params = {};` : `const params = {};`
} }
${ ${
...@@ -150,7 +227,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -150,7 +227,7 @@ const nextServerlessLoader: loader.Loader = function() {
// into our builder to ensure we're decoupled. However, this entails // into our builder to ensure we're decoupled. However, this entails
// removing reliance on `req.url` and using `req.query` instead // removing reliance on `req.url` and using `req.query` instead
// (which is needed for "custom routes" anyway). // (which is needed for "custom routes" anyway).
isDynamicRoute(page) pageIsDynamicRoute
? `const nowParams = req.headers && req.headers["x-now-route-matches"] ? `const nowParams = req.headers && req.headers["x-now-route-matches"]
? getRouteMatcher( ? getRouteMatcher(
(function() { (function() {
......
import { match } from 'path-to-regexp' import * as pathToRegexp from 'path-to-regexp'
export { pathToRegexp }
export default (customRoute = false) => { export default (customRoute = false) => {
return (path: string) => { return (path: string) => {
const matcher = match(path, { const matcher = pathToRegexp.match(path, {
sensitive: false, sensitive: false,
delimiter: '/', delimiter: '/',
...(customRoute ? { strict: true } : undefined), ...(customRoute ? { strict: true } : undefined),
......
...@@ -34,7 +34,13 @@ import { recursiveReadDirSync } from './lib/recursive-readdir-sync' ...@@ -34,7 +34,13 @@ import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components' import { loadComponents, LoadComponentsReturnType } from './load-components'
import { renderToHTML } from './render' import { renderToHTML } from './render'
import { getPagePath } from './require' import { getPagePath } from './require'
import Router, { Params, route, Route, RouteMatch } from './router' import Router, {
Params,
route,
Route,
DynamicRoutes,
PageChecker,
} from './router'
import { sendHTML } from './send-html' import { sendHTML } from './send-html'
import { serveStatic } from './serve-static' import { serveStatic } from './serve-static'
import { getSprCache, initializeSprCache, setSprCache } from './spr-cache' import { getSprCache, initializeSprCache, setSprCache } from './spr-cache'
...@@ -95,7 +101,7 @@ export default class Server { ...@@ -95,7 +101,7 @@ export default class Server {
private compression?: Middleware private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void> private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
router: Router router: Router
protected dynamicRoutes?: Array<{ page: string; match: RouteMatch }> protected dynamicRoutes?: DynamicRoutes
protected customRoutes?: { protected customRoutes?: {
rewrites: Rewrite[] rewrites: Rewrite[]
redirects: Redirect[] redirects: Redirect[]
...@@ -256,7 +262,13 @@ export default class Server { ...@@ -256,7 +262,13 @@ export default class Server {
return require(join(this.distDir, ROUTES_MANIFEST)) return require(join(this.distDir, ROUTES_MANIFEST))
} }
protected generateRoutes(): Route[] { protected generateRoutes(): {
routes: Route[]
fsRoutes: Route[]
catchAllRoute: Route
pageChecker: PageChecker
dynamicRoutes: DynamicRoutes | undefined
} {
this.customRoutes = this.getCustomRoutes() this.customRoutes = this.getCustomRoutes()
const publicRoutes = fs.existsSync(this.publicDir) const publicRoutes = fs.existsSync(this.publicDir)
...@@ -283,7 +295,7 @@ export default class Server { ...@@ -283,7 +295,7 @@ export default class Server {
] ]
: [] : []
const topRoutes: Route[] = [ const fsRoutes: Route[] = [
{ {
match: route('/_next/static/:path*'), match: route('/_next/static/:path*'),
type: 'route', type: 'route',
...@@ -377,7 +389,7 @@ export default class Server { ...@@ -377,7 +389,7 @@ export default class Server {
...publicRoutes, ...publicRoutes,
...staticFilesRoute, ...staticFilesRoute,
] ]
const routes: Route[] = [...topRoutes] const routes: Route[] = []
if (this.customRoutes) { if (this.customRoutes) {
const { redirects, rewrites } = this.customRoutes const { redirects, rewrites } = this.customRoutes
...@@ -399,6 +411,7 @@ export default class Server { ...@@ -399,6 +411,7 @@ export default class Server {
routes.push( routes.push(
...customRoutes.map(route => { ...customRoutes.map(route => {
return { return {
check: true,
match: route.matcher, match: route.matcher,
type: route.type, type: route.type,
statusCode: route.statusCode, statusCode: route.statusCode,
...@@ -450,27 +463,42 @@ export default class Server { ...@@ -450,27 +463,42 @@ export default class Server {
} as Route } as Route
}) })
) )
// make sure previous routes can still be rewritten to by
// custom routes e.g. /docs/_next/static -> /_next/static
routes.push(...topRoutes)
} }
routes.push({ const catchAllRoute: Route = {
match: route('/api/:path*'), match: route('/:path*'),
type: 'route', type: 'route',
name: 'API Route', name: 'Catchall render',
fn: async (req, res, params, parsedUrl) => { fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl const { pathname, query } = parsedUrl
await this.handleApiRequest( if (!pathname) {
req as NextApiRequest, throw new Error('pathname is undefined')
res as NextApiResponse, }
pathname!
) // Used in development to check public directory paths
if (await this._beforeCatchAllRender(req, res, params, parsedUrl)) {
return {
finished: true,
}
}
if (params && params.path && params.path[0] === 'api') {
const handled = await this.handleApiRequest(
req as NextApiRequest,
res as NextApiResponse,
pathname!
)
if (handled) {
return { finished: true }
}
}
await this.render(req, res, pathname, query, parsedUrl)
return { return {
finished: true, finished: true,
} }
}, },
}) }
if (this.nextConfig.useFileSystemPublicRoutes) { if (this.nextConfig.useFileSystemPublicRoutes) {
this.dynamicRoutes = this.getDynamicRoutes() this.dynamicRoutes = this.getDynamicRoutes()
...@@ -479,32 +507,16 @@ export default class Server { ...@@ -479,32 +507,16 @@ export default class Server {
// (but it should support as many params as needed, separated by '/') // (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack. // Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617 // See more: https://github.com/zeit/next.js/issues/2617
routes.push({ routes.push(catchAllRoute)
match: route('/:path*'),
type: 'route',
name: 'Catchall render',
fn: async (req, res, params, parsedUrl) => {
const { pathname, query } = 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,
}
}
await this.render(req, res, pathname, query, parsedUrl)
return {
finished: true,
}
},
})
} }
return routes return {
routes,
fsRoutes,
catchAllRoute,
dynamicRoutes: this.dynamicRoutes,
pageChecker: this.hasPage.bind(this),
}
} }
private async getPagePath(pathname: string) { private async getPagePath(pathname: string) {
...@@ -564,7 +576,7 @@ export default class Server { ...@@ -564,7 +576,7 @@ export default class Server {
} }
if (!pageFound) { if (!pageFound) {
return this.render404(req, res) return false
} }
// Make sure the page is built before getting the path // Make sure the page is built before getting the path
// or else it won't be in the manifest yet // or else it won't be in the manifest yet
...@@ -575,11 +587,13 @@ export default class Server { ...@@ -575,11 +587,13 @@ export default class Server {
if (!this.renderOpts.dev && this._isLikeServerless) { if (!this.renderOpts.dev && this._isLikeServerless) {
if (typeof pageModule.default === 'function') { if (typeof pageModule.default === 'function') {
return pageModule.default(req, res) await pageModule.default(req, res)
return true
} }
} }
await apiResolver(req, res, params, pageModule, this.onErrorMiddleware) await apiResolver(req, res, params, pageModule, this.onErrorMiddleware)
return true
} }
protected generatePublicRoutes(): Route[] { protected generatePublicRoutes(): Route[] {
......
...@@ -16,6 +16,7 @@ type RouteResult = { ...@@ -16,6 +16,7 @@ type RouteResult = {
export type Route = { export type Route = {
match: RouteMatch match: RouteMatch
type: string type: string
check?: boolean
statusCode?: number statusCode?: number
name: string name: string
fn: ( fn: (
...@@ -26,10 +27,39 @@ export type Route = { ...@@ -26,10 +27,39 @@ export type Route = {
) => Promise<RouteResult> | RouteResult ) => Promise<RouteResult> | RouteResult
} }
export type DynamicRoutes = Array<{ page: string; match: RouteMatch }>
export type PageChecker = (pathname: string) => Promise<boolean>
export default class Router { export default class Router {
routes: Route[] routes: Route[]
constructor(routes: Route[] = []) { fsRoutes: Route[]
catchAllRoute: Route
pageChecker: PageChecker
dynamicRoutes: DynamicRoutes
constructor({
routes = [],
fsRoutes = [],
catchAllRoute,
dynamicRoutes = [],
pageChecker,
}: {
routes: Route[]
fsRoutes: Route[]
catchAllRoute: Route
dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker
}) {
this.routes = routes this.routes = routes
this.fsRoutes = fsRoutes
this.pageChecker = pageChecker
this.catchAllRoute = catchAllRoute
this.dynamicRoutes = dynamicRoutes
}
setDynamicRoutes(routes: DynamicRoutes = []) {
this.dynamicRoutes = routes
} }
add(route: Route) { add(route: Route) {
...@@ -41,8 +71,20 @@ export default class Router { ...@@ -41,8 +71,20 @@ export default class Router {
res: ServerResponse, res: ServerResponse,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
): Promise<boolean> { ): Promise<boolean> {
// memoize page check calls so we don't duplicate checks for pages
const pageChecks: { [name: string]: boolean } = {}
const memoizedPageChecker = async (p: string): Promise<boolean> => {
if (pageChecks[p]) {
return pageChecks[p]
}
const result = await this.pageChecker(p)
pageChecks[p] = result
return result
}
let parsedUrlUpdated = parsedUrl let parsedUrlUpdated = parsedUrl
for (const route of this.routes) {
for (const route of [...this.fsRoutes, ...this.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
...@@ -62,6 +104,54 @@ export default class Router { ...@@ -62,6 +104,54 @@ export default class Router {
if (result.pathname) { if (result.pathname) {
parsedUrlUpdated.pathname = result.pathname parsedUrlUpdated.pathname = result.pathname
} }
// check filesystem
if (route.check === true) {
for (const fsRoute of this.fsRoutes) {
const fsParams = fsRoute.match(parsedUrlUpdated.pathname)
if (fsParams) {
const result = await fsRoute.fn(
req,
res,
fsParams,
parsedUrlUpdated
)
if (result.finished) {
return true
}
}
}
let matchedPage = await memoizedPageChecker(
parsedUrlUpdated.pathname!
)
// If we didn't match a page check dynamic routes
if (!matchedPage) {
for (const dynamicRoute of this.dynamicRoutes) {
if (dynamicRoute.match(parsedUrlUpdated.pathname)) {
matchedPage = true
}
}
}
// Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) {
const pageParams = this.catchAllRoute.match(
parsedUrlUpdated.pathname
)
await this.catchAllRoute.fn(
req,
res,
pageParams as Params,
parsedUrlUpdated
)
return true
}
}
} }
} }
......
...@@ -21,7 +21,7 @@ import { ...@@ -21,7 +21,7 @@ import {
} from '../next-server/lib/router/utils' } from '../next-server/lib/router/utils'
import Server, { ServerConstructor } from '../next-server/server/next-server' import Server, { ServerConstructor } from '../next-server/server/next-server'
import { normalizePagePath } from '../next-server/server/normalize-page-path' import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { route, Params } from '../next-server/server/router' import Router, { route, Params } from '../next-server/server/router'
import { eventVersion } from '../telemetry/events' import { eventVersion } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import ErrorDebug from './error-debug' import ErrorDebug from './error-debug'
...@@ -186,6 +186,7 @@ export default class DevServer extends Server { ...@@ -186,6 +186,7 @@ export default class DevServer extends Server {
page, page,
match: getRouteMatcher(getRouteRegex(page)), match: getRouteMatcher(getRouteRegex(page)),
})) }))
this.router.setDynamicRoutes(this.dynamicRoutes)
if (!resolved) { if (!resolved) {
resolve() resolve()
...@@ -212,8 +213,7 @@ export default class DevServer extends Server { ...@@ -212,8 +213,7 @@ export default class DevServer extends Server {
const { redirects, rewrites } = this.customRoutes const { redirects, rewrites } = this.customRoutes
if (redirects.length || rewrites.length) { if (redirects.length || rewrites.length) {
// TODO: don't reach into router instance this.router = new Router(this.generateRoutes())
this.router.routes = this.generateRoutes()
} }
} }
...@@ -330,11 +330,17 @@ export default class DevServer extends Server { ...@@ -330,11 +330,17 @@ export default class DevServer extends Server {
} }
generateRoutes() { generateRoutes() {
const routes = super.generateRoutes() const {
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
routes.unshift({ fsRoutes.unshift({
match: route('/_next/development/:path*'), match: route('/_next/development/:path*'),
type: 'route', type: 'route',
name: '_next/development catchall', name: '_next/development catchall',
...@@ -347,7 +353,7 @@ export default class DevServer extends Server { ...@@ -347,7 +353,7 @@ export default class DevServer extends Server {
}, },
}) })
return routes return { routes, fsRoutes, catchAllRoute, dynamicRoutes, pageChecker }
} }
// 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
......
...@@ -23,6 +23,14 @@ module.exports = { ...@@ -23,6 +23,14 @@ module.exports = {
source: '/second', source: '/second',
destination: '/hello-again', destination: '/hello-again',
}, },
{
source: '/to-hello',
destination: '/hello',
},
{
source: '/blog/post-1',
destination: '/blog/post-2',
},
{ {
source: '/test/:path', source: '/test/:path',
destination: '/:path', destination: '/:path',
...@@ -35,6 +43,10 @@ module.exports = { ...@@ -35,6 +43,10 @@ module.exports = {
source: '/params/:something', source: '/params/:something',
destination: '/with-params', destination: '/with-params',
}, },
{
source: '/hidden/_next/:path*',
destination: '/_next/:path*',
},
] ]
}, },
async redirects() { async redirects() {
......
import { useRouter } from 'next/router'
const Page = () => (
<>
<p>post: {useRouter().query.post}</p>
</>
)
Page.getInitialProps = () => ({ hello: 'world' })
export default Page
import Link from 'next/link' import Link from 'next/link'
export default () => ( const Page = () => (
<> <>
<h3 id="hello">Hello</h3> <h3 id="hello">Hello</h3>
<Link href="/nav"> <Link href="/nav">
...@@ -8,3 +8,7 @@ export default () => ( ...@@ -8,3 +8,7 @@ export default () => (
</Link> </Link>
</> </>
) )
Page.getInitialProps = () => ({ hello: 'world' })
export default Page
...@@ -23,6 +23,7 @@ jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2 ...@@ -23,6 +23,7 @@ jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
let appDir = join(__dirname, '..') let appDir = join(__dirname, '..')
const nextConfigPath = join(appDir, 'next.config.js') const nextConfigPath = join(appDir, 'next.config.js')
let nextConfigContent let nextConfigContent
let buildId
let stdout = '' let stdout = ''
let appPort let appPort
let app let app
...@@ -152,6 +153,31 @@ const runTests = (isDev = false) => { ...@@ -152,6 +153,31 @@ const runTests = (isDev = false) => {
expect(await getBrowserBodyText(browser)).toMatch(/Hello again/) expect(await getBrowserBodyText(browser)).toMatch(/Hello again/)
}) })
it('should match a page after a rewrite', async () => {
const html = await renderViaHTTP(appPort, '/to-hello')
expect(html).toContain('Hello')
})
it('should match dynamic route after rewrite', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
expect(html).toMatch(/post:.*?post-2/)
})
it('should match public file after rewrite', async () => {
const data = await renderViaHTTP(appPort, '/blog/data.json')
expect(JSON.parse(data)).toEqual({ hello: 'world' })
})
it('should match /_next file after rewrite', async () => {
await renderViaHTTP(appPort, '/hello')
const data = await renderViaHTTP(
appPort,
`/hidden/_next/static/${buildId}/pages/hello.js`
)
expect(data).toContain('Hello')
expect(data).toContain('createElement')
})
it('should allow redirecting to external resource', async () => { it('should allow redirecting to external resource', async () => {
const res = await fetchViaHTTP(appPort, '/to-external', undefined, { const res = await fetchViaHTTP(appPort, '/to-external', undefined, {
redirect: 'manual', redirect: 'manual',
...@@ -166,6 +192,11 @@ const runTests = (isDev = false) => { ...@@ -166,6 +192,11 @@ const runTests = (isDev = false) => {
const manifest = await fs.readJSON( const manifest = await fs.readJSON(
join(appDir, '.next/routes-manifest.json') join(appDir, '.next/routes-manifest.json')
) )
for (const route of manifest.dynamicRoutes) {
route.regex = normalizeRegEx(route.regex)
}
expect(manifest).toEqual({ expect(manifest).toEqual({
version: 1, version: 1,
redirects: [ redirects: [
...@@ -285,6 +316,18 @@ const runTests = (isDev = false) => { ...@@ -285,6 +316,18 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/second$'), regex: normalizeRegEx('^\\/second$'),
regexKeys: [], regexKeys: [],
}, },
{
destination: '/hello',
regex: normalizeRegEx('^\\/to-hello$'),
regexKeys: [],
source: '/to-hello',
},
{
destination: '/blog/post-2',
regex: normalizeRegEx('^\\/blog\\/post-1$'),
regexKeys: [],
source: '/blog/post-1',
},
{ {
source: '/test/:path', source: '/test/:path',
destination: '/:path', destination: '/:path',
...@@ -305,8 +348,21 @@ const runTests = (isDev = false) => { ...@@ -305,8 +348,21 @@ const runTests = (isDev = false) => {
regex: normalizeRegEx('^\\/params(?:\\/([^\\/]+?))$'), regex: normalizeRegEx('^\\/params(?:\\/([^\\/]+?))$'),
regexKeys: ['something'], regexKeys: ['something'],
}, },
{
destination: '/_next/:path*',
regex: normalizeRegEx(
'^\\/hidden\\/_next(?:\\/((?:[^\\/]+?)(?:\\/(?:[^\\/]+?))*))?$'
),
regexKeys: ['path'],
source: '/hidden/_next/:path*',
},
],
dynamicRoutes: [
{
page: '/blog/[post]',
regex: normalizeRegEx('^\\/blog\\/([^/]+?)(?:\\/)?$'),
},
], ],
dynamicRoutes: [],
}) })
}) })
...@@ -321,7 +377,7 @@ const runTests = (isDev = false) => { ...@@ -321,7 +377,7 @@ const runTests = (isDev = false) => {
for (const route of [...manifest.redirects, ...manifest.rewrites]) { for (const route of [...manifest.redirects, ...manifest.rewrites]) {
expect(cleanStdout).toMatch( expect(cleanStdout).toMatch(
new RegExp(`${route.source}.*?${route.destination}`) new RegExp(`${route}.*?${route.destination}`)
) )
} }
}) })
...@@ -333,6 +389,7 @@ describe('Custom routes', () => { ...@@ -333,6 +389,7 @@ describe('Custom routes', () => {
beforeAll(async () => { beforeAll(async () => {
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort) app = await launchApp(appDir, appPort)
buildId = 'development'
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests(true) runTests(true)
...@@ -346,6 +403,7 @@ describe('Custom routes', () => { ...@@ -346,6 +403,7 @@ describe('Custom routes', () => {
stdout = buildStdout stdout = buildStdout
appPort = await findPort() appPort = await findPort()
app = await nextStart(appDir, appPort) app = await nextStart(appDir, appPort)
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests()
...@@ -369,6 +427,7 @@ describe('Custom routes', () => { ...@@ -369,6 +427,7 @@ describe('Custom routes', () => {
stdout += msg stdout += msg
}, },
}) })
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
afterAll(async () => { afterAll(async () => {
await killApp(app) await killApp(app)
......
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