Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcoedo/4bf5e6c377b52d5fd1ff1d555c6a369e to your computer and use it in GitHub Desktop.
Save rcoedo/4bf5e6c377b52d5fd1ff1d555c6a369e to your computer and use it in GitHub Desktop.
const { createNamespace } = require("cls-hooked");
const ns = createNamespace("myApp");
const requestIdMiddleware = (req, res, next) => {
ns.run(() => {
ns.set("requestId", uuid());
next();
});
};
const express = require("express");
const { createNamespace } = require("cls-hooked");
const uuid = require("uuid/v4");
const ns = createNamespace("myApp");
const requestIdMiddleware = (req, res, next) => {
ns.run(() => {
ns.set("requestId", uuid());
next();
});
};
const app = express();
app.use(requestIdMiddleware);
app.get("/", (req, res) => {
console.log(`[${ns.get("requestId")}] request received`);
res.send("It works!");
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Express server listening on port ${port}`));
This gist contains the examples for the article "Continuation Local Storage for Easy Context Passing in Node.js".
- https://medium.com/trabe/continuation-local-storage-for-easy-context-passing-in-node-js-2461c2120284
- https://rcoedo.com/blog/2019/11/14/continuation-local-storage-for-easy-context-passing-in-node-js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment