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

Add basePath in link component and add/remove it consistently (#9988)

* Add basePath in link component and add/remove it consistently

* Update to not use regex for delBasePath

* Expose addBasePath as router method

* Revert "Expose addBasePath as router method"

This reverts commit 40fed596195c6affabf837e42d472452768e13a3.

* Expose basePath as router field

* Apply suggestion

* Expose basePath as router field

* remove un-used vars

* Update externals

* Apply lint fix

* Update size-limit test

* Update prefetch
parent 0b51b234
...@@ -540,7 +540,12 @@ export default async function getBaseWebpackConfig( ...@@ -540,7 +540,12 @@ export default async function getBaseWebpackConfig(
let isNextExternal: boolean = false let isNextExternal: boolean = false
if (isLocal) { if (isLocal) {
isNextExternal = /next[/\\]dist[/\\]next-server[/\\]/.test(res) // we need to process next-server/lib/router/router so that
// the DefinePlugin can inject process.env values
isNextExternal = /next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/.test(
res
)
if (!isNextExternal) { if (!isNextExternal) {
return callback() return callback()
} }
......
...@@ -266,6 +266,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -266,6 +266,7 @@ const nextServerlessLoader: loader.Loader = function() {
runtimeConfig: runtimeConfig.publicRuntimeConfig || {}, runtimeConfig: runtimeConfig.publicRuntimeConfig || {},
previewProps: ${encodedPreviewProps}, previewProps: ${encodedPreviewProps},
env: process.env, env: process.env,
basePath: "${basePath}",
..._renderOpts ..._renderOpts
} }
let _nextData = false let _nextData = false
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
getLocationOrigin, getLocationOrigin,
} from '../next-server/lib/utils' } from '../next-server/lib/utils'
import Router from './router' import Router from './router'
import { addBasePath } from '../next-server/lib/router/router'
function isLocal(href: string) { function isLocal(href: string) {
const url = parse(href, false, true) const url = parse(href, false, true)
...@@ -161,8 +162,8 @@ class Link extends Component<LinkProps> { ...@@ -161,8 +162,8 @@ class Link extends Component<LinkProps> {
// as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html // as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
formatUrls = memoizedFormatUrl((href, asHref) => { formatUrls = memoizedFormatUrl((href, asHref) => {
return { return {
href: formatUrl(href), href: addBasePath(formatUrl(href)),
as: asHref ? formatUrl(asHref) : asHref, as: asHref ? addBasePath(formatUrl(asHref)) : asHref,
} }
}) })
......
...@@ -36,6 +36,7 @@ const urlPropertyFields = [ ...@@ -36,6 +36,7 @@ const urlPropertyFields = [
'asPath', 'asPath',
'components', 'components',
'isFallback', 'isFallback',
'basePath',
] ]
const routerEvents = [ const routerEvents = [
'routeChangeStart', 'routeChangeStart',
......
...@@ -238,6 +238,7 @@ export default async function( ...@@ -238,6 +238,7 @@ export default async function(
dev: false, dev: false,
staticMarkup: false, staticMarkup: false,
hotReloader: null, hotReloader: null,
basePath: nextConfig.experimental.basePath,
canonicalBase: nextConfig.amp?.canonicalBase || '', canonicalBase: nextConfig.amp?.canonicalBase || '',
isModern: nextConfig.experimental.modern, isModern: nextConfig.experimental.modern,
ampValidatorPath: nextConfig.experimental.amp?.validator || undefined, ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
......
...@@ -16,10 +16,16 @@ import { isDynamicRoute } from './utils/is-dynamic' ...@@ -16,10 +16,16 @@ import { isDynamicRoute } from './utils/is-dynamic'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
function addBasePath(path: string): string { const basePath = process.env.__NEXT_ROUTER_BASEPATH as string
// variable is always a string
const p = process.env.__NEXT_ROUTER_BASEPATH as string export function addBasePath(path: string): string {
return path.indexOf(p) !== 0 ? p + path : path return path.indexOf(basePath) !== 0 ? basePath + path : path
}
function delBasePath(path: string): string {
return path.indexOf(basePath) === 0
? path.substr(basePath.length) || '/'
: path
} }
function toRoute(path: string): string { function toRoute(path: string): string {
...@@ -38,6 +44,7 @@ export type BaseRouter = { ...@@ -38,6 +44,7 @@ export type BaseRouter = {
pathname: string pathname: string
query: ParsedUrlQuery query: ParsedUrlQuery
asPath: string asPath: string
basePath: string
} }
export type NextRouter = BaseRouter & export type NextRouter = BaseRouter &
...@@ -133,6 +140,8 @@ export default class Router implements BaseRouter { ...@@ -133,6 +140,8 @@ export default class Router implements BaseRouter {
pathname: string pathname: string
query: ParsedUrlQuery query: ParsedUrlQuery
asPath: string asPath: string
basePath: string
/** /**
* Map of all components loaded in `Router` * Map of all components loaded in `Router`
*/ */
...@@ -206,6 +215,7 @@ export default class Router implements BaseRouter { ...@@ -206,6 +215,7 @@ export default class Router implements BaseRouter {
this.asPath = this.asPath =
// @ts-ignore this is temporarily global (attached to window) // @ts-ignore this is temporarily global (attached to window)
isDynamicRoute(pathname) && __NEXT_DATA__.autoExport ? pathname : as isDynamicRoute(pathname) && __NEXT_DATA__.autoExport ? pathname : as
this.basePath = basePath
this.sub = subscription this.sub = subscription
this.clc = null this.clc = null
this._wrapApp = wrapApp this._wrapApp = wrapApp
...@@ -361,9 +371,12 @@ export default class Router implements BaseRouter { ...@@ -361,9 +371,12 @@ export default class Router implements BaseRouter {
// If url and as provided as an object representation, // If url and as provided as an object representation,
// we'll format them into the string version here. // we'll format them into the string version here.
const url = typeof _url === 'object' ? formatWithValidation(_url) : _url let url = typeof _url === 'object' ? formatWithValidation(_url) : _url
let as = typeof _as === 'object' ? formatWithValidation(_as) : _as let as = typeof _as === 'object' ? formatWithValidation(_as) : _as
url = addBasePath(url)
as = addBasePath(as)
// Add the ending slash to the paths. So, we can serve the // Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly for the SSR page. // "<page>/index.html" directly for the SSR page.
if (process.env.__NEXT_EXPORT_TRAILING_SLASH) { if (process.env.__NEXT_EXPORT_TRAILING_SLASH) {
...@@ -386,7 +399,7 @@ export default class Router implements BaseRouter { ...@@ -386,7 +399,7 @@ export default class Router implements BaseRouter {
if (!options._h && this.onlyAHashChange(as)) { if (!options._h && this.onlyAHashChange(as)) {
this.asPath = as this.asPath = as
Router.events.emit('hashChangeStart', as) Router.events.emit('hashChangeStart', as)
this.changeState(method, url, addBasePath(as), options) this.changeState(method, url, as, options)
this.scrollToHash(as) this.scrollToHash(as)
Router.events.emit('hashChangeComplete', as) Router.events.emit('hashChangeComplete', as)
return resolve(true) return resolve(true)
...@@ -458,7 +471,7 @@ export default class Router implements BaseRouter { ...@@ -458,7 +471,7 @@ export default class Router implements BaseRouter {
} }
Router.events.emit('beforeHistoryChange', as) Router.events.emit('beforeHistoryChange', as)
this.changeState(method, url, addBasePath(as), options) this.changeState(method, url, as, options)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const appComp: any = this.components['/_app'].Component const appComp: any = this.components['/_app'].Component
...@@ -737,12 +750,10 @@ export default class Router implements BaseRouter { ...@@ -737,12 +750,10 @@ export default class Router implements BaseRouter {
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
return return
} }
const route = delBasePath(toRoute(pathname))
Promise.all([ Promise.all([
this.pageLoader.prefetchData(url, asPath), this.pageLoader.prefetchData(url, delBasePath(asPath)),
this.pageLoader[options.priority ? 'loadPage' : 'prefetch']( this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),
toRoute(pathname)
),
]).then(() => resolve(), reject) ]).then(() => resolve(), reject)
}) })
} }
...@@ -752,6 +763,7 @@ export default class Router implements BaseRouter { ...@@ -752,6 +763,7 @@ export default class Router implements BaseRouter {
const cancel = (this.clc = () => { const cancel = (this.clc = () => {
cancelled = true cancelled = true
}) })
route = delBasePath(route)
const componentResult = await this.pageLoader.loadPage(route) const componentResult = await this.pageLoader.loadPage(route)
......
...@@ -123,6 +123,7 @@ export default class Server { ...@@ -123,6 +123,7 @@ export default class Server {
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
customServer?: boolean customServer?: boolean
ampOptimizerConfig?: { [key: string]: any } ampOptimizerConfig?: { [key: string]: any }
basePath: string
} }
private compression?: Middleware private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void> private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
...@@ -179,6 +180,7 @@ export default class Server { ...@@ -179,6 +180,7 @@ export default class Server {
previewProps: this.getPreviewProps(), previewProps: this.getPreviewProps(),
customServer: customServer === true ? true : undefined, customServer: customServer === true ? true : undefined,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.experimental.basePath,
} }
// Only the `publicRuntimeConfig` key is exposed to the client side // Only the `publicRuntimeConfig` key is exposed to the client side
...@@ -265,14 +267,15 @@ export default class Server { ...@@ -265,14 +267,15 @@ export default class Server {
parsedUrl.query = parseQs(parsedUrl.query) parsedUrl.query = parseQs(parsedUrl.query)
} }
if (parsedUrl.pathname!.startsWith(this.nextConfig.experimental.basePath)) { const { basePath } = this.nextConfig.experimental
// if basePath is set require it be present
if (basePath && !req.url!.startsWith(basePath)) {
return this.render404(req, res, parsedUrl)
} else {
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/` // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
parsedUrl.pathname = parsedUrl.pathname = parsedUrl.pathname!.replace(basePath, '') || '/'
parsedUrl.pathname!.replace( req.url = req.url!.replace(basePath, '')
this.nextConfig.experimental.basePath,
''
) || '/'
req.url = req.url!.replace(this.nextConfig.experimental.basePath, '')
} }
res.statusCode = 200 res.statusCode = 200
......
...@@ -54,6 +54,7 @@ class ServerRouter implements NextRouter { ...@@ -54,6 +54,7 @@ class ServerRouter implements NextRouter {
pathname: string pathname: string
query: ParsedUrlQuery query: ParsedUrlQuery
asPath: string asPath: string
basePath: string
events: any events: any
isFallback: boolean isFallback: boolean
// TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method // TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method
...@@ -63,14 +64,15 @@ class ServerRouter implements NextRouter { ...@@ -63,14 +64,15 @@ class ServerRouter implements NextRouter {
pathname: string, pathname: string,
query: ParsedUrlQuery, query: ParsedUrlQuery,
as: string, as: string,
{ isFallback }: { isFallback: boolean } { isFallback }: { isFallback: boolean },
basePath: string
) { ) {
this.route = pathname.replace(/\/$/, '') || '/' this.route = pathname.replace(/\/$/, '') || '/'
this.pathname = pathname this.pathname = pathname
this.query = query this.query = query
this.asPath = as this.asPath = as
this.isFallback = isFallback this.isFallback = isFallback
this.basePath = basePath
} }
push(): any { push(): any {
noRouter() noRouter()
...@@ -156,6 +158,7 @@ export type RenderOptsPartial = { ...@@ -156,6 +158,7 @@ export type RenderOptsPartial = {
isDataReq?: boolean isDataReq?: boolean
params?: ParsedUrlQuery params?: ParsedUrlQuery
previewProps: __ApiPreviewProps previewProps: __ApiPreviewProps
basePath: string
} }
export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
...@@ -309,6 +312,7 @@ export async function renderToHTML( ...@@ -309,6 +312,7 @@ export async function renderToHTML(
isDataReq, isDataReq,
params, params,
previewProps, previewProps,
basePath,
} = renderOpts } = renderOpts
const callMiddleware = async (method: string, args: any[], props = false) => { const callMiddleware = async (method: string, args: any[], props = false) => {
...@@ -452,10 +456,16 @@ export async function renderToHTML( ...@@ -452,10 +456,16 @@ export async function renderToHTML(
await Loadable.preloadAll() // Make sure all dynamic imports are loaded await Loadable.preloadAll() // Make sure all dynamic imports are loaded
// url will always be set // url will always be set
const asPath = req.url as string const asPath: string = req.url as string
const router = new ServerRouter(pathname, query, asPath, { const router = new ServerRouter(
pathname,
query,
asPath,
{
isFallback: isFallback, isFallback: isFallback,
}) },
basePath
)
const ctx = { const ctx = {
err, err,
req: isAutoExport ? undefined : req, req: isAutoExport ? undefined : req,
......
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/router'
export default () => ( export default () => (
<>
<Link href="/other-page"> <Link href="/other-page">
<a id="other-page-link"> <a id="other-page-link">
<h1>Hello World</h1> <h1>Hello World</h1>
</a> </a>
</Link> </Link>
<div id="base-path">{useRouter().basePath}</div>
</>
) )
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
/* global jasmine */ /* global jasmine */
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
import url from 'url'
import { import {
nextServer, nextServer,
launchApp, launchApp,
...@@ -49,6 +50,19 @@ const runTests = (context, dev = false) => { ...@@ -49,6 +50,19 @@ const runTests = (context, dev = false) => {
} }
}) })
it('should have correct href for a link', async () => {
const browser = await webdriver(context.appPort, '/docs/hello')
const href = await browser.elementByCss('a').getAttribute('href')
const { pathname } = url.parse(href)
expect(pathname).toBe('/docs/other-page')
})
it('should show 404 for page not under the /docs prefix', async () => {
const text = await renderViaHTTP(context.appPort, '/hello')
expect(text).not.toContain('Hello World')
expect(text).toContain('This page could not be found')
})
it('should show the other-page page under the /docs prefix', async () => { it('should show the other-page page under the /docs prefix', async () => {
const browser = await webdriver(context.appPort, '/docs/other-page') const browser = await webdriver(context.appPort, '/docs/other-page')
try { try {
...@@ -59,6 +73,12 @@ const runTests = (context, dev = false) => { ...@@ -59,6 +73,12 @@ const runTests = (context, dev = false) => {
} }
}) })
it('should have basePath field on Router', async () => {
const html = await renderViaHTTP(context.appPort, '/docs/hello')
const $ = cheerio.load(html)
expect($('#base-path').text()).toBe('/docs')
})
it('should navigate to the page without refresh', async () => { it('should navigate to the page without refresh', async () => {
const browser = await webdriver(context.appPort, '/docs/hello') const browser = await webdriver(context.appPort, '/docs/hello')
try { try {
......
...@@ -100,7 +100,7 @@ describe('Production response size', () => { ...@@ -100,7 +100,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 165 * 1024 const delta = responseSizesBytes - 166 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
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