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

Ensure interpolating dynamic href values works correctly (#16774)

This corrects/makes sure interpolating dynamic route values for `href` works correctly. This provides an alternative approach to building the `href` value with `next/link` so that you don't need to worry about encoding the params manually. 

Closes: https://github.com/vercel/next.js/issues/13473
Closes: https://github.com/vercel/next.js/issues/14959
Closes: https://github.com/vercel/next.js/issues/16771
parent 22800319
...@@ -257,10 +257,12 @@ function Link(props: React.PropsWithChildren<LinkProps>) { ...@@ -257,10 +257,12 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
const pathname = (router && router.pathname) || '/' const pathname = (router && router.pathname) || '/'
const { href, as } = React.useMemo(() => { const { href, as } = React.useMemo(() => {
const resolvedHref = resolveHref(pathname, props.href) const [resolvedHref, resolvedAs] = resolveHref(pathname, props.href, true)
return { return {
href: resolvedHref, href: resolvedHref,
as: props.as ? resolveHref(pathname, props.as) : resolvedHref, as: props.as
? resolveHref(pathname, props.as)
: resolvedAs || resolvedHref,
} }
}, [pathname, props.href, props.as]) }, [pathname, props.href, props.as])
......
...@@ -3,14 +3,16 @@ import type { ClientSsgManifest } from '../build' ...@@ -3,14 +3,16 @@ import type { ClientSsgManifest } from '../build'
import type { ClientBuildManifest } from '../build/webpack/plugins/build-manifest-plugin' import type { ClientBuildManifest } from '../build/webpack/plugins/build-manifest-plugin'
import mitt from '../next-server/lib/mitt' import mitt from '../next-server/lib/mitt'
import type { MittEmitter } from '../next-server/lib/mitt' import type { MittEmitter } from '../next-server/lib/mitt'
import { addBasePath, markLoadingError } from '../next-server/lib/router/router' import {
import escapePathDelimiters from '../next-server/lib/router/utils/escape-path-delimiters' addBasePath,
markLoadingError,
interpolateAs,
} from '../next-server/lib/router/router'
import getAssetPathFromRoute from '../next-server/lib/router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../next-server/lib/router/utils/get-asset-path-from-route'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import { parseRelativeUrl } from '../next-server/lib/router/utils/parse-relative-url' import { parseRelativeUrl } from '../next-server/lib/router/utils/parse-relative-url'
import { searchParamsToUrlQuery } from '../next-server/lib/router/utils/querystring' import { searchParamsToUrlQuery } from '../next-server/lib/router/utils/querystring'
import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher'
import { getRouteRegex } from '../next-server/lib/router/utils/route-regex'
export const looseToArray = <T extends {}>(input: any): T[] => export const looseToArray = <T extends {}>(input: any): T[] =>
[].slice.call(input) [].slice.call(input)
...@@ -216,51 +218,10 @@ export default class PageLoader { ...@@ -216,51 +218,10 @@ export default class PageLoader {
) )
} }
let isDynamic: boolean = isDynamicRoute(route), const isDynamic: boolean = isDynamicRoute(route)
interpolatedRoute: string | undefined const interpolatedRoute = isDynamic
if (isDynamic) { ? interpolateAs(hrefPathname, asPathname, query)
const dynamicRegex = getRouteRegex(route) : ''
const dynamicGroups = dynamicRegex.groups
const dynamicMatches =
// Try to match the dynamic route against the asPath
getRouteMatcher(dynamicRegex)(asPathname) ||
// Fall back to reading the values from the href
// TODO: should this take priority; also need to change in the router.
query
interpolatedRoute = route
if (
!Object.keys(dynamicGroups).every((param) => {
let value = dynamicMatches[param] || ''
const { repeat, optional } = dynamicGroups[param]
// support single-level catch-all
// TODO: more robust handling for user-error (passing `/`)
let replaced = `[${repeat ? '...' : ''}${param}]`
if (optional) {
replaced = `${!value ? '/' : ''}[${replaced}]`
}
if (repeat && !Array.isArray(value)) value = [value]
return (
(optional || param in dynamicMatches) &&
// Interpolate group into data URL if present
(interpolatedRoute =
interpolatedRoute!.replace(
replaced,
repeat
? (value as string[]).map(escapePathDelimiters).join('/')
: escapePathDelimiters(value as string)
) || '/')
)
})
) {
interpolatedRoute = '' // did not satisfy all requirements
// n.b. We ignore this error because we handle warning for this case in
// development in the `<Link>` component directly.
}
}
return isDynamic return isDynamic
? interpolatedRoute && getHrefForSlug(interpolatedRoute) ? interpolatedRoute && getHrefForSlug(interpolatedRoute)
......
...@@ -25,6 +25,7 @@ import { searchParamsToUrlQuery } from './utils/querystring' ...@@ -25,6 +25,7 @@ import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites' import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher' import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex' import { getRouteRegex } from './utils/route-regex'
import escapePathDelimiters from './utils/escape-path-delimiters'
interface TransitionOptions { interface TransitionOptions {
shallow?: boolean shallow?: boolean
...@@ -80,11 +81,66 @@ export function isLocalURL(url: string): boolean { ...@@ -80,11 +81,66 @@ export function isLocalURL(url: string): boolean {
type Url = UrlObject | string type Url = UrlObject | string
export function interpolateAs(
route: string,
asPathname: string,
query: ParsedUrlQuery
) {
let interpolatedRoute = ''
const dynamicRegex = getRouteRegex(route)
const dynamicGroups = dynamicRegex.groups
const dynamicMatches =
// Try to match the dynamic route against the asPath
(asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') ||
// Fall back to reading the values from the href
// TODO: should this take priority; also need to change in the router.
query
interpolatedRoute = route
if (
!Object.keys(dynamicGroups).every((param) => {
let value = dynamicMatches[param] || ''
const { repeat, optional } = dynamicGroups[param]
// support single-level catch-all
// TODO: more robust handling for user-error (passing `/`)
let replaced = `[${repeat ? '...' : ''}${param}]`
if (optional) {
replaced = `${!value ? '/' : ''}[${replaced}]`
}
if (repeat && !Array.isArray(value)) value = [value]
return (
(optional || param in dynamicMatches) &&
// Interpolate group into data URL if present
(interpolatedRoute =
interpolatedRoute!.replace(
replaced,
repeat
? (value as string[]).map(escapePathDelimiters).join('/')
: escapePathDelimiters(value as string)
) || '/')
)
})
) {
interpolatedRoute = '' // did not satisfy all requirements
// n.b. We ignore this error because we handle warning for this case in
// development in the `<Link>` component directly.
}
return interpolatedRoute
}
/** /**
* Resolves a given hyperlink with a certain router state (basePath not included). * Resolves a given hyperlink with a certain router state (basePath not included).
* Preserves absolute urls. * Preserves absolute urls.
*/ */
export function resolveHref(currentPath: string, href: Url): string { export function resolveHref(
currentPath: string,
href: Url,
resolveAs?: boolean
): string {
// we use a dummy base url for relative urls // we use a dummy base url for relative urls
const base = new URL(currentPath, 'http://n') const base = new URL(currentPath, 'http://n')
const urlAsString = const urlAsString =
...@@ -92,12 +148,31 @@ export function resolveHref(currentPath: string, href: Url): string { ...@@ -92,12 +148,31 @@ export function resolveHref(currentPath: string, href: Url): string {
try { try {
const finalUrl = new URL(urlAsString, base) const finalUrl = new URL(urlAsString, base)
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname) finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname)
let interpolatedAs = ''
if (
isDynamicRoute(finalUrl.pathname) &&
finalUrl.searchParams &&
resolveAs
) {
const query = searchParamsToUrlQuery(finalUrl.searchParams)
interpolatedAs = interpolateAs(
finalUrl.pathname,
finalUrl.pathname,
query
)
}
// if the origin didn't change, it means we received a relative href // if the origin didn't change, it means we received a relative href
return finalUrl.origin === base.origin const resolvedHref =
? finalUrl.href.slice(finalUrl.origin.length) finalUrl.origin === base.origin
: finalUrl.href ? finalUrl.href.slice(finalUrl.origin.length)
: finalUrl.href
return (resolveAs ? [resolvedHref, interpolatedAs] : resolvedHref) as string
} catch (_) { } catch (_) {
return urlAsString return (resolveAs ? [urlAsString] : urlAsString) as string
} }
} }
...@@ -558,6 +633,8 @@ export default class Router implements BaseRouter { ...@@ -558,6 +633,8 @@ export default class Router implements BaseRouter {
`Read more: https://err.sh/vercel/next.js/incompatible-href-as` `Read more: https://err.sh/vercel/next.js/incompatible-href-as`
) )
} }
} else if (route === asPathname) {
as = interpolateAs(route, asPathname, query)
} else { } else {
// Merge params into `query`, overwriting any specified in search // Merge params into `query`, overwriting any specified in search
Object.assign(query, routeMatch) Object.assign(query, routeMatch)
......
...@@ -10,7 +10,16 @@ const Page = () => { ...@@ -10,7 +10,16 @@ const Page = () => {
</Link> </Link>
<br /> <br />
<Link href="/post-1"> <Link href="/post-1">
<a id="view-post-1-no-as">View post 1</a> <a id="view-post-1-no-as">View post 1 (no as)</a>
</Link>
<br />
<Link
href={{
pathname: '/[name]',
query: { name: 'post-1' },
}}
>
<a id="view-post-1-interpolated">View post 1 (interpolated)</a>
</Link> </Link>
<br /> <br />
<Link href="/[name]/comments" as="/post-1/comments"> <Link href="/[name]/comments" as="/post-1/comments">
...@@ -22,7 +31,18 @@ const Page = () => { ...@@ -22,7 +31,18 @@ const Page = () => {
</Link> </Link>
<br /> <br />
<Link href="/post-1/comment-1"> <Link href="/post-1/comment-1">
<a id="view-post-1-comment-1-no-as">View comment 1 on post 1</a> <a id="view-post-1-comment-1-no-as">View comment 1 on post 1 (no as)</a>
</Link>
<br />
<Link
href={{
pathname: '/[name]/[comment]',
query: { name: 'post-1', comment: 'comment-1' },
}}
>
<a id="view-post-1-comment-1-interpolated">
View comment 1 on post 1 (interpolated)
</a>
</Link> </Link>
<br /> <br />
<Link href="/added-later/first"> <Link href="/added-later/first">
...@@ -40,42 +60,74 @@ const Page = () => { ...@@ -40,42 +60,74 @@ const Page = () => {
<Link href="/on-mount/[post]" as="/on-mount/test-w-hash#item-400"> <Link href="/on-mount/[post]" as="/on-mount/test-w-hash#item-400">
<a id="view-dynamic-with-hash">View test with hash</a> <a id="view-dynamic-with-hash">View test with hash</a>
</Link> </Link>
<br />
<Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/hello"> <Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/hello">
<a id="catch-all-single">Catch-all route (single)</a> <a id="catch-all-single">Catch-all route (single)</a>
</Link> </Link>
<br />
<Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/hello1/hello2"> <Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/hello1/hello2">
<a id="catch-all-multi">Catch-all route (multi)</a> <a id="catch-all-multi">Catch-all route (multi)</a>
</Link> </Link>
<br />
<Link <Link
href="/p1/p2/all-ssr/[...rest]" href="/p1/p2/all-ssr/[...rest]"
as="/p1/p2/all-ssr/hello1%2F/he%2Fllo2" as="/p1/p2/all-ssr/hello1%2F/he%2Fllo2"
> >
<a id="catch-all-enc">Catch-all route (encoded)</a> <a id="catch-all-enc">Catch-all route (encoded)</a>
</Link> </Link>
<br />
<Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/:42"> <Link href="/p1/p2/all-ssr/[...rest]" as="/p1/p2/all-ssr/:42">
<a id="catch-all-colonnumber">Catch-all route :42</a> <a id="catch-all-colonnumber">Catch-all route :42</a>
</Link> </Link>
<br />
<Link href="/p1/p2/all-ssg/[...rest]" as="/p1/p2/all-ssg/hello"> <Link href="/p1/p2/all-ssg/[...rest]" as="/p1/p2/all-ssg/hello">
<a id="ssg-catch-all-single">Catch-all route (single)</a> <a id="ssg-catch-all-single">Catch-all route (single)</a>
</Link> </Link>
<br />
<Link
href={{
pathname: '/p1/p2/all-ssg/[...rest]',
query: { rest: ['hello'] },
}}
>
<a id="ssg-catch-all-single-interpolated">
Catch-all route (single interpolated)
</a>
</Link>
<br />
<Link href="/p1/p2/all-ssg/[...rest]" as="/p1/p2/all-ssg/hello1/hello2"> <Link href="/p1/p2/all-ssg/[...rest]" as="/p1/p2/all-ssg/hello1/hello2">
<a id="ssg-catch-all-multi">Catch-all route (multi)</a> <a id="ssg-catch-all-multi">Catch-all route (multi)</a>
</Link> </Link>
<br />
<Link href="/p1/p2/all-ssg/hello1/hello2"> <Link href="/p1/p2/all-ssg/hello1/hello2">
<a id="ssg-catch-all-multi-no-as">Catch-all route (multi)</a> <a id="ssg-catch-all-multi-no-as">Catch-all route (multi)</a>
</Link> </Link>
<br />
<Link
href={{
pathname: '/p1/p2/all-ssg/[...rest]',
query: { rest: ['hello1', 'hello2'] },
}}
>
<a id="ssg-catch-all-multi-interpolated">
Catch-all route (multi interpolated)
</a>
</Link>
<br />
<Link <Link
href="/p1/p2/nested-all-ssg/[...rest]" href="/p1/p2/nested-all-ssg/[...rest]"
as="/p1/p2/nested-all-ssg/hello" as="/p1/p2/nested-all-ssg/hello"
> >
<a id="nested-ssg-catch-all-single">Nested Catch-all route (single)</a> <a id="nested-ssg-catch-all-single">Nested Catch-all route (single)</a>
</Link> </Link>
<br />
<Link <Link
href="/p1/p2/nested-all-ssg/[...rest]" href="/p1/p2/nested-all-ssg/[...rest]"
as="/p1/p2/nested-all-ssg/hello1/hello2" as="/p1/p2/nested-all-ssg/hello1/hello2"
> >
<a id="nested-ssg-catch-all-multi">Nested Catch-all route (multi)</a> <a id="nested-ssg-catch-all-multi">Nested Catch-all route (multi)</a>
</Link> </Link>
<br />
<p id="query">{JSON.stringify(Object.keys(useRouter().query))}</p> <p id="query">{JSON.stringify(Object.keys(useRouter().query))}</p>
</div> </div>
) )
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join, dirname } from 'path' import { join, dirname } from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import url from 'url'
import { import {
renderViaHTTP, renderViaHTTP,
fetchViaHTTP, fetchViaHTTP,
...@@ -117,6 +118,30 @@ function runTests(dev) { ...@@ -117,6 +118,30 @@ function runTests(dev) {
} }
}) })
it('should navigate to a dynamic page successfully interpolated', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = 1')
const href = await browser
.elementByCss('#view-post-1-interpolated')
.getAttribute('href')
expect(url.parse(href).pathname).toBe('/post-1')
await browser.elementByCss('#view-post-1-interpolated').click()
await browser.waitForElementByCss('#asdf')
expect(await browser.eval('window.beforeNav')).toBe(1)
const text = await browser.elementByCss('#asdf').text()
expect(text).toMatch(/this is.*?post-1/i)
} finally {
if (browser) await browser.close()
}
})
it('should allow calling Router.push on mount successfully', async () => { it('should allow calling Router.push on mount successfully', async () => {
const browser = await webdriver(appPort, '/post-1/on-mount-redir') const browser = await webdriver(appPort, '/post-1/on-mount-redir')
try { try {
...@@ -188,6 +213,30 @@ function runTests(dev) { ...@@ -188,6 +213,30 @@ function runTests(dev) {
} }
}) })
it('should navigate to a nested dynamic page successfully interpolated', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = 1')
const href = await browser
.elementByCss('#view-post-1-comment-1-interpolated')
.getAttribute('href')
expect(url.parse(href).pathname).toBe('/post-1/comment-1')
await browser.elementByCss('#view-post-1-comment-1-interpolated').click()
await browser.waitForElementByCss('#asdf')
expect(await browser.eval('window.beforeNav')).toBe(1)
const text = await browser.elementByCss('#asdf').text()
expect(text).toMatch(/i am.*comment-1.*on.*post-1/i)
} finally {
if (browser) await browser.close()
}
})
it('should pass params in getInitialProps during SSR', async () => { it('should pass params in getInitialProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/post-1/cmnt-1') const html = await renderViaHTTP(appPort, '/post-1/cmnt-1')
expect(html).toMatch(/gip.*post-1/i) expect(html).toMatch(/gip.*post-1/i)
...@@ -381,9 +430,36 @@ function runTests(dev) { ...@@ -381,9 +430,36 @@ function runTests(dev) {
let browser let browser
try { try {
browser = await webdriver(appPort, '/') browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = 1')
await browser.elementByCss('#ssg-catch-all-single').click() await browser.elementByCss('#ssg-catch-all-single').click()
await browser.waitForElementByCss('#all-ssg-content') await browser.waitForElementByCss('#all-ssg-content')
expect(await browser.eval('window.beforeNav')).toBe(1)
const text = await browser.elementByCss('#all-ssg-content').text()
expect(text).toBe('{"rest":["hello"]}')
} finally {
if (browser) await browser.close()
}
})
it('[ssg: catch-all] should pass params in getStaticProps during client navigation (single interpolated)', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = 1')
const href = await browser
.elementByCss('#ssg-catch-all-single-interpolated')
.getAttribute('href')
expect(url.parse(href).pathname).toBe('/p1/p2/all-ssg/hello')
await browser.elementByCss('#ssg-catch-all-single-interpolated').click()
await browser.waitForElementByCss('#all-ssg-content')
expect(await browser.eval('window.beforeNav')).toBe(1)
const text = await browser.elementByCss('#all-ssg-content').text() const text = await browser.elementByCss('#all-ssg-content').text()
expect(text).toBe('{"rest":["hello"]}') expect(text).toBe('{"rest":["hello"]}')
} finally { } finally {
...@@ -425,6 +501,30 @@ function runTests(dev) { ...@@ -425,6 +501,30 @@ function runTests(dev) {
} }
}) })
it('[ssg: catch-all] should pass params in getStaticProps during client navigation (multi interpolated)', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = 1')
const href = await browser
.elementByCss('#ssg-catch-all-multi-interpolated')
.getAttribute('href')
expect(url.parse(href).pathname).toBe('/p1/p2/all-ssg/hello1/hello2')
await browser.elementByCss('#ssg-catch-all-multi-interpolated').click()
await browser.waitForElementByCss('#all-ssg-content')
expect(await browser.eval('window.beforeNav')).toBe(1)
const text = await browser.elementByCss('#all-ssg-content').text()
expect(text).toBe('{"rest":["hello1","hello2"]}')
} finally {
if (browser) await browser.close()
}
})
it('[nested ssg: catch-all] should pass params in getStaticProps during client navigation (single)', async () => { it('[nested ssg: catch-all] should pass params in getStaticProps during client navigation (single)', async () => {
let browser let browser
try { try {
......
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