Unverified Commit b6e0c350 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Update the mutableCookies class to accept extra options (#48877)

This PR changes `mutableCookies` from `RequestCookies` to a
`ResponseCookies` instance, and it now accepts extra options for each
cookie. Take a look at the tests for more details.

cc @styfle

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent f7baa567
import { RequestCookiesAdapter } from '../../server/web/spec-extension/adapters/request-cookies'
import {
type ReadonlyRequestCookies,
RequestCookiesAdapter,
} from '../../server/web/spec-extension/adapters/request-cookies'
import { HeadersAdapter } from '../../server/web/spec-extension/adapters/headers'
import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { requestAsyncStorage } from './request-async-storage'
......@@ -48,7 +51,9 @@ export function cookies() {
asyncActionStore &&
(asyncActionStore.isAction || asyncActionStore.isAppRoute)
) {
return requestStore.mutableCookies
// We can't conditionally return different types here based on the context.
// To avoid confusion, we always return the readonly type here.
return requestStore.mutableCookies as unknown as ReadonlyRequestCookies
}
return requestStore.cookies
......
import type { AsyncLocalStorage } from 'async_hooks'
import type { RequestCookies } from '../../server/web/spec-extension/cookies'
import type { ResponseCookies } from '../../server/web/spec-extension/cookies'
import type { PreviewData } from '../../../types'
import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies'
......@@ -9,7 +9,7 @@ import { createAsyncLocalStorage } from './async-local-storage'
export interface RequestStore {
readonly headers: ReadonlyHeaders
readonly cookies: ReadonlyRequestCookies
readonly mutableCookies: RequestCookies
readonly mutableCookies: ResponseCookies
readonly previewData: PreviewData
}
......
......@@ -18,7 +18,7 @@ import {
RequestCookiesAdapter,
type ReadonlyRequestCookies,
} from '../web/spec-extension/adapters/request-cookies'
import { RequestCookies } from '../web/spec-extension/cookies'
import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'
function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const cleaned = HeadersAdapter.from(headers)
......@@ -39,7 +39,7 @@ function getCookies(
function getMutableCookies(
headers: Headers | IncomingHttpHeaders,
res: ServerResponse | BaseNextResponse | undefined
): RequestCookies {
): ResponseCookies {
const cookies = new RequestCookies(HeadersAdapter.from(headers))
return MutableRequestCookiesAdapter.seal(cookies, res)
}
......@@ -89,7 +89,7 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
const cache: {
headers?: ReadonlyHeaders
cookies?: ReadonlyRequestCookies
mutableCookies?: RequestCookies
mutableCookies?: ResponseCookies
} = {}
const store: RequestStore = {
......
......@@ -351,7 +351,9 @@ export class AppRouteRouteModule extends RouteModule<
if (requestStore && requestStore.mutableCookies) {
const modifiedCookieValues = (
requestStore.mutableCookies as any
)[SYMBOL_MODIFY_COOKIE_VALUES] as [string, string][]
)[SYMBOL_MODIFY_COOKIE_VALUES] as NonNullable<
ReturnType<InstanceType<typeof ResponseCookies>['get']>
>[]
if (modifiedCookieValues.length) {
// Return a new response that extends the response with
// the modified cookies as fallbacks. `res`' cookies
......@@ -359,22 +361,39 @@ export class AppRouteRouteModule extends RouteModule<
const resCookies = new ResponseCookies(
HeadersAdapter.from(res.headers)
)
const finalCookies = resCookies.getAll()
const returnedCookies = resCookies.getAll()
// Set the modified cookies as fallbacks.
modifiedCookieValues.forEach((cookie) =>
resCookies.set(cookie[0], cookie[1])
)
for (const cookie of modifiedCookieValues) {
resCookies.set(cookie)
}
// Set the original cookies as the final values.
finalCookies.forEach((cookie) => resCookies.set(cookie))
for (const cookie of returnedCookies) {
resCookies.set(cookie)
}
const responseHeaders = new Headers({})
// Set all the headers except for the cookies.
res.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'set-cookie') {
responseHeaders.append(key, value)
}
})
// Set the final cookies, need to append cookies one
// at a time otherwise it might not work in some browsers.
resCookies.getAll().forEach((cookie) => {
const tempCookies = new ResponseCookies(new Headers())
tempCookies.set(cookie)
responseHeaders.append(
'Set-Cookie',
tempCookies.toString()
)
})
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: {
...res.headers,
'Set-Cookie': resCookies.toString(),
},
headers: responseHeaders,
})
}
}
......
......@@ -2,6 +2,7 @@ import type { RequestCookies } from '../cookies'
import type { BaseNextResponse } from '../../../base-http'
import type { ServerResponse } from 'http'
import { ResponseCookies } from '../cookies'
import { ReflectAdapter } from './reflect'
/**
......@@ -43,27 +44,37 @@ export class RequestCookiesAdapter {
export const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies')
type ResponseCookie = NonNullable<
ReturnType<InstanceType<typeof ResponseCookies>['get']>
>
export class MutableRequestCookiesAdapter {
public static seal(
cookies: RequestCookies,
res: ServerResponse | BaseNextResponse | undefined
): RequestCookies {
let modifiedValues: [string, string][] = []
): ResponseCookies {
const responseCookes = new ResponseCookies(new Headers())
for (const cookie of cookies.getAll()) {
responseCookes.set(cookie)
}
let modifiedValues: ResponseCookie[] = []
const modifiedCookies = new Set<string>()
const updateResponseCookies = () => {
const allCookies = cookies.getAll()
modifiedValues = allCookies
.filter((c) => modifiedCookies.has(c.name))
.map((c) => [c.name, c.value])
const allCookies = responseCookes.getAll()
modifiedValues = allCookies.filter((c) => modifiedCookies.has(c.name))
if (res) {
res.setHeader(
'Set-Cookie',
modifiedValues.map((c) => `${c[0]}=${c[1]}`)
)
const serializedCookies: string[] = []
for (const cookie of modifiedValues) {
const tempCookies = new ResponseCookies(new Headers())
tempCookies.set(cookie)
serializedCookies.push(tempCookies.toString())
}
res.setHeader('Set-Cookie', serializedCookies)
}
}
return new Proxy(cookies, {
return new Proxy(responseCookes, {
get(target, prop, receiver) {
switch (prop) {
// A special symbol to get the modified cookie values
......@@ -72,26 +83,13 @@ export class MutableRequestCookiesAdapter {
// TODO: Throw error if trying to set a cookie after the response
// headers have been set.
case 'clear':
return function () {
for (const c of cookies.getAll()) {
modifiedCookies.add(c.name)
}
try {
return cookies.clear()
} finally {
updateResponseCookies()
}
}
case 'delete':
return function (names: string | string[]) {
if (Array.isArray(names)) {
names.forEach((name) => modifiedCookies.add(name))
} else {
modifiedCookies.add(names)
}
return function (...args: [string] | [ResponseCookie]) {
modifiedCookies.add(
typeof args[0] === 'string' ? args[0] : args[0].name
)
try {
return cookies.delete(names)
target.delete(...args)
} finally {
updateResponseCookies()
}
......@@ -99,25 +97,14 @@ export class MutableRequestCookiesAdapter {
case 'set':
return function (
...args:
| [string, string]
| [
options: NonNullable<
ReturnType<InstanceType<typeof RequestCookies>['get']>
>
]
| [key: string, value: string, cookie?: Partial<ResponseCookie>]
| [options: ResponseCookie]
) {
const [key, value] = args
if (typeof key === 'string') {
modifiedCookies.add(key)
try {
return cookies.set(key, value!)
} finally {
updateResponseCookies()
}
}
modifiedCookies.add(key.name)
modifiedCookies.add(
typeof args[0] === 'string' ? args[0] : args[0].name
)
try {
return cookies.set(key)
return target.set(...args)
} finally {
updateResponseCookies()
}
......
......@@ -56,10 +56,12 @@ createNextDescribe(
it('should support setting cookies in route handlers with the correct overrides', async () => {
const res = await next.fetch('/handler')
const setCookieHeader = res.headers.get('set-cookie')
expect(setCookieHeader).toInclude('bar=bar2;')
expect(setCookieHeader).toInclude('baz=baz2;')
expect(setCookieHeader).toInclude('foo=foo1;')
const setCookieHeader = res.headers.get('set-cookie') as string[]
expect(setCookieHeader).toContain('bar=bar2; Path=/')
expect(setCookieHeader).toContain('baz=baz2; Path=/')
expect(setCookieHeader).toContain('foo=foo1; Path=/')
expect(setCookieHeader).toContain('test1=value1; Path=/; Secure')
expect(setCookieHeader).toContain('test2=value2; Path=/handler; HttpOnly')
})
it('should support formData and redirect', async () => {
......
......@@ -3,8 +3,22 @@ import { cookies } from 'next/headers'
export const GET = async () => {
cookies().set('foo', 'foo1')
cookies().set('bar', 'bar1')
// Key, value, options
cookies().set('test1', 'value1', { secure: true })
// One object
cookies().set({
name: 'test2',
value: 'value2',
httpOnly: true,
path: '/handler',
})
// Cookies here will be merged with the ones above
return new Response('Hello, world!', {
headers: [
['Content-Type', 'text/custom'],
['Set-Cookie', 'bar=bar2'],
['Set-Cookie', 'baz=baz2'],
],
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment