Skip to content

Commit bc14f19

Browse files
F7b5devjiwonchoi
andauthored
fix: Update URL resolution logic to handle search parameters on root path /?foo=bar (#78262)
## What? This PR fixes and implements test for an URL resolution issue that stripped the searchparam when `metadataBase` was defined and a search param was set on the root path. This created a behavior where : ``` export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", metadataBase: new URL("https://www.example.com"), alternates: { canonical: "/?foo=bar", }, }; ``` would result in `<link rel="canonical" href="https://www.example.com">` instead of `<link rel="canonical" href="https://www.example.com/?foo=bar">` ## Related issues - Fixes #65776 - Fixes #74689 Co-authored-by: Jiwon Choi <[email protected]>
1 parent 3f6ffba commit bc14f19

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

packages/next/src/lib/metadata/resolvers/resolve-url.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ describe('resolveAbsoluteUrlWithPathname', () => {
6262
'https://example.com/foo'
6363
)
6464
})
65+
66+
it('should resolve absolute internal url with query', () => {
67+
expect(resolver('https://example.com/?foo=bar')).toBe(
68+
'https://example.com/?foo=bar'
69+
)
70+
})
6571
})
6672

6773
describe('trailingSlash is true', () => {
@@ -102,13 +108,20 @@ describe('resolveAbsoluteUrlWithPathname', () => {
102108
expect(resolver(new URL('https://example.com/foo?bar'))).toBe(
103109
'https://example.com/foo?bar'
104110
)
111+
expect(resolver('https://example.com/?foo=bar')).toBe(
112+
'https://example.com/?foo=bar'
113+
)
105114
})
106115

107116
it('should not add trailing slash to relative url with query', () => {
108117
expect(resolver('/foo?bar')).toBe('https://example.com/foo?bar')
109118
expect(resolver(new URL('/foo?bar', metadataBase))).toBe(
110119
'https://example.com/foo?bar'
111120
)
121+
expect(resolver('/?foo=bar')).toBe('https://example.com/?foo=bar')
122+
expect(resolver(new URL('/?foo=bar', metadataBase))).toBe(
123+
'https://example.com/?foo=bar'
124+
)
112125
})
113126

114127
it('should not add trailing slash to relative url that matches file pattern', () => {

packages/next/src/lib/metadata/resolvers/resolve-url.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,10 @@ function resolveAbsoluteUrlWithPathname(
114114
if (typeof result === 'string') {
115115
resolvedUrl = result
116116
} else {
117-
resolvedUrl = result.pathname === '/' ? result.origin : result.href
117+
resolvedUrl =
118+
result.pathname === '/' && result.searchParams.size === 0
119+
? result.origin
120+
: result.href
118121
}
119122

120123
// Add trailing slash if it's enabled for urls matches the condition

0 commit comments

Comments
 (0)