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
292 additions
and
49 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,72 @@ | ||
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 { | ||
constructor(input: string | null | undefined) { | ||
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: [key: string, value: unknown, options: CookieSerializeOptions]) { | ||
const store = super.set(...args) | ||
this.response.headers.append('set-cookie', store.get(args[0])) | ||
return store | ||
} | ||
delete(key: any) { | ||
const isDeleted = super.delete(key) | ||
|
||
if (isDeleted) { | ||
const setCookie = this.response.headers | ||
.get('set-cookie') | ||
?.split(', ') | ||
.filter((value) => !value.startsWith(`${key}=`)) | ||
.join(',') | ||
|
||
if (setCookie) { | ||
this.response.headers.set('set-cookie', setCookie) | ||
} else { | ||
this.response.headers.delete('set-cookie') | ||
} | ||
} | ||
|
||
return isDeleted | ||
} | ||
} | ||
|
||
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,98 @@ | ||
/* eslint-env jest */ | ||
|
||
import { Cookies } 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 = { | ||
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) | ||
}) |
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,75 @@ | ||
/* eslint-env jest */ | ||
|
||
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node' | ||
import { Crypto } from 'next/dist/server/web/sandbox/polyfills' | ||
import { Request } from 'next/dist/server/web/spec-compliant/request' | ||
import { Headers } from 'next/dist/server/web/spec-compliant/headers' | ||
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 | ||
global['Request'] = Request | ||
}) | ||
|
||
afterAll(() => { | ||
delete global['Blob'] | ||
delete global['crypto'] | ||
delete global['File'] | ||
delete global['Headers'] | ||
delete global['FormData'] | ||
delete global['ReadableStream'] | ||
delete global['TransformStream'] | ||
}) | ||
|
||
it('automatically modify `set-cookie` when interact with request.cookies', async () => { | ||
const { NextRequest } = await import( | ||
'next/dist/server/web/spec-extension/request' | ||
) | ||
|
||
const request = new NextRequest('https://vercel.com') | ||
|
||
request.cookies.set('foo', 'bar') | ||
expect(Object.fromEntries(request.headers.entries())['set-cookie']).toBe( | ||
'foo=bar; Path=/' | ||
) | ||
expect(request.cookies.get('foo')).toBe('foo=bar; Path=/') | ||
|
||
request.cookies.set('fooz', 'barz') | ||
expect(Object.fromEntries(request.headers.entries())['set-cookie']).toBe( | ||
'foo=bar; Path=/, fooz=barz; Path=/' | ||
) | ||
expect(request.cookies.get('fooz')).toBe('fooz=barz; Path=/') | ||
|
||
const firstDelete = request.cookies.delete('foo') | ||
expect(firstDelete).toBe(true) | ||
expect(Object.fromEntries(request.headers.entries())['set-cookie']).toBe( | ||
'fooz=barz; Path=/' | ||
) | ||
expect(request.cookies.get('foo')).toBe(undefined) | ||
|
||
const secondDelete = request.cookies.delete('fooz') | ||
expect(secondDelete).toBe(true) | ||
expect(Object.fromEntries(request.headers.entries())['set-cookie']).toBe( | ||
undefined | ||
) | ||
expect(request.cookies.get('fooz')).toBe(undefined) | ||
|
||
expect(request.cookies.size).toBe(0) | ||
}) | ||
|
||
it('request.cookie does not modify options', async () => { | ||
const { NextRequest } = await import( | ||
'next/dist/server/web/spec-extension/request' | ||
) | ||
|
||
const options = { maxAge: 10000 } | ||
const request = new NextRequest('https://vercel.com') | ||
request.cookies.set('cookieName', 'cookieValue', options) | ||
expect(options).toEqual({ maxAge: 10000 }) | ||
}) |
Oops, something went wrong.