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

Allow mismatching `href` and `as` when manually provided (#9837)

* Allow mismatch href and as when manually provided

* Swap warning and error and throw error in production also

* Add test for mismatch error in production

* Update to only show warning in development
parent 57aae473
...@@ -331,22 +331,34 @@ export default class Router implements BaseRouter { ...@@ -331,22 +331,34 @@ export default class Router implements BaseRouter {
if (isDynamicRoute(route)) { if (isDynamicRoute(route)) {
const { pathname: asPathname } = parse(as) const { pathname: asPathname } = parse(as)
const routeMatch = getRouteMatcher(getRouteRegex(route))(asPathname) const routeRegex = getRouteRegex(route)
const routeMatch = getRouteMatcher(routeRegex)(asPathname)
if (!routeMatch) { if (!routeMatch) {
const error = const missingParams = Object.keys(routeRegex.groups).filter(
`The provided \`as\` value (${asPathname}) is incompatible with the \`href\` value (${route}). ` + param => !query[param]
`Read more: https://err.sh/zeit/next.js/incompatible-href-as` )
if (process.env.NODE_ENV !== 'production') { if (missingParams.length > 0) {
throw new Error(error) if (process.env.NODE_ENV !== 'production') {
} else { console.warn(
console.error(error) `Mismatching \`as\` and \`href\` failed to manually provide ` +
`the params: ${missingParams.join(
', '
)} in the \`href\`'s \`query\``
)
}
return reject(
new Error(
`The provided \`as\` value (${asPathname}) is incompatible with the \`href\` value (${route}). ` +
`Read more: https://err.sh/zeit/next.js/incompatible-href-as`
)
)
} }
return resolve(false) } else {
// Merge params into `query`, overwriting any specified in search
Object.assign(query, routeMatch)
} }
// Merge params into `query`, overwriting any specified in search
Object.assign(query, routeMatch)
} }
Router.events.emit('routeChangeStart', as) Router.events.emit('routeChangeStart', as)
......
export default () => 'hi from post'
import Link from 'next/link'
export default () => (
<Link href="/[post]?post=post-1" as="/blog/post-1">
<a>Click me</a>
</Link>
)
...@@ -20,13 +20,45 @@ const appDir = join(__dirname, '..') ...@@ -20,13 +20,45 @@ const appDir = join(__dirname, '..')
const firstErrorRegex = /Invalid href passed to router: mailto:idk@idk.com.*invalid-href-passed/ const firstErrorRegex = /Invalid href passed to router: mailto:idk@idk.com.*invalid-href-passed/
const secondErrorRegex = /Invalid href passed to router: .*google\.com.*invalid-href-passed/ const secondErrorRegex = /Invalid href passed to router: .*google\.com.*invalid-href-passed/
const showsError = async (pathname, regex, click = false) => { const showsError = async (
pathname,
regex,
click = false,
isWarn = false,
cb
) => {
const browser = await webdriver(appPort, pathname) const browser = await webdriver(appPort, pathname)
if (isWarn) {
await browser.eval(`(function() {
window.warnLogs = []
var origWarn = window.console.warn
window.console.warn = function() {
var warnStr = ''
for (var i = 0; i < arguments.length; i++) {
if (i > 0) warnStr += ' ';
warnStr += arguments[i]
}
window.warnLogs.push(warnStr)
origWarn.apply(undefined, arguments)
}
})()`)
}
if (click) { if (click) {
await browser.elementByCss('a').click() await browser.elementByCss('a').click()
} }
const errorContent = await getReactErrorOverlayContent(browser) if (isWarn) {
expect(errorContent).toMatch(regex) await waitFor(2000)
const warnLogs = await browser.eval('window.warnLogs')
console.log(warnLogs)
expect(warnLogs.some(log => log.match(regex))).toBe(true)
} else {
const errorContent = await getReactErrorOverlayContent(browser)
expect(errorContent).toMatch(regex)
}
if (cb) await cb(browser)
await browser.close() await browser.close()
} }
...@@ -89,6 +121,16 @@ describe('Invalid hrefs', () => { ...@@ -89,6 +121,16 @@ describe('Invalid hrefs', () => {
/The provided `as` value \(\/blog\/post-1\) is incompatible with the `href` value \(\/\[post\]\)/, /The provided `as` value \(\/blog\/post-1\) is incompatible with the `href` value \(\/\[post\]\)/,
true true
) )
await showsError(
'/dynamic-route-mismatch',
/Mismatching `as` and `href` failed to manually provide the params: post in the `href`'s `query`/,
true,
true
)
})
it('does not throw error when dynamic route mismatch is used on Link and params are manually provided', async () => {
await noError('/dynamic-route-mismatch-manual', true)
}) })
}) })
...@@ -123,5 +165,25 @@ describe('Invalid hrefs', () => { ...@@ -123,5 +165,25 @@ describe('Invalid hrefs', () => {
it('does not show error in production when https://google.com is used as href on router.replace', async () => { it('does not show error in production when https://google.com is used as href on router.replace', async () => {
await noError('/second?method=replace', true) await noError('/second?method=replace', true)
}) })
it('shows error when dynamic route mismatch is used on Link', async () => {
const browser = await webdriver(appPort, '/dynamic-route-mismatch')
await browser.eval(`(function() {
window.caughtErrors = []
window.addEventListener('unhandledrejection', (error) => {
window.caughtErrors.push(error.reason.message)
})
})()`)
await browser.elementByCss('a').click()
await waitFor(500)
const errors = await browser.eval('window.caughtErrors')
expect(
errors.find(err =>
err.includes(
'The provided `as` value (/blog/post-1) is incompatible with the `href` value (/[post]). Read more: https://err.sh/zeit/next.js/incompatible-href-as'
)
)
).toBeTruthy()
})
}) })
}) })
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