Skip to content

Instantly share code, notes, and snippets.

@sachin-hg
Created November 24, 2022 09:02
Show Gist options
  • Save sachin-hg/a35b34d71d9fbe46c239d38b9fa1aba7 to your computer and use it in GitHub Desktop.
Save sachin-hg/a35b34d71d9fbe46c239d38b9fa1aba7 to your computer and use it in GitHub Desktop.
Request Context creation example for module federation request context cache
// utils/requestContext.js
import { createNamespace } from 'cls-hooked'
// context variable here may be global, but the data stored is
// not shared among different requests
const context = createNamespace(`app:requestData`)
// use this middleware in your express middleware chain, as early as possible
export function expressMiddleware (req, res, next) {
context.run(function () {
context.set('requestContext', {})
next()
})
}
export const getFromRequestContext = () => {
return context.get('requestContext')
}
export const addToRequestContext = (slave, container) => {
const ctx = context.get('requestContext')
ctx[slave] = container
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment