diff --git a/packages/next/shared/lib/router/utils/format-next-pathname-info.ts b/packages/next/shared/lib/router/utils/format-next-pathname-info.ts index 784bd8adc8d0e..55cdbb05d64dd 100644 --- a/packages/next/shared/lib/router/utils/format-next-pathname-info.ts +++ b/packages/next/shared/lib/router/utils/format-next-pathname-info.ts @@ -17,6 +17,10 @@ export function formatNextPathnameInfo(info: ExtendedInfo) { info.ignorePrefix ) + if (info.buildId || !info.trailingSlash) { + pathname = removeTrailingSlash(pathname) + } + if (info.buildId) { pathname = addPathSuffix( addPathPrefix(pathname, `/_next/data/${info.buildId}`), @@ -25,8 +29,8 @@ export function formatNextPathnameInfo(info: ExtendedInfo) { } pathname = addPathPrefix(pathname, info.basePath) - return info.trailingSlash - ? !info.buildId && !pathname.endsWith('/') + return !info.buildId && info.trailingSlash + ? !pathname.endsWith('/') ? addPathSuffix(pathname, '/') : pathname : removeTrailingSlash(pathname) diff --git a/test/unit/web-runtime/next-url.test.ts b/test/unit/web-runtime/next-url.test.ts index 582466a38d072..69c80c0a7a35b 100644 --- a/test/unit/web-runtime/next-url.test.ts +++ b/test/unit/web-runtime/next-url.test.ts @@ -263,6 +263,39 @@ it('correctly parses a prefetch url', async () => { ) }) +it('correctly handles trailing slash in _next/data', async () => { + const url = new NextURL('/abc/', 'http://127.0.0.1:3000') + url.buildId = '1234' + + expect(url.pathname).toEqual('/abc/') + expect(url.locale).toEqual('') + expect(String(url)).toEqual('http://localhost:3000/_next/data/1234/abc.json') +}) + +it('correctly handles trailing slash in _next/data with config', async () => { + const url = new NextURL('/abc/', 'http://127.0.0.1:3000', { + nextConfig: { trailingSlash: true }, + }) + url.buildId = '1234' + + expect(url.pathname).toEqual('/abc/') + expect(url.locale).toEqual('') + expect(String(url)).toEqual('http://localhost:3000/_next/data/1234/abc.json') +}) + +it('correctly handles trailing slash in _next/data with basePath', async () => { + const url = new NextURL('/docs/abc/', 'http://127.0.0.1:3000', { + nextConfig: { basePath: '/docs', trailingSlash: true }, + }) + url.buildId = '1234' + + expect(url.pathname).toEqual('/abc/') + expect(url.locale).toEqual('') + expect(String(url)).toEqual( + 'http://localhost:3000/docs/_next/data/1234/abc.json' + ) +}) + it('correctly parses a prefetch index url', async () => { const url = new NextURL( '/_next/data/development/index.json',