-
Notifications
You must be signed in to change notification settings - Fork 27.5k
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 NextResponse
- Loading branch information
Showing
6 changed files
with
343 additions
and
59 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
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) | ||
options.maxAge /= 1000 | ||
} | ||
|
||
if (options.path == null) { | ||
options.path = '/' | ||
} | ||
|
||
return options | ||
} | ||
|
||
const serializeValue = (value: unknown) => | ||
typeof value === 'object' ? `j:${JSON.stringify(value)}` : String(value) | ||
|
||
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) | ||
) | ||
) | ||
} | ||
} | ||
|
||
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 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}` | ||
) | ||
} 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) { | ||
const isDeleted = super.delete(key) | ||
|
||
if (isDeleted) { | ||
const setCookie = serializeCookie( | ||
deserializeCookie(this.response).filter( | ||
(value) => !value.startsWith(`${key}=`) | ||
) | ||
) | ||
|
||
if (setCookie) { | ||
this.response.headers.set('set-cookie', setCookie) | ||
} else { | ||
this.response.headers.delete('set-cookie') | ||
} | ||
} | ||
|
||
return isDeleted | ||
} | ||
clear() { | ||
this.response.headers.delete('set-cookie') | ||
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
/* eslint-env jest */ | ||
|
||
import { | ||
Cookies, | ||
CookieSerializeOptions, | ||
} from 'next/dist/server/web/spec-extension/cookies' | ||
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node' | ||
import { Headers } from 'next/dist/server/web/spec-compliant/headers' | ||
import { Crypto } from 'next/dist/server/web/sandbox/polyfills' | ||
import * as streams from 'web-streams-polyfill/ponyfill' | ||
|
||
beforeAll(() => { | ||
global['Blob'] = Blob | ||
global['crypto'] = new Crypto() | ||
global['File'] = File | ||
global['FormData'] = FormData | ||
global['Headers'] = Headers | ||
global['ReadableStream'] = streams.ReadableStream | ||
global['TransformStream'] = streams.TransformStream | ||
}) | ||
|
||
afterAll(() => { | ||
delete global['Blob'] | ||
delete global['crypto'] | ||
delete global['File'] | ||
delete global['Headers'] | ||
delete global['FormData'] | ||
delete global['ReadableStream'] | ||
delete global['TransformStream'] | ||
}) | ||
|
||
it('create a empty cookies bag', async () => { | ||
const cookies = new Cookies() | ||
expect(Object.entries(cookies)).toStrictEqual([]) | ||
}) | ||
|
||
it('create a cookies bag from string', async () => { | ||
const cookies = new Cookies('foo=bar; equation=E%3Dmc%5E2') | ||
expect(Array.from(cookies.entries())).toStrictEqual([ | ||
['foo', 'foo=bar; Path=/'], | ||
['equation', 'equation=E%3Dmc%5E2; Path=/'], | ||
]) | ||
}) | ||
|
||
it('.set', async () => { | ||
const cookies = new Cookies() | ||
cookies.set('foo', 'bar') | ||
expect(Array.from(cookies.entries())).toStrictEqual([ | ||
['foo', 'foo=bar; Path=/'], | ||
]) | ||
}) | ||
|
||
it('.set with options', async () => { | ||
const cookies = new Cookies() | ||
|
||
const options: CookieSerializeOptions = { | ||
path: '/', | ||
maxAge: 1000 * 60 * 60 * 24 * 7, | ||
httpOnly: true, | ||
sameSite: 'strict', | ||
domain: 'example.com', | ||
} | ||
|
||
cookies.set('foo', 'bar', options) | ||
|
||
expect(options).toStrictEqual({ | ||
path: '/', | ||
maxAge: 1000 * 60 * 60 * 24 * 7, | ||
httpOnly: true, | ||
sameSite: 'strict', | ||
domain: 'example.com', | ||
}) | ||
|
||
const [[key, value]] = Array.from(cookies.entries()) | ||
const values = value.split('; ') | ||
|
||
expect(key).toBe('foo') | ||
|
||
expect(values).toStrictEqual([ | ||
'foo=bar', | ||
'Max-Age=604800', | ||
'Domain=example.com', | ||
'Path=/', | ||
expect.stringContaining('Expires='), | ||
'HttpOnly', | ||
'SameSite=Strict', | ||
]) | ||
}) | ||
|
||
it('.delete', async () => { | ||
const cookies = new Cookies() | ||
cookies.set('foo', 'bar') | ||
cookies.delete('foo') | ||
expect(Array.from(cookies.entries())).toStrictEqual([]) | ||
}) | ||
|
||
it('.has', async () => { | ||
const cookies = new Cookies() | ||
cookies.set('foo', 'bar') | ||
expect(cookies.has('foo')).toBe(true) | ||
}) |
Oops, something went wrong.