1.0.2 • Published 3 years ago

cookie-session-store v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

cookie-session-store

This package is created to manage cookie sessions. (It is a Remix like createCookieSessionStorage api) The package can handle any request type, because it uses the request's cookie header as a parameter.

To install run:

npm install cookie-session-store

Example:

import { createCookieSessionStore } from "cookie-session-store";

// this should be in a separate file
// perhaps session.js/ts
const { getSession, destroySession, commitSession} = createCookieSessionStore({ 
	name: "__session", 
	secret: "this is a secret",
	cookieOptions: {...}
})

app.get((req, res) => {
	const session = getSession(req.headers.cookie);
	const userId = session.get("userId");

	if (userId) {
		session.set("userId", 5)
		// you need to set this if you modify the session
		// modification is when you call set/unset
		res.set("Set-Cookie", commitSession(session));
	} else {
		res.set("Set-Cookie", destroySession())
	}
})

API

  • getSession(httpCookieHeader: string) it reads the cookie header and gets the cookie by the name that you specified in createCookieSessionStore than it decrypts the cookie with the secret than it returns a session object

  • commitSession(session: Session) it gets a session object as a parameter, than it encrypts that session object and returns a proper set cookie header this way we persist changes made to the session

  • destroySession() it returns a set cookie header that destroys the session cookie

  • session.get(key: string) returns the value by the key if key is not in the session it returns undefined

  • session.set(key: string, value: string | number | boolean | null) if the key is in the session than it's value will be overridden with the value parameter if the key is not in the session than the key value pare will be added to it

  • session.has(key: string) checks if a given key is in the session returns true or false

  • session.unset(key: string) deletes the key value pair from the session

  • session.data() returns the raw session object