Skip to content

Commit

Permalink
update trailing slash logic
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Jun 11, 2024
1 parent a08e9b7 commit 54c1781
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe('resolveAbsoluteUrlWithPathname', () => {
)
})

it('should not add trailing slash to relative url that ends with a file extension', () => {
it('should not add trailing slash to relative url that matches file pattern', () => {
expect(resolver('/foo.html')).toBe('https://example.com/foo.html')
expect(resolver(new URL('/foo.html', metadataBase))).toBe(
'https://example.com/foo.html'
Expand Down
13 changes: 10 additions & 3 deletions packages/next/src/lib/metadata/resolvers/resolve-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ function resolveRelativeUrl(url: string | URL, pathname: string): string | URL {
return url
}

// The regex is matching logic from packages/next/src/lib/load-custom-routes.ts
const FILE_REGEX =
/^(?:\/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+))\/[/#?]?$/i
function isFilePattern(pathname: string): boolean {
return FILE_REGEX.test(pathname)
}

// Resolve `pathname` if `url` is a relative path the compose with `metadataBase`.
function resolveAbsoluteUrlWithPathname(
url: string | URL,
Expand All @@ -112,7 +119,8 @@ function resolveAbsoluteUrlWithPathname(
let isRelative = resolvedUrl.startsWith('/')
let isExternal = false
let hasQuery = resolvedUrl.includes('?')
let hasFileExtension = /\.[0-9a-z]+$/i.test(resolvedUrl)
// Do not apply trailing slash for file like urls, aligning with the behavior with `trailingSlash`
let isFileUrl = isFilePattern(resolvedUrl)

if (!isRelative) {
try {
Expand All @@ -123,8 +131,7 @@ function resolveAbsoluteUrlWithPathname(
// If it's not a valid URL, treat it as external
isExternal = true
}
if (!hasFileExtension && !isExternal && !hasQuery)
return `${resolvedUrl}/`
if (!isFileUrl && !isExternal && !hasQuery) return `${resolvedUrl}/`
}
}

Expand Down

0 comments on commit 54c1781

Please sign in to comment.