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/ab9af352c6fb58279f752ce85099d756 to your computer and use it in GitHub Desktop.
Save rcoedo/ab9af352c6fb58279f752ce85099d756 to your computer and use it in GitHub Desktop.
const { AsyncLocalStorage } = require("async_hooks");
const asyncLocalStorage = new AsyncLocalStorage();
const requestIdMiddleware = (req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set("requestId", uuid());
next();
});
};
const express = require("express");
const { AsyncLocalStorage } = require("async_hooks");
const uuid = require("uuid/v4");
const asyncLocalStorage = new AsyncLocalStorage();
const requestIdMiddleware = (req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set("requestId", uuid());
next();
});
};
const app = express();
app.use(requestIdMiddleware);
app.get("/", (req, res) => {
const id = asyncLocalStorage.getStore().get("requestId");
console.log(`[${id}] 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 "AsyncLocalStorage for Easy Context Passing in Node.js".
- https://medium.com/trabe/asynclocalstorage-for-easy-context-passing-in-node-js-e33c84679516
- https://rcoedo.com/blog/2020/05/25/async-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