cookie-session-store v1.0.2
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 increateCookieSessionStore
than it decrypts the cookie with the secret than it returns a session objectcommitSession(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 sessiondestroySession()
it returns a set cookie header that destroys the session cookiesession.get(key: string)
returns the value by the key if key is not in the session it returns undefinedsession.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 itsession.has(key: string)
checks if a given key is in the session returns true or falsesession.unset(key: string)
deletes the key value pair from the sessionsession.data()
returns the raw session object