1.0.8 • Published 11 months ago

@brightcove/hono-sessions v1.0.8

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

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

ParamTypeDescriptionRequiredDefault
tableNamestringDynamoDB table nameyes
primaryKeystringDynamoDB primary keynopk
sortKeystringDynamoDB sort keynosk
expiresAttrstringDynamoDB TTL attribute name. This will be used for setting session expiration and auto expiration behaviornoexpires
documentDynamoDBDocumenthttps://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/DynamoDBDocumentyes

Middleware Options

ParamTypeDescriptionRequiredDefault
adapterAdapterA valid Adapter instanceyes
cookieobjectAccepts all the Hono cookie optionsyes
cookie.namestringThe session cookie namenosid.bgs
secretstringThe secret used for signing cookiesyes, if cookie.secure or token, otherwise no
loggerLoggerWhat will be used for logging errors (ie. logger.error()). console is used by default if not specifiednoconsole
token.maxAgenumberThe token expiration in seconds from the time it's generatedyes, if using token
token.queryParamFunctionSpecifies the query param that is checked for the tokennotoken
token.payloadFunctionBy 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
allowOverwritebooleanDetermines whether a new session can be started when the current one hasn't been endednotrue

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');
    ...
});
1.0.8

11 months ago

1.0.7

11 months ago

1.0.6

11 months ago

1.0.5

11 months ago

1.0.4

12 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago