hono-cookie-state
v0.1.4
Published
Simple library to persist data / states in cookies for Hono, securely and with type-safety.
Readme
hono-cookie-state 
Overview
hono-cookie-state is a simple library to persist data / states in cookies for Hono, securely (via iron-webcrypto) and with type-safety.
Features
- 👌 TypeScript
Usage
Install package
# npm
npm install -D hono-cookie-state
# bun
bun add -D hono-cookie-state
# pnpm
pnpm install -D hono-cookie-stateImport and use
import type { CookieState } from 'hono-cookie-state'
import { createCookieState } from 'hono-cookie-state'
// Usage is as simple .use() the created middleware, and just update the state's data, the cookie will automatically be updated when the data has changed, or is near expiration with `autoRefreshSession=true` (default)
const app = new Hono()
.use(createCookieState({
key: 'hiWorld',
secret: 'password_at_least_32_characters!',
cookieOptions: {
maxAge: 90 * 60, // 90 mins
sameSite: 'None',
secure: true,
path: '/',
httpOnly: true,
},
}))
// For simple inline usage, variable type is automatically populated to context chain
.get('/sample', async (c) => {
const state = c.var.hiWorld // is of type CookieState<any>
state.data.hi = 'world'
})
// For more complex usage, you can populate Hono's init Env:
const app = new Hono<{ Variables: { hiWorld: CookieState<{ hello: string }> } }>()
// Or pass the data type into createCookieState, note you need to also pass the key as the second generic, due to TS limitation:
createCookieState<{ hello: string }, 'hiWorld'>({
key: 'hiWorld',
secret: 'password_at_least_32_characters!',
})Roadmap
- Chunked cookie support
- Awaits honojs/hono#4447
Credits and Notes
This package copies the inline, rewritten iron-crypto.ts and base64url encoding.ts from h3
