Skip to content

Commit

Permalink
create setCookie function to add a Set-Cookie header on a response
Browse files Browse the repository at this point in the history
  • Loading branch information
broswen committed May 21, 2023
1 parent 71c904a commit ea9a6d8
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/setCookie.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import 'isomorphic-fetch'
import { describe, expect, it } from 'vitest'
import { status } from './status'
import {setCookie} from "./setCookie";

describe('setCookie("name", "value"): Response', () => {
it('creates a response with the set-cookie header', async () => {
const response = status(200)
setCookie(response, "name", "value")
expect(response.headers.get("set-cookie")).toBe("name=value")
})
it('creates a response with the set-cookie header using options', async () => {
const response = status(200)
setCookie(response, "name", "value", {
httpOnly: true,
secure: true,
})
expect(response.headers.get("set-cookie")).toBe("name=value; HttpOnly; Secure")
})
it('creates a response with the set-cookie header using all options', async () => {
const response = status(200)
const now = new Date();
setCookie(response, "name", "value", {
httpOnly: true,
secure: true,
expires: now,
maxAge: 1000,
path: "/",
domain: "itty.dev",
partitioned: true,
sameSite: "Strict"
})
expect(response.headers.get("set-cookie")).toBe(`name=value; Domain=itty.dev; Path=/; HttpOnly; Secure; Expires=${now.toUTCString()}; Max-Age=1000; Partitioned; SameSite=Strict`)
})
})
24 changes: 24 additions & 0 deletions src/setCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
type CookieOptions = {
domain?: string;
path?: string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
partitioned?: boolean;
secure?: boolean;
sameSite?: "Strict" | "Lax" | "None";
}

export const setCookie = (response: Response, name: string, value: string, options?: CookieOptions): Response => {
response.headers.append("Set-Cookie", `${name}=${value}\
${options?.domain ? `; Domain=${options.domain}`: ""}\
${options?.path ? `; Path=${options?.path}`: ""}\
${options?.httpOnly ? `; HttpOnly`: ""}\
${options?.secure ? `; Secure`: ""}\
${options?.expires? `; Expires=${options.expires.toUTCString()}`: ""}\
${options?.maxAge? `; Max-Age=${options.maxAge}`: ""}\
${options?.partitioned? `; Partitioned`: ""}\
${options?.sameSite? `; SameSite=${options.sameSite}`: ""}\
`)
return response;
}

0 comments on commit ea9a6d8

Please sign in to comment.