diff --git a/packages/router/src/hooks/useRoute.spec.tsx b/packages/router/src/hooks/useRoute.spec.tsx index 8ec6452b..37017d5c 100644 --- a/packages/router/src/hooks/useRoute.spec.tsx +++ b/packages/router/src/hooks/useRoute.spec.tsx @@ -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( diff --git a/packages/router/src/hooks/useRoute.tsx b/packages/router/src/hooks/useRoute.tsx index 3124057d..8f48a24a 100644 --- a/packages/router/src/hooks/useRoute.tsx +++ b/packages/router/src/hooks/useRoute.tsx @@ -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]