npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@brightcove/hono-sessions

v1.0.8

Published

A session manager for Hono that uses DynamoDB as session storage by default. Supports session retrieval by cookie or access token.

Downloads

137

Maintainers

sachin-brightcovesachin-brightcovealexey.kremsaalexey.kremsamelinda.darvasimelinda.darvasijose.luis.sanchezjose.luis.sanchezpedro-cruzpedro-cruzgabor.kiacz.brightcovegabor.kiacz.brightcoveadambertalanbcadambertalanbcmiklospocsaji_bcmiklospocsaji_bcmaraizamaraizaskarukamannaskarukamannaaviel_resnickaviel_resnicknorma.gonzaleznorma.gonzalezjvaldez1jvaldez1fsalazarbcfsalazarbccognatusbgscognatusbgsmbalasubramaniammbalasubramaniamssahssahdgonzalez89dgonzalez89areis10areis10vmnavarrovmnavarroalfredo-reyesalfredo-reyesjterranovajterranovajfloresbcjfloresbcmlopez.bmlopez.bttabrilla-bcttabrilla-bcmsivallsmsivallssstevanussstevanusrwbarber2rwbarber2rwingerrwingerbcc-bfranklinbcc-bfranklinapenigalapatiapenigalapatilmaultsbylmaultsbysravan.pbrsravan.pbrijunaidfijunaidfmgoncalvesmgoncalvesmfregozomfregozoareveloarevelomadhu_gmadhu_ghugocjimhugocjimdaniel_camposdaniel_camposkevin.schickkevin.schickm.morrisonm.morrisonuomaruomarabarstowbcabarstowbcsbarathansbarathankpandiyarajankpandiyarajanimoronesimoroneswalterseymourbcwalterseymourbcddashkevichddashkevichalbertogomezalbertogomezgestrada-brgestrada-bramillerbrightcoveamillerbrightcovelvohralvohramcho-bcmcho-bcawaldronawaldrondawnpackodawnpackoldominguezldominguezbc-srimron-soutterbc-srimron-soutterrsilva_brightcoversilva_brightcovejoeyleshjoeyleshlmelchorx1lmelchorx1juan-sanchezjuan-sanchezeolveraeolveracloewer_bccloewer_bccarredondocarredondobrianhsubrianhsuniklagbrightcoveniklagbrightcovetsraveling_bctsraveling_bcbcbcliffordbcbcliffordbc-acgarciabc-acgarciaadavila1adavila1kreynoldskreynoldsbgs-devopsbgs-devopsalbinjohnsonalbinjohnsonrtezerartezerabcmneilbcmneilrandresfrandresfv.kozlov_bcv.kozlov_bcnagendra_mnagendra_mmichaelmccarthybcmichaelmccarthybcponeill-bcovponeill-bcovmdeltorobcovmdeltorobcovjmohneycovejmohneycoveinbc01inbc01aperezbrightcoveaperezbrightcoveireyes94ireyes94brightcove-adminbrightcove-admintedktedkabradley-brightcoveabradley-brightcovebc-alivebc-alivelasanchezclasanchezcmarguinbcmarguinbcbrightcove-userbrightcove-userkmasonkmasoncbarstowcbarstowhikehhikehmyerramallamyerramallapdiaspdiasjwhisenantjwhisenantebertaudebertauddsalnikovdsalnikovsharanya.muruganandamsharanya.muruganandamxgarcia_npmxgarcia_npmjguerrajguerrarjunerjunejonbwalshjonbwalshkhaiphamkhaiphamwswanbeckwswanbeckgastafurovgastafurovadalwaniadalwaniekelson-bcoveekelson-bcovesysengsysengmcarreiromcarreirohwoodburyhwoodburyjblakerjblakerbcmauleonbcmauleonpaco_oblea_bcpaco_oblea_bcjsepulvedajsepulvedabiswaranjanbiswaranjanbarroyobarroyobmartinezbmartinezbc-jcarlsonbc-jcarlsoneledezmaeledezmajcuetojcuetoerodrigueserodriguespsousapsousamarcogaraymarcogarayjavibrightjavibrightbcpsalasbcpsalasetobinetobinackbabeackbabecvillasenorcvillasenoromartinezomartinezmgonzalez_bcmgonzalez_bcpdohertybcovpdohertybcovmuthukumar.bcmuthukumar.bcbzizmondbzizmondjmpmacedojmpmacedoscorreiascorreialescorciolescorciocavieiracavieiraarunjeyaprasadarunjeyaprasadbvilvanathanbvilvanathananand.gangadharananand.gangadharanrociosantosrociosantosagarciabcovagarciabcovattinderattinderlauralopezlauralopezskumar85skumar85hrodriguez2hrodriguez2jasilvaantoniojasilvaantoniopalvarezbcpalvarezbcericramosericramoscarlosabajocarlosabajoingrid.s.cruzingrid.s.cruzluis_fernando_lopez_ruizluis_fernando_lopez_ruizvishal64vishal64tresa.bajitresa.bajiluis.garcia.brightcoveluis.garcia.brightcoverodrigofdzrodrigofdzpgutierrezgilpgutierrezgilharish17harish17jjeyaprakashjjeyaprakashrrajendran1698rrajendran1698jlomelijlomelisjimenezsjimenezrwenger_brightcoverwenger_brightcoverujordanrujordanstuartmhstuartmhjherrerabcovjherrerabcovmshiwalmshiwalptamizhptamizhakamalakkannanakamalakkannanroman-bcroman-bctnwannatnwannabsahlas.npmbsahlas.npmdherrera1109dherrera1109hswaminathanhswaminathanechengbcechengbcsbarrettbcsbarrettbc

Keywords

Readme

Hono Sessions

package-info NPM NodeJS

A session manager for Hono that uses DynamoDB as session storage by default. Supports session retrieval by cookie or access token.

Install

npm install @brightcove/hono-sessions --save

Usage

A middleware is provided that allows configuration of the session options and adds the object sessions to the Hono context.

import { Hono } from 'hono';
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { sessions, DynamoDBAdapter } from '@brightcove/hono-sessions';

const client = new DynamoDBClient({
    endpoint: 'http://localhost:4566',
    region: 'us-east-1'
});
const document = DynamoDBDocument.from(client);

const app = new Hono();

app.use(sessions({
    adapter: new DynamoDBAdapter({
        tableName: 'my-table',
        primaryKey: 'pk',
        sortKey: 'sk',
        expiresAttr: 'expires',
        document
    })
    ...
}));

app.get('/my_route', async (c, next) => {
    const session = c.get('session');
});

Session Storage

DynamoDBAdapter is provided by default for use with DynamoDB as the storage backend, but alternate backends can be used if they conform to Adapter

export interface Adapter {
    get: (key: Record<string, string>) => Promise<{ session: any, cookie?: any, token?: any } | undefined>;
    set: (key: Record<string, string>, data: any, cookie?: any, token?: string, expires?: number) => Promise<void>;
    delete: (key: Record<string, string>) => Promise<void>;
    defaultKeyFn: () => (sessionId: string) => Record<string, string>;
}

Session Retrieval

Cookie

When configured to use cookies the library automatically manages setting/unsetting any any options configured

app.use(sessions({
    adapter: new DynamoDBAdapter({
        tableName: 'my-table',
        primaryKey: 'pk',
        sortKey: 'sk',
        expiresAttr: 'expires',
        document
    }),
    cookie: {
        name: 'session_storage',
        maxAge: 60000,
        secure: true
    }
}));

Access Token

When configured to use tokens, the library looks for a token in the header Authorization: Bearer <token> or in the query parameter token.

Note: If both are included, the query parameter takes precedence

app.use(sessions({
    adapter: new DynamoDBAdapter({
        tableName: 'my-table',
        primaryKey: 'pk',
        sortKey: 'sk',
        expiresAttr: 'expires',
        document
    }),
    token: {
        maxAge: 60000,
        payload: (session) => ({ user_id: session.user.id })
    }
}));

Options

DynamoDBAdapter Options

| Param | Type | Description | Required | Default | | ------------- | ---------------- | ----------------------------------------------------------------------------------------------------------- | -------- | --------- | | tableName | string | DynamoDB table name | yes | | primaryKey | string | DynamoDB primary key | no | pk | | sortKey | string | DynamoDB sort key | no | sk | | expiresAttr | string | DynamoDB TTL attribute name. This will be used for setting session expiration and auto expiration behavior | no | expires | | document | DynamoDBDocument | https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/DynamoDBDocument | yes |

Middleware Options

| Param | Type | Description | Required | Default | | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | --------- | | adapter | Adapter | A valid Adapter instance | yes | | cookie | object | Accepts all the Hono cookie options | yes | | cookie.name | string | The session cookie name | no | sid.bgs | | secret | string | The secret used for signing cookies | yes, if cookie.secure or token, otherwise no | | logger | Logger | What will be used for logging errors (ie. logger.error()). console is used by default if not specified | no | console | | token.maxAge | number | The token expiration in seconds from the time it's generated | yes, if using token | | token.queryParam | Function | Specifies the query param that is checked for the token | no | token | | token.payload | Function | By default tokens only contain the sid and exp in the payload, but this allows additional data to be included with a function with the signature (session) => object. | no | | allowOverwrite | boolean | Determines whether a new session can be started when the current one hasn't been ended | no | true |

Starting a session

This creates the session item in the database, initialized with a serialized version of any data passed into the function (must be serializable or this will fail) and sets the session cookie on the response.

import { startSession } from '@brightcove/hono-sessions';

app.get('/my_route', async (c, next) => {
    await startSession(c, {
        user_id: 1234,
        name: 'user'
    });
    ...
});

Updating a session

The context exposes both the session and sessionCookie, which can freely be edited.

app.get('/my_route', async (c, next) => {
    const session = c.get('session');
    const cookie = c.get('sessionCookie');

    session.newField = 'new value';
    ...
});

If any of the updated cookie options are invalid, this will fail.

When the request is finalizing, if either has been updated the changes will automatically be synced back to storage.

If any of the cookie options were updated an updated cookie will be set in the response.

Ending a session

This deletes the session from the database and the session cookie in the response if there was one.

import { endSession } from '@brightcove/hono-sessions';

app.get('/my_route', async (c, next) => {
    await endSession(c);
    ...
});

If the library is configured to use token retrieval, the token can also be passed in for cases where it isn't found in the normal locations

app.get('/my_route', async (c, next) => {
    await endSession(c, token);
    ...
});

Getting the access token

If the library is configured to use token retrieval, and there's a valid session, the access token can be found in the context

app.get('/my_route', async (c, next) => {
    const token = c.get('sessionToken');
    ...
});