Skip to content

omar2205/squishy_cookies

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Squishy Cookies 🍪

Easily sign and verify cookies.

Usage

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

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],
  ]
})