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

fix encoding error with location and refresh headers #27003

Closed
16 changes: 14 additions & 2 deletions packages/next/server/next-server.ts
Expand Up @@ -934,13 +934,25 @@ export default class Server {
// we need to re-encode them here but still allow passing through
// values from rewrites/redirects
const stringifyQuery = (req: IncomingMessage, query: ParsedUrlQuery) => {
const initialQueryValues = Object.values((req as any).__NEXT_INIT_QUERY)
const initialQuery = (req as any).__NEXT_INIT_QUERY
const initialQueryValues: Array<string | string[]> =
Object.values(initialQuery)

return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (initialQueryValues.some((val) => val === value)) {
const queryContainsValue = (queryVal: string | string[]) =>
Array.isArray(queryVal)
? queryVal.includes(value)
: queryVal === value

if (
value in initialQuery ||
initialQueryValues.some(queryContainsValue)
) {
// Encode keys and values from initial query
return encodeURIComponent(value)
}

return value
},
})
Expand Down
20 changes: 20 additions & 0 deletions test/integration/custom-routes/test/index.test.js
Expand Up @@ -690,6 +690,26 @@ const runTests = (isDev = false) => {
expect(res.headers.get('refresh')).toBe(`0;url=/`)
})

it('should have correctly encoded query in location and refresh headers', async () => {
const res = await fetchViaHTTP(
appPort,
// Query unencoded is ?テスト=あ
'/redirect4?%E3%83%86%E3%82%B9%E3%83%88=%E3%81%82',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(308)

expect(res.headers.get('location').split('?')[1]).toBe(
'%E3%83%86%E3%82%B9%E3%83%88=%E3%81%82'
)
expect(res.headers.get('refresh')).toBe(
'0;url=/?%E3%83%86%E3%82%B9%E3%83%88=%E3%81%82'
)
})

it('should handle basic api rewrite successfully', async () => {
const data = await renderViaHTTP(appPort, '/api-hello')
expect(JSON.parse(data)).toEqual({ query: {} })
Expand Down