Skip to content

Commit

Permalink
fix: sanitize client side pathnames
Browse files Browse the repository at this point in the history
  • Loading branch information
Valerioageno committed Aug 15, 2024
1 parent 3ca24ec commit 826e287
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/router/src/hooks/useRoute.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('Test useRoute fn', () => {
routesById: {
'/': { id: '/' },
'/about': { id: '/about' },
'/posts/': { id: '/posts/' }, // posts/index
'/posts': { id: '/posts' }, // posts/index
'/posts/[post]': { id: '/posts/[post]' },
'/posts/defined-post': { id: '/posts/defined-post' },
'/posts/[post]/[comment]': { id: '/posts/[post]/[comment]' },
Expand All @@ -26,7 +26,7 @@ describe('Test useRoute fn', () => {
expect(useRoute('/')?.id).toBe('/')
expect(useRoute('/not-found')?.id).toBe(undefined)
expect(useRoute('/about')?.id).toBe('/about')
expect(useRoute('/posts/')?.id).toBe('/posts/')
expect(useRoute('/posts/')?.id).toBe('/posts')
expect(useRoute('/posts/dynamic-post')?.id).toBe('/posts/[post]')
expect(useRoute('/posts/defined-post')?.id).toBe('/posts/defined-post')
expect(useRoute('/posts/dynamic-post/dynamic-comment')?.id).toBe(
Expand Down
14 changes: 14 additions & 0 deletions packages/router/src/hooks/useRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import { useInternalRouter } from './useInternalRouter'

const DYNAMIC_PATH_REGEX = /\[(.*?)\]/

/**
* In order to correctly handle pathnames that might finish with a slash
* we first sanitize them by removing the final slash.
*/
export function sanitizePathname(pathname: string): string {
if (pathname.endsWith('/') && pathname !== '/') {
return pathname.substring(0, pathname.length - 1)
}

return pathname
}

/*
* This hook is also implemented on server side to match the bundle
* file to load at the first rendering.
Expand All @@ -14,6 +26,8 @@ const DYNAMIC_PATH_REGEX = /\[(.*?)\]/
export default function useRoute(pathname?: string): Route | undefined {
if (!pathname) return

pathname = sanitizePathname(pathname)

const { routesById } = useInternalRouter()

if (routesById[pathname]) return routesById[pathname]
Expand Down

0 comments on commit 826e287

Please sign in to comment.