📖
Internal Wiki
  • My Knowledge Wiki 🌿
  • ai
    • Prompts
  • beautiful
    • Beautiful websites
  • blog
    • best blog times
    • Good Blog Posts
  • career
    • First 90 Days
    • income streams
    • interview questions
    • Misc
    • Negotiation
    • On Call
  • coding
    • AWS
    • Bash
    • Browser Extensions
    • Cloudflare
    • CopyQ
    • Docker
    • Express
    • Filebase
    • Firebase
    • Git Commit Message Standards
    • GIT
    • Github Actions
    • html
    • TypeScript / JavaScript
    • JavaScript / TypeScript
    • NodeJS
    • npm
    • npx
    • Service Workers
    • Tunnel
    • Vite
    • Wrangler
    • New Angular Project
    • snippets
      • angular
        • Performance Tracking
        • Web3 in Angular Projects
      • nodejs
        • Dynamically load classes
  • communities
    • Communities
  • devex
    • Browser Experience
  • github
    • CI/CD
  • infra
    • Kubernetes
    • Windows
  • links
    • AI
    • Awesome lists
    • Beautify Code
    • cli
    • Code Snippet Images
    • Coding
    • Courses
    • Creators
    • Crypto
    • CSS
    • Design
    • Diagrams
    • Domains
    • events
    • Fonts
    • Funding
    • gifs
    • Github
    • I18N
    • Icons
    • Identity
    • Image (drawing, manipulation, ...)
    • All around infra (hosting, serverless, ...)
    • JSON utils
    • Libraries and Tools
    • Markdown
    • Machine Learning
    • Monetization
    • Music
    • No Code Tools
    • Node and NPM (and other package managers)
    • nostr
    • Other
    • Pitch
    • react
    • Resources
    • Resumes
    • SaaS
    • scraping
    • Screenshots
    • Search
    • SEO
    • Services
    • Social Media Engagement
    • Popular Stacks
    • Storage
    • Terms
    • Text to speech
    • Text Effects
    • Tutorials
    • video
    • Nice wasm libs
    • Writing
    • YouTube
  • linux-commands
    • convert
    • ffmpeg
    • General
    • Screen
  • Quotes
    • Twitter Quotes
  • reddit
    • Side projects
  • shops
    • Dog Stuff
    • wir-machen-druck
  • watch
    • Youtube Videos
  • wine
    • Wine
  • learning
    • house
      • Heating Energy Act
    • sbf
      • SBF Navi
      • SBF Praxis
      • SBF
Powered by GitBook
On this page
  • Session handling
  • Express middleware
  • Access session context
  • Set entry
  • Usage
  1. coding

Express

Session handling

Implement a session context for requests and use the data in all async execution.

Express middleware

import { AsyncLocalStorage } from "async_hooks";
import crypto from "crypto";

export const asyncLocalStorage = new AsyncLocalStorage();

export enum SessionMapKey {
  SESSION_ID = "sessionId",
  USER_ID = "userId",
}

export function SessionMiddleware(_req, _res, next) {
  const sessionMap = new Map();
  sessionMap.set(SessionMapKey.SESSION_ID, crypto.randomUUID());
  asyncLocalStorage.run(sessionMap, () => {
    next();
  });
}

Access session context

export function getByKey(key: SessionMapKey): string {
  const sessionMap: Map<string, string> = asyncLocalStorage.getStore() as Map<
    string,
    string
  >;
  let value = "unset";
  if (sessionMap) {
    value = sessionMap.get(key) || "unset";
  }
  return value;
}

Set entry

export function setByKey(key: SessionMapKey, value: string) {
  const sessionMap: Map<string, string> = asyncLocalStorage.getStore() as Map<
    string,
    string
  >;
  if (sessionMap) {
    sessionMap.set(key, value);
  }
}

Usage

Add middleware to server (or a route)

const app = express();
app.use(SessionMiddleware);

Use in a log message

// use a proper logging framework ;)
const sessionId = getByKey(SessionMapKey.SESSION_ID);
console.log(`${sessionId} | get request to flethy.com`);
PreviousDockerNextFilebase

Last updated 2 years ago