Singleton class across multiple requests in route handlers #55263
Replies: 3 comments 2 replies
-
@danieljee I have the same issue, did you resolved it ? |
Beta Was this translation helpful? Give feedback.
-
NodeJS already have a internal cache module resolution, so singleton is easy to implement, for example: @/lib/Api.ts:
This way, event if I import X times |
Beta Was this translation helpful? Give feedback.
-
Here's the approach I'm using: The issue you're seeing is indeed related to how Next.js works, particularly in development mode. // Use a global variable to store the instance
declare global {
var socketManager: SocketManager | undefined
}
const socketManager = global.socketManager || SocketManager.getInstance();
if (process.env.NODE_ENV !== 'production') global.socketManager = socketManager
export default socketManager; |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Environment:
node.js: v18.15.0
nextjs: 13.4.13
Problem
I'm trying to enable Server Sent Event so that I can push messages to the clients.
To do this, I'm using instrumentation to initialize required modules:
instrumentation.ts:
server-sent-event.ts:
As you can see, my intention is that I want to use SSEManager as a singleton to ensure I keep the record of the connections across requests.
In /api/sse route handler I'm importing the SSEManager class:
When send a request using different user accounts to the same route handler
output:
expected:
In every request the SSEManager reinitialized.
Is there way to use a module as a singleton just like in a normal node.js application?
Thank you
Beta Was this translation helpful? Give feedback.
All reactions