hono-cookie-state
    Preparing search index...

    hono-cookie-state

    Hono Cookie State

    hono-cookie-state TypeScript heart icon

    npm version npm downloads Codecov Bundlejs TypeDoc

    hono-cookie-state is a simple library to persist data / states in cookies for Hono, securely (via iron-webcrypto) and with type-safety.

    • 👌 TypeScript
    # npm
    npm install -D hono-cookie-state

    # bun
    bun add -D hono-cookie-state

    # pnpm
    pnpm install -D hono-cookie-state
    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!',
    })

    This package copies the inline, rewritten iron-crypto.ts and base64url encoding.ts from h3

    License