Skip to content

Commit 9db98e0

Browse files
committed
create setCookie function to add a Set-Cookie header on a response
1 parent 71c904a commit 9db98e0

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/setCookie.spec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import 'isomorphic-fetch'
2+
import { describe, expect, it } from 'vitest'
3+
import { status } from './status'
4+
import {setCookie} from "./setCookie";
5+
6+
describe('setCookie("name", "value"): Response', () => {
7+
it('creates a response with the set-cookie header', async () => {
8+
const response = status(200)
9+
setCookie(response, "name", "value")
10+
expect(response.headers.get("set-cookie")).toBe("name=value")
11+
})
12+
it('creates a response with the set-cookie header using options', async () => {
13+
const response = status(200)
14+
setCookie(response, "name", "value", {
15+
httpOnly: true,
16+
secure: true,
17+
})
18+
expect(response.headers.get("set-cookie")).toBe("name=value; HttpOnly; Secure")
19+
})
20+
it('creates a response with the set-cookie header using all options', async () => {
21+
const response = status(200)
22+
const now = new Date();
23+
setCookie(response, "name", "value", {
24+
httpOnly: true,
25+
secure: true,
26+
expires: now,
27+
maxAge: 1000,
28+
path: "/",
29+
domain: "itty.dev",
30+
partitioned: true,
31+
sameSite: "Strict"
32+
})
33+
expect(response.headers.get("set-cookie")).toBe(`name=value; Domain=itty.dev; Path=/; HttpOnly; Secure; Expires=${now.toUTCString()}; Max-Age=1000; Partitioned; SameSite=Strict`)
34+
})
35+
})

src/setCookie.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
type CookieOptions = {
2+
domain?: string;
3+
path?: string;
4+
expires?: Date;
5+
httpOnly?: boolean;
6+
maxAge?: number;
7+
partitioned?: boolean;
8+
secure?: boolean;
9+
sameSite?: "Strict" | "Lax" | "None";
10+
}
11+
12+
export const setCookie = (response: Response, name: string, value: string, options?: CookieOptions): Response => {
13+
response.headers.append("Set-Cookie", `${name}=${value}\
14+
${options?.domain ? `; Domain=${options.domain}`: ""}\
15+
${options?.path ? `; Path=${options?.path}`: ""}\
16+
${options?.httpOnly ? `; HttpOnly`: ""}\
17+
${options?.secure ? `; Secure`: ""}\
18+
${options?.expires? `; Expires=${options.expires.toUTCString()}`: ""}\
19+
${options?.maxAge? `; Max-Age=${options.maxAge}`: ""}\
20+
${options?.partitioned? `; Partitioned`: ""}\
21+
${options?.sameSite? `; SameSite=${options.sameSite}`: ""}\
22+
`)
23+
return response;
24+
}

0 commit comments

Comments
 (0)