Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/omar2205/squishy_cookies

Easily sign and verify cookies
https://github.com/omar2205/squishy_cookies

cookie cookies deno typescript

Last synced: 1 day ago
JSON representation

Easily sign and verify cookies

Awesome Lists containing this project

README

        

# Squishy Cookies 🍪

Easily sign and verify cookies.

## Usage

```ts
import {
createSignedCookie, verifySignedCookie,
} from 'https://deno.land/x/squishy_cookies/mod.ts'

const COOKIE_SECRET = Deno.env.get('COOKIE_SECRET') || 'super_secret'

// 1. Create a signed cookie

// Optional, headers or cookie string (to be used in Set-cookie header)
const { headers, cookie } = await createSignedCookie(
'id', '1', COOKIE_SECRET,
{ httpOnly: true, path: '/' }
)
return new Response(page, { headers })

// or

const headers = new Headers()
headers.append('set-cookie', cookie)

// 2. Verifying a cookie

headers.append('cookie', cookie) // verifySignedCookie will search for 'cookie' header
const userId = await verifySignedCookie(headers, 'id', COOKIE_SECRET)
// userId is false if the verification failed or the cookie value
if (userId) {
const user = await getUserById(userId.split('.')[0])
}

```

### Tip to add multiple cookies
```ts
const { cookie: cookie1 } = await createSignedCookie(/* ... */)
const { cookie: cookie2 } = await createSignedCookie(/* ... */)

const response = new Response(someHTML, {
// using headers as an array of arrays let you use
// multiple headers with the same name
headers: [
['Set-cookie', cookie1],
['Set-cookie', cookie2],
]
})
```