diff --git a/packages/next/src/server/async-storage/request-async-storage-wrapper.ts b/packages/next/src/server/async-storage/request-async-storage-wrapper.ts index 634e4c13be2ee..09a863ea6d994 100644 --- a/packages/next/src/server/async-storage/request-async-storage-wrapper.ts +++ b/packages/next/src/server/async-storage/request-async-storage-wrapper.ts @@ -44,6 +44,35 @@ export type RequestContext = { renderOpts?: RenderOpts } +/** + * If middleware set cookies in this request (indicated by `x-middleware-set-cookie`), + * then merge those into the existing cookie object, so that when `cookies()` is accessed + * it's able to read the newly set cookies. + */ +function mergeMiddlewareCookies( + req: RequestContext['req'], + existingCookies: RequestCookies | ResponseCookies +) { + if ( + 'x-middleware-set-cookie' in req.headers && + typeof req.headers['x-middleware-set-cookie'] === 'string' + ) { + const setCookieValue = req.headers['x-middleware-set-cookie'] + const responseHeaders = new Headers() + + for (const cookie of splitCookiesString(setCookieValue)) { + responseHeaders.append('set-cookie', cookie) + } + + const responseCookies = new ResponseCookies(responseHeaders) + + // Transfer cookies from ResponseCookies to RequestCookies + for (const cookie of responseCookies.getAll()) { + existingCookies.set(cookie.name, cookie.value ?? '') + } + } +} + export const RequestAsyncStorageWrapper: AsyncStorageWrapper< RequestStore, RequestContext @@ -100,24 +129,7 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< HeadersAdapter.from(req.headers) ) - if ( - 'x-middleware-set-cookie' in req.headers && - typeof req.headers['x-middleware-set-cookie'] === 'string' - ) { - const setCookieValue = req.headers['x-middleware-set-cookie'] - const responseHeaders = new Headers() - - for (const cookie of splitCookiesString(setCookieValue)) { - responseHeaders.append('set-cookie', cookie) - } - - const responseCookies = new ResponseCookies(responseHeaders) - - // Transfer cookies from ResponseCookies to RequestCookies - for (const cookie of responseCookies.getAll()) { - requestCookies.set(cookie.name, cookie.value ?? '') - } - } + mergeMiddlewareCookies(req, requestCookies) // Seal the cookies object that'll freeze out any methods that could // mutate the underlying data. @@ -128,11 +140,15 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< }, get mutableCookies() { if (!cache.mutableCookies) { - cache.mutableCookies = getMutableCookies( + const mutableCookies = getMutableCookies( req.headers, renderOpts?.onUpdateCookies || (res ? defaultOnUpdateCookies : undefined) ) + + mergeMiddlewareCookies(req, mutableCookies) + + cache.mutableCookies = mutableCookies } return cache.mutableCookies }, diff --git a/test/e2e/app-dir/app-middleware/app-middleware.test.ts b/test/e2e/app-dir/app-middleware/app-middleware.test.ts index 778bce5918ad9..c412beb622542 100644 --- a/test/e2e/app-dir/app-middleware/app-middleware.test.ts +++ b/test/e2e/app-dir/app-middleware/app-middleware.test.ts @@ -171,6 +171,31 @@ createNextDescribe( ) }) }) + + it('should be possible to read cookies that are set during the middleware handling of a server action', async () => { + const browser = await next.browser('/rsc-cookies') + const initialRandom1 = await browser.elementById('rsc-cookie-1').text() + const initialRandom2 = await browser.elementById('rsc-cookie-2').text() + const totalCookies = await browser.elementById('total-cookies').text() + + // cookies were set in middleware, assert they are present and match the Math.random() pattern + expect(initialRandom1).toMatch(/Cookie 1: \d+\.\d+/) + expect(initialRandom2).toMatch(/Cookie 2: \d+\.\d+/) + expect(totalCookies).toBe('Total Cookie Length: 2') + + expect(await browser.eval('document.cookie')).toBeTruthy() + + await browser.deleteCookies() + + // assert that document.cookie is empty + expect(await browser.eval('document.cookie')).toBeFalsy() + + await browser.elementById('submit-server-action').click() + + await retry(() => { + expect(next.cliOutput).toMatch(/\[Cookie From Action\]: \d+\.\d+/) + }) + }) } ) diff --git a/test/e2e/app-dir/app-middleware/app/rsc-cookies/page.js b/test/e2e/app-dir/app-middleware/app/rsc-cookies/page.js index 12dde4cb1b1f1..774e3003953ed 100644 --- a/test/e2e/app-dir/app-middleware/app/rsc-cookies/page.js +++ b/test/e2e/app-dir/app-middleware/app/rsc-cookies/page.js @@ -11,6 +11,20 @@ export default function Page() {

Total Cookie Length: {cookies().size}

To Delete Cookies Route + +
{ + 'use server' + console.log( + '[Cookie From Action]:', + cookies().get('rsc-cookie-value-1')?.value + ) + }} + > + +
) }