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 cookie merging in Server Action redirections #61113

Merged
merged 6 commits into from
Jan 27, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions packages/next/src/server/app-render/action-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ import {
} from '../lib/server-action-request-meta'
import { isCsrfOriginAllowed } from './csrf-protection'
import { warn } from '../../build/output/log'
import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import { fromNodeOutgoingHttpHeaders } from '../web/utils'

function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query)
Expand Down Expand Up @@ -70,18 +73,13 @@ function getForwardedHeaders(
): Headers {
// Get request headers and cookies
const requestHeaders = req.headers
const requestCookies = requestHeaders['cookie'] ?? ''
const requestCookies = new RequestCookies(HeadersAdapter.from(requestHeaders))

// Get response headers and Set-Cookie header
// Get response headers and cookies
const responseHeaders = res.getHeaders()
const rawSetCookies = responseHeaders['set-cookie']
const setCookies = (
Array.isArray(rawSetCookies) ? rawSetCookies : [rawSetCookies]
).map((setCookie) => {
// remove the suffixes like 'HttpOnly' and 'SameSite'
const [cookie] = `${setCookie}`.split(';', 1)
return cookie
})
const responseCookies = new ResponseCookies(
fromNodeOutgoingHttpHeaders(responseHeaders)
)

// Merge request and response headers
const mergedHeaders = filterReqHeaders(
Expand All @@ -92,11 +90,18 @@ function getForwardedHeaders(
actionsForbiddenHeaders
) as Record<string, string>

// Merge cookies
const mergedCookies = requestCookies.split('; ').concat(setCookies).join('; ')
// Merge cookies into requestCookies, so responseCookies always take precedence
// and overwrite/delete those from requestCookies.
responseCookies.getAll().forEach((cookie) => {
if (typeof cookie.value === 'undefined') {
requestCookies.delete(cookie.name)
} else {
requestCookies.set(cookie)
}
})

// Update the 'cookie' header with the merged cookies
mergedHeaders['cookie'] = mergedCookies
mergedHeaders['cookie'] = requestCookies.toString()

// Remove headers that should not be forwarded
delete mergedHeaders['transfer-encoding']
Expand Down
21 changes: 21 additions & 0 deletions test/e2e/app-dir/actions/app-action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,27 @@ createNextDescribe(
expect(responseCodes).toEqual([303])
})

it('merges cookies correctly when redirecting', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm surprised that this test seems to be passing on canary without the changes in the PR, is there something more specific needed to trigger the buggy behavior?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's very strange - during a manual testing of cookies().delete('foo') it didn't work.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ztanner Okay I know what's happening! On an action redirection, cookies().delete('foo') only sets the value to '' (an empty string), not actually deleting it.

Here's a reproduction:

CleanShot.2024-01-26.at.21.32.04.mp4

After clicking on the button, that /2 route should display deleted instead of foo=. The client cookie was correctly updated as it worked after refreshing though.

const browser = await next.browser('/redirects/action-redirect')

// set foo and bar to be both 1, and verify
await browser.eval(
`document.cookie = 'bar=1; Path=/'; document.cookie = 'foo=1; Path=/';`
)
await browser.refresh()
expect(await browser.elementByCss('h1').text()).toBe('foo=1; bar=1')

// delete foo and set bar to 2, redirect
await browser.elementById('redirect-with-cookie-mutation').click()
await check(
() => browser.url(),
/\/redirects\/action-redirect\/redirect-target/
)

// verify that the cookies were merged correctly
expect(await browser.elementByCss('h1').text()).toBe('foo=; bar=2')
})

it.each(['307', '308'])(
`redirects properly when server action handler redirects with a %s status code`,
async (statusCode) => {
Expand Down
26 changes: 26 additions & 0 deletions test/e2e/app-dir/actions/app/redirects/action-redirect/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'

export default function Page() {
const foo = cookies().get('foo')
const bar = cookies().get('bar')
return (
<div>
<h1>
foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''}
</h1>
<form
action={async () => {
'use server'
cookies().delete('foo')
cookies().set('bar', '2')
redirect('/redirects/action-redirect/redirect-target')
}}
>
<button type="submit" id="redirect-with-cookie-mutation">
Set Cookies and Redirect
</button>
</form>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { cookies } from 'next/headers'

export default function Page() {
const foo = cookies().get('foo')
const bar = cookies().get('bar')
return (
<div>
<h1>
foo={foo ? foo.value : ''}; bar={bar ? bar.value : ''}
</h1>
</div>
)
}
Loading