Canonical approach to instantiating singletons in NextJS #68572
Replies: 1 comment
-
There's a lot of confusion regarding singletons in Nextjs since a lot has changed from Next 13 to the current version. Since 13+, all Nextjs context now runs in the same process (prior to 13, there were 2-3 jest workers handling different things like pages & app router, middleware, etc...) But now that everything runs in the same process, // singleton.ts
const instance = {
db: new DBConnection()
}
export default instance In To make sure the singleton still works, just wrap all single variables inside // singleton.ts
globalThis.instance = globalThis.instance || { db: new DBConnection() }
export default globalThis.instance You'll want to extend Don't use |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
I'm looking for advice regarding how one would instantiate a server-side singleton.
Where in something like an express.js application, we have a clear entry point for our application, an
index.ts
orserver.ts
and that's where we can instantiate/configure such service singletons - nextjs doesn't appear to have a clear entry point.My scenario
In my specific scenario this singleton essentially behaves as an alternative to context provider, where I do something like this:
Other Scenarios
There are other scenarios that I've run across in the wild:
This discussion mentions instantiating database connections: #16271
Advice in the thread appear to be 'instantiate as and where you need it' , (could be problematic, surely), and otherwise people mentioning instantiating in layout.tsx
This in-progress MSW example PR shows instantiating the MSW behaviour in layout.tsx
https://github.com/mswjs/examples/pull/101/files#diff-8c12b389f7663528d803c57e6fe92f1635c6bbeafcf9d1b3d069d8b31fc88471R5-R12
Solutions
This is the first solution I'd thought of too - it seems like the most obvious 'this is the first thing will render'. My experimenting with a local dev server does indicate that this module will only be evaluated once.
The reason this file seems appropriate is the documentation says:
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions