luis pedro
luis pedro

Reputation: 1

A PusherServer is created in every endpoint call to my Next.js API

I have a Next.js web application, I have an api to controll where I trigger events using Pusher.js, but when I call those endpoints, a new PusherServer instance is created the firs time I call this endpoints, so a new connection is created for each of that instances,therefore, if the web app uses 4 endpoints then each user will generate 4 connections when it just should creat one connection. I actually using the single pattern but it seems to be not working. This is my PusherServer creation file:

import PusherServer from 'pusher';

const pusherServerConfig = {
  appId: process.env.PUSHER_APP_ID!,
  key: process.env.NEXT_PUBLIC_PUSHER_KEY!,
  secret: process.env.PUSHER_SECRET!,
  cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER!,
  useTLS: true,
};

let pusherServer: PusherServer | null = null;

export const getPusherServerInstance = () => {
  if (!pusherServer) {
    pusherServer = new PusherServer(pusherServerConfig);
  }
  return pusherServer;
};

And when I want to use the pusherServer I just import it and used like this:

import { getPusherServerInstance } from '@/pusher/pusherServer';
...
  await getPusherServerInstance().trigger(...);

Does someone know what the problem is?

I tried to create this instance in many ways, but I have not found the way to don't create multiple instances by endpoint

Upvotes: 0

Views: 74

Answers (0)

Related Questions