fix: sanitize client side pathnames (#25)

This commit is contained in:
Valerio Ageno
2024-08-15 20:42:47 +02:00
committed by GitHub
parent 71d7ccf27d
commit 1b1e91b6c0
2 changed files with 16 additions and 2 deletions
+2 -2
View File
@@ -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]' },
@@ -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(
+14
View File
@@ -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.
@@ -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]