Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Append the fragment in NextUrl.toString() #41501

Merged
merged 4 commits into from Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/next/server/web/next-url.ts
Expand Up @@ -181,7 +181,7 @@ export class NextURL {
get href() {
const pathname = this.formatPathname()
const search = this.formatSearch()
return `${this.protocol}//${this.host}${pathname}${search}`
return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`
}

set href(url: string) {
Expand Down
5 changes: 5 additions & 0 deletions test/e2e/middleware-redirects/app/middleware.js
Expand Up @@ -75,4 +75,9 @@ export async function middleware(request) {
url.searchParams.delete('pathname')
return Response.redirect(url)
}

if (url.pathname === '/with-fragment') {
console.log(String(new URL('/new-home#fragment', url)))
return Response.redirect(new URL('/new-home#fragment', url))
}
}
14 changes: 14 additions & 0 deletions test/e2e/middleware-redirects/test/index.test.ts
Expand Up @@ -157,6 +157,20 @@ describe('Middleware Redirect', () => {
.join('\n')
expect(errors).not.toContain('Failed to lookup route')
})

// A regression test for https://github.com/vercel/next.js/pull/41501
it(`${label}should redirect with a fragment`, async () => {
const res = await fetchViaHTTP(next.url, `${locale}/with-fragment`)
const html = await res.text()
const $ = cheerio.load(html)
const browser = await webdriver(next.url, `${locale}/with-fragment`)
try {
expect(await browser.eval(`window.location.hash`)).toBe(`#fragment`)
} finally {
await browser.close()
}
expect($('.title').text()).toBe('Welcome to a new page')
})
}
tests()
testsWithLocale()
Expand Down
9 changes: 9 additions & 0 deletions test/unit/web-runtime/next-url.test.ts
Expand Up @@ -39,6 +39,15 @@ it('does noop changing to an invalid hostname', () => {
expect(url.toString()).toEqual('https://foo.com/example')
})

it('preserves the fragment', () => {
const url = new NextURL(
'https://example.com/path/to?param1=value1#this-is-fragment'
)
expect(url.toString()).toEqual(
'https://example.com/path/to?param1=value1#this-is-fragment'
)
})

it('allows to change the whole href', () => {
const url = new NextURL('https://localhost.com/foo')
expect(url.hostname).toEqual('localhost.com')
Expand Down