MikroORM refuses to use the global EntityManager
ValidationError: Using global EntityManager instance methods for context specific actions is disallowedShort answer
MikroORM no longer allows the global identity map. Every unit of work needs its own EntityManager context. In a web app, register RequestContext.create as middleware before your handlers. For jobs, use fork() or the CreateRequestContext decorator. Only tests should disable the check.
Fix it fast
1Find out which cause you have
Find where the failing call runs. A route handler, a queue worker and a script each need a different fix below.
grep -rn "orm.em\|RequestContext" src2Match what you see, then jump to its fix
- 1
The error appears in route handlers that use the global orm.emNo request context around the HTTP handlersFix - 2
The error comes from code that no web request startsWork outside HTTP: a queue handler, a cron job or a scriptFix - 3
Only the test suite failsUnit tests that use the global manager on purposeFix
- 1
What does the error look like?
ValidationError: Using global EntityManager instance methods for context specific actions is disallowed
Cause 1 of 3
No request context around the HTTP handlers
1Check
The docs say using the global EntityManager without a request context is almost always wrong. They require a middleware that forks it per request.
grep -rn "RequestContext.create" src2Fix
Register the middleware after body and query parsers and just before the handlers that use the ORM.
app.use(express.json());
app.use((req, res, next) => {
RequestContext.create(orm.em, next);
});
app.get('/', async (req, res) => {
res.json(await orm.em.find(Book, {}));
});3Verify
Request the route again; the query should run.
curl -i http://localhost:3000/Confirmed by mikro-orm.io
Cause 2 of 3
Work outside HTTP: a queue handler, a cron job or a script
1Check
RequestContext only helps inside the request. Background code needs its own context.
grep -rn "@CreateRequestContext\|fork(" src2Fix
Decorate the top-level method with CreateRequestContext, or take a clean manager with fork().
export class MyService {
constructor(private readonly orm: MikroORM) {}
@CreateRequestContext()
async doSomething() {
// runs in its own context
}
}
const em = orm.em.fork();3Verify
Run the job once and check that it finishes without a validation error.
node dist/jobs/run-once.jsConfirmed by mikro-orm.io
Cause 3 of 3
Unit tests that use the global manager on purpose
1Check
The docs mention that the check can be switched off, and that this is handy in unit tests.
grep -rn "allowGlobalContext" src test2Fix
Set allowGlobalContext in the test configuration, or use the MIKRO_ORM_ALLOW_GLOBAL_CONTEXT environment variable. Keep it off in production.
MikroORM.init({
// ...
allowGlobalContext: true,
});3Verify
Run the tests.
npm testConfirmed by mikro-orm.io
How do I stop it coming back?
- Put the RequestContext middleware next to the ORM setup so nobody adds a route above it.
- Do not call a decorated method from another decorated method.
- Keep allowGlobalContext out of the production config.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
Related fixes
Back end
TypeScript says req.user does not exist on the Express Request type
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'
The Request type from Express has no user field until you declare one.
2 causes, each with a fixBack end
TypeScript cannot find req.cookies in a NestJS controller
error TS2339: Property 'cookies' does not exist on type
TypeScript says 'cookies' is missing because the Request type in your file is not Express's, or because cookie support is not installed.
3 causes, each with a fixBack end
TS1259: module can only be default-imported with esModuleInterop
error TS1259: Module '"./node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag
TS1259 means you wrote a default import for a CommonJS module that TypeScript does not treat as having one.
3 causes, each with a fixBack end
A namespace-style import cannot be called or constructed (import * as express)
A namespace-style import cannot be called or constructed, and will cause a failure at runtime
A namespace import (import * as x) is by spec an object, never a function.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
TypeScript cannot find '@angular/platform-browser' in an Angular project
Cannot find module '@angular/platform-browser' or its corresponding type declarations.
TS2307 means TypeScript could not turn the import into a file.
3 causes, each with a fix