Next.js Discord

Discord Forum

Best way to implement singleton in nextjs shared between custom http server

Unanswered
Cornish Rex posted this in #help-forum
Open in Discord
Avatar
Cornish RexOP
Hey guys, im trying to implemenet a singleton class problem is that the custom server and nextjs server side will have different results so its not really singleton shared between these 2 but if i use globalthis it will share it as i like but im not sure if its secure or good is there any better method to do this ?
as i will be storing processes and cannot store it in DB
class ServerManager {
    servers: Map<string, Server> = new Map();

    addServer(id: string, name: string) {
        if (this.servers.has(id)) {
            console.log(`Server ${id} already exists.`);
            return;
        }
        const server = new Server(id, name);
        this.servers.set(id, server);
        console.log(`Server ${id} added.`);
    }

    getServers() {
        return this.servers;
    }
}


declare global {
    var serverManager: ServerManager | undefined;
}

const serverManager = globalThis.serverManager ?? new ServerManager();

if (process.env.NODE_ENV !== 'production') {
    globalThis.serverManager = serverManager;
}

export default serverManager;

0 Replies