Unverified Commit 6f61fb40 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

bugfix: route interception with dynamic paths (#51526)

### What?
Paths with interception markers adjacent to dynamic segments are not correctly parsed, which leads to the path match logic failing. 

### Why?
`getParametrizedRoutes` checks for brackets but isn't expecting to receive an interception marker. For example, a path of `/photos/(.)[author]/[id]` results in the following regex:
`/^\/photos\/\(\.\)\[author\]\/([^/]+?)(?:\/)?$/`

This will not match a path of `/photos/(.)zack/1` since it retained the `[author]` brackets.

`getSegmentParam` has a similar issue when getting values for path params, though we can just skip the interception markers and go straight to the params.

Closes NEXT-1166, NEXT-1013
Fixes #48143
Fixes #49614

link NEXT-1013
parent c6313606
import { INTERCEPTION_ROUTE_MARKERS } from '../future/helpers/interception-routes'
import { DynamicParamTypes } from './types' import { DynamicParamTypes } from './types'
/** /**
...@@ -7,6 +8,16 @@ export function getSegmentParam(segment: string): { ...@@ -7,6 +8,16 @@ export function getSegmentParam(segment: string): {
param: string param: string
type: DynamicParamTypes type: DynamicParamTypes
} | null { } | null {
const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker) =>
segment.startsWith(marker)
)
// if an interception marker is part of the path segment, we need to jump ahead
// to the relevant portion for param parsing
if (interceptionMarker) {
segment = segment.slice(interceptionMarker.length)
}
if (segment.startsWith('[[...') && segment.endsWith(']]')) { if (segment.startsWith('[[...') && segment.endsWith(']]')) {
return { return {
type: 'optional-catchall', type: 'optional-catchall',
......
import { getNamedRouteRegex } from './route-regex'
describe('getNamedRouteRegex', () => {
it('should handle interception markers adjacent to dynamic path segments', () => {
const regex = getNamedRouteRegex('/photos/(.)[author]/[id]', true)
expect(regex.routeKeys).toEqual({
nxtIauthor: 'nxtIauthor',
nxtPid: 'nxtPid',
})
expect(regex.groups['author']).toEqual({
pos: 1,
repeat: false,
optional: false,
})
expect(regex.groups['id']).toEqual({
pos: 2,
repeat: false,
optional: false,
})
expect(regex.re.test('/photos/(.)next/123')).toBe(true)
})
it('should handle multi-level interception markers', () => {
const regex = getNamedRouteRegex('/photos/(..)(..)[author]/[id]', true)
expect(regex.routeKeys).toEqual({
nxtIauthor: 'nxtIauthor',
nxtPid: 'nxtPid',
})
expect(regex.groups['author']).toEqual({
pos: 1,
repeat: false,
optional: false,
})
expect(regex.groups['id']).toEqual({
pos: 2,
repeat: false,
optional: false,
})
expect(regex.re.test('/photos/(..)(..)next/123')).toBe(true)
})
it('should handle interception markers not adjacent to dynamic path segments', () => {
const regex = getNamedRouteRegex('/photos/(.)author/[id]', true)
expect(regex.routeKeys).toEqual({
nxtPid: 'nxtPid',
})
expect(regex.groups['author']).toBeUndefined()
expect(regex.groups['id']).toEqual({
pos: 1,
repeat: false,
optional: false,
})
expect(regex.re.test('/photos/(.)author/123')).toBe(true)
})
it('should handle optional dynamic path segments', () => {
const regex = getNamedRouteRegex('/photos/[[id]]', true)
expect(regex.routeKeys).toEqual({
nxtPid: 'nxtPid',
})
expect(regex.groups['id']).toEqual({
pos: 1,
repeat: false,
optional: true,
})
})
it('should handle optional catch-all dynamic path segments', () => {
const regex = getNamedRouteRegex('/photos/[[...id]]', true)
expect(regex.routeKeys).toEqual({
nxtPid: 'nxtPid',
})
expect(regex.groups['id']).toEqual({
pos: 1,
repeat: true,
optional: true,
})
expect(regex.re.test('/photos/1')).toBe(true)
expect(regex.re.test('/photos/1/2/3')).toBe(true)
expect(regex.re.test('/photos')).toBe(true)
})
})
import { INTERCEPTION_ROUTE_MARKERS } from '../../../../server/future/helpers/interception-routes'
import { escapeStringRegexp } from '../../escape-regexp' import { escapeStringRegexp } from '../../escape-regexp'
import { removeTrailingSlash } from './remove-trailing-slash' import { removeTrailingSlash } from './remove-trailing-slash'
const NEXT_QUERY_PARAM_PREFIX = 'nxtP' const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'
export interface Group { export interface Group {
pos: number pos: number
...@@ -41,8 +43,17 @@ function getParametrizedRoute(route: string) { ...@@ -41,8 +43,17 @@ function getParametrizedRoute(route: string) {
return { return {
parameterizedRoute: segments parameterizedRoute: segments
.map((segment) => { .map((segment) => {
if (segment.startsWith('[') && segment.endsWith(']')) { const markerMatch = INTERCEPTION_ROUTE_MARKERS.find((m) =>
const { key, optional, repeat } = parseParameter(segment.slice(1, -1)) segment.startsWith(m)
)
const paramMatches = segment.match(/\[((?:\[.*\])|.+)\]/) // Check for parameters
if (markerMatch && paramMatches) {
const { key, optional, repeat } = parseParameter(paramMatches[1])
groups[key] = { pos: groupIndex++, repeat, optional }
return `/${escapeStringRegexp(markerMatch)}([^/]+?)`
} else if (paramMatches) {
const { key, repeat, optional } = parseParameter(paramMatches[1])
groups[key] = { pos: groupIndex++, repeat, optional } groups[key] = { pos: groupIndex++, repeat, optional }
return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)' return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)'
} else { } else {
...@@ -90,48 +101,79 @@ function buildGetSafeRouteKey() { ...@@ -90,48 +101,79 @@ function buildGetSafeRouteKey() {
} }
} }
function getSafeKeyFromSegment({
segment,
routeKeys,
keyPrefix,
}: {
segment: string
routeKeys: Record<string, string>
keyPrefix?: string
}) {
const getSafeRouteKey = buildGetSafeRouteKey()
const { key, optional, repeat } = parseParameter(segment)
// replace any non-word characters since they can break
// the named regex
let cleanedKey = key.replace(/\W/g, '')
if (keyPrefix) {
cleanedKey = `${keyPrefix}${cleanedKey}`
}
let invalidKey = false
// check if the key is still invalid and fallback to using a known
// safe key
if (cleanedKey.length === 0 || cleanedKey.length > 30) {
invalidKey = true
}
if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) {
invalidKey = true
}
if (invalidKey) {
cleanedKey = getSafeRouteKey()
}
if (keyPrefix) {
routeKeys[cleanedKey] = `${keyPrefix}${key}`
} else {
routeKeys[cleanedKey] = `${key}`
}
return repeat
? optional
? `(?:/(?<${cleanedKey}>.+?))?`
: `/(?<${cleanedKey}>.+?)`
: `/(?<${cleanedKey}>[^/]+?)`
}
function getNamedParametrizedRoute(route: string, prefixRouteKeys: boolean) { function getNamedParametrizedRoute(route: string, prefixRouteKeys: boolean) {
const segments = removeTrailingSlash(route).slice(1).split('/') const segments = removeTrailingSlash(route).slice(1).split('/')
const getSafeRouteKey = buildGetSafeRouteKey()
const routeKeys: { [named: string]: string } = {} const routeKeys: { [named: string]: string } = {}
return { return {
namedParameterizedRoute: segments namedParameterizedRoute: segments
.map((segment) => { .map((segment) => {
if (segment.startsWith('[') && segment.endsWith(']')) { const hasInterceptionMarker = INTERCEPTION_ROUTE_MARKERS.some((m) =>
const { key, optional, repeat } = parseParameter(segment.slice(1, -1)) segment.startsWith(m)
// replace any non-word characters since they can break )
// the named regex const paramMatches = segment.match(/\[((?:\[.*\])|.+)\]/) // Check for parameters
let cleanedKey = key.replace(/\W/g, '')
if (hasInterceptionMarker && paramMatches) {
if (prefixRouteKeys) { return getSafeKeyFromSegment({
cleanedKey = `${NEXT_QUERY_PARAM_PREFIX}${cleanedKey}` segment: paramMatches[1],
} routeKeys,
let invalidKey = false keyPrefix: prefixRouteKeys
? NEXT_INTERCEPTION_MARKER_PREFIX
// check if the key is still invalid and fallback to using a known : undefined,
// safe key })
if (cleanedKey.length === 0 || cleanedKey.length > 30) { } else if (paramMatches) {
invalidKey = true return getSafeKeyFromSegment({
} segment: paramMatches[1],
if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) { routeKeys,
invalidKey = true keyPrefix: prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined,
} })
if (invalidKey) {
cleanedKey = getSafeRouteKey()
}
if (prefixRouteKeys) {
routeKeys[cleanedKey] = `${NEXT_QUERY_PARAM_PREFIX}${key}`
} else {
routeKeys[cleanedKey] = `${key}`
}
return repeat
? optional
? `(?:/(?<${cleanedKey}>.+?))?`
: `/(?<${cleanedKey}>.+?)`
: `/(?<${cleanedKey}>[^/]+?)`
} else { } else {
return `/${escapeStringRegexp(segment)}` return `/${escapeStringRegexp(segment)}`
} }
......
export default function InterceptedAuthorIdPage() {
return <div id="user-intercept-page">Intercepted Page</div>
}
export default function AuthorIdPage() {
return <div id="user-regular-page">Regular Page</div>
}
import Link from 'next/link'
export default function Home() {
return (
<Link href="/intercepting-routes-dynamic/photos/next/123">Visit Next</Link>
)
}
...@@ -340,6 +340,46 @@ createNextDescribe( ...@@ -340,6 +340,46 @@ createNextDescribe(
}) })
}) })
describe('route intercepting with dynamic routes', () => {
it('should render intercepted route', async () => {
const browser = await next.browser(
'/intercepting-routes-dynamic/photos'
)
// Check if navigation to modal route works
await check(
() =>
browser
.elementByCss(
'[href="/intercepting-routes-dynamic/photos/next/123"]'
)
.click()
.waitForElementByCss('#user-intercept-page')
.text(),
'Intercepted Page'
)
// Check if url matches even though it was intercepted.
await check(
() => browser.url(),
next.url + '/intercepting-routes-dynamic/photos/next/123'
)
// Trigger a refresh, this should load the normal page, not the modal.
await check(
() =>
browser.refresh().waitForElementByCss('#user-regular-page').text(),
'Regular Page'
)
// Check if the url matches still.
await check(
() => browser.url(),
next.url + '/intercepting-routes-dynamic/photos/next/123'
)
})
})
describe('route intercepting', () => { describe('route intercepting', () => {
it('should render intercepted route', async () => { it('should render intercepted route', async () => {
const browser = await next.browser('/intercepting-routes/feed') const browser = await next.browser('/intercepting-routes/feed')
......
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