Skip to content

Commit

Permalink
Fix as option with optional catch all routes
Browse files Browse the repository at this point in the history
`as` option used to throw with url object syntax: optional attribute were not taken into account when checking missing parameters in router change method.
Fixes #41624
  • Loading branch information
cvolant committed Nov 2, 2022
1 parent 468f2c4 commit be83e50
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/next/shared/lib/router/router.ts
Expand Up @@ -1505,7 +1505,7 @@ export default class Router implements BaseRouter {

if (!routeMatch || (shouldInterpolate && !interpolatedAs.result)) {
const missingParams = Object.keys(routeRegex.groups).filter(
(param) => !query[param]
(param) => !query[param] && !routeRegex.groups[param].optional
)

if (missingParams.length > 0 && !isMiddlewareMatch) {
Expand Down
4 changes: 4 additions & 0 deletions test/integration/rewrites-manual-href-as/next.config.js
Expand Up @@ -5,6 +5,10 @@ module.exports = {
source: '/rewrite-me',
destination: '/another',
},
{
source: '/blog/:slugs*',
destination: '/news/:slugs*',
},
]
},
}
@@ -0,0 +1,22 @@
import Link from 'next/link'
import { useRouter } from 'next/router'

export default function News() {
const { asPath, pathname, query } = useRouter()

return (
<div>
<h1 id="news">news page</h1>
<p id="asPath">{asPath}</p>
<p id="pathname">{pathname}</p>
<p id="query">{JSON.stringify(query)}</p>
<Link href="/">&larr; Back home</Link>
</div>
)
}

export async function getServerSideProps() {
return {
props: {},
}
}
Expand Up @@ -55,6 +55,15 @@ export default function Page(props) {
go to /preview/321 as /rewrite-me
</Link>
<br />

<Link
href={{ pathname: '/news/[[...slugs]]', query: { slugs: [] } }}
as="/blog"
id="to-news-as-blog"
>
go to /news as /blog
</Link>
<br />
</>
)
}
12 changes: 12 additions & 0 deletions test/integration/rewrites-manual-href-as/test/index.test.js
Expand Up @@ -144,6 +144,18 @@ const runTests = () => {
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({
slug: '321',
})

await browser.back().waitForElementByCss('#preview')

await browser
.elementByCss('#to-news-as-blog')
.click()
.waitForElementByCss('#news')

expect(await browser.elementByCss('#news').text()).toBe('news page')
expect(await browser.elementByCss('#asPath').text()).toBe('/blog')
expect(await browser.eval('window.beforeNav')).toBe(1)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual({})
})
}

Expand Down

0 comments on commit be83e50

Please sign in to comment.