Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: better cookies API for Edge Functions (#36478)
This PR introduces a more predictable API to manipulate cookies in an Edge Function context. ```js const response = new NextResponse() // set a cookie response.cookies.set('foo, 'bar') // => set-cookie: 'foo=bar; Path=/'` // set another cookie response.cookies.set('fooz, 'barz') // => set-cookie: 'foo=bar; Path=/, fooz=barz; Path=/'` // delete a cookie means mark it as expired response.cookies.delete('foo') // => set-cookie: 'foo=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT, fooz=barz; Path=/'` // clear all cookies means mark all of them as expired response.cookies.clear() // => set-cookie: 'fooz=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT, foo=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT'` ``` This new cookies API uses [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) interface, and it's available for `NextRequest` and `NextResponse`. Additionally, you can pass a specific cookies option as a third argument in `set` method: ```js response.cookies.set('foo', 'bar', { path: '/', maxAge: 60 * 60 * 24 * 7, httpOnly: true, sameSite: 'strict', domain: 'example.com' } ``` **Note**: `maxAge` it's in seconds rather than milliseconds. Any cookie manipulation will be reflected over the `set-cookie` header, transparently. closes #31719
- Loading branch information
Showing
9 changed files
with
374 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import cookie from 'next/dist/compiled/cookie' | ||
import { CookieSerializeOptions } from '../types' | ||
|
||
const normalizeCookieOptions = (options: CookieSerializeOptions) => { | ||
options = Object.assign({}, options) | ||
|
||
if (options.maxAge) { | ||
options.expires = new Date(Date.now() + options.maxAge * 1000) | ||
} | ||
|
||
if (options.path == null) { | ||
options.path = '/' | ||
} | ||
|
||
return options | ||
} | ||
|
||
const serializeValue = (value: unknown) => | ||
typeof value === 'object' ? `j:${JSON.stringify(value)}` : String(value) | ||
|
||
const serializeExpiredCookie = ( | ||
key: string, | ||
options: CookieSerializeOptions = {} | ||
) => | ||
cookie.serialize(key, '', { | ||
expires: new Date(0), | ||
path: '/', | ||
...options, | ||
}) | ||
|
||
const deserializeCookie = (input: Request | Response): string[] => { | ||
const value = input.headers.get('set-cookie') | ||
return value !== undefined && value !== null ? value.split(', ') : [] | ||
} | ||
|
||
const serializeCookie = (input: string[]) => input.join(', ') | ||
|
||
export class Cookies extends Map<string, any> { | ||
constructor(input?: string | null) { | ||
const parsedInput = typeof input === 'string' ? cookie.parse(input) : {} | ||
super(Object.entries(parsedInput)) | ||
} | ||
set(key: string, value: unknown, options: CookieSerializeOptions = {}) { | ||
return super.set( | ||
key, | ||
cookie.serialize( | ||
key, | ||
serializeValue(value), | ||
normalizeCookieOptions(options) | ||
) | ||
) | ||
} | ||
} | ||
|
||
export class NextCookies extends Cookies { | ||
response: Request | Response | ||
|
||
constructor(response: Request | Response) { | ||
super(response.headers.get('cookie')) | ||
this.response = response | ||
} | ||
set = (...args: Parameters<Cookies['set']>) => { | ||
const isAlreadyAdded = super.has(args[0]) | ||
const store = super.set(...args) | ||
|
||
if (isAlreadyAdded) { | ||
const setCookie = serializeCookie( | ||
deserializeCookie(this.response).filter( | ||
(value) => !value.startsWith(`${args[0]}=`) | ||
) | ||
) | ||
|
||
if (setCookie) { | ||
this.response.headers.set( | ||
'set-cookie', | ||
[store.get(args[0]), setCookie].join(', ') | ||
) | ||
} else { | ||
this.response.headers.set('set-cookie', store.get(args[0])) | ||
} | ||
} else { | ||
this.response.headers.append('set-cookie', store.get(args[0])) | ||
} | ||
|
||
return store | ||
} | ||
delete = (key: any, options: CookieSerializeOptions = {}) => { | ||
const isDeleted = super.delete(key) | ||
|
||
if (isDeleted) { | ||
const setCookie = serializeCookie( | ||
deserializeCookie(this.response).filter( | ||
(value) => !value.startsWith(`${key}=`) | ||
) | ||
) | ||
const expiredCookie = serializeExpiredCookie(key, options) | ||
this.response.headers.set( | ||
'set-cookie', | ||
[expiredCookie, setCookie].join(', ') | ||
) | ||
} | ||
|
||
return isDeleted | ||
} | ||
clear = (options: CookieSerializeOptions = {}) => { | ||
const expiredCookies = Array.from(super.keys()) | ||
.map((key) => serializeExpiredCookie(key, options)) | ||
.join(', ') | ||
|
||
if (expiredCookies) this.response.headers.set('set-cookie', expiredCookies) | ||
return super.clear() | ||
} | ||
} | ||
|
||
export { CookieSerializeOptions } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.