Continuous process while server is running

With NextJs my definition of a server is being challenged. I see a server as a program that can serve requests and do background tasks. With nextjs it seems to only do the former.

I have a web application where users can manage instances of a program on several machines. The machines run a kotlin program that manages the machine processes of the program instances locally. I want this kotlin program to communicate with the T3 server backend to listen for requests such as making a screenshot. I was thinking of doing this with a websocket.

When the user opens the /instances web page, they will see the running instances of the program on the machines. I want the user to be able to click on Screenshot button and then the backend notifies the kotlin programs that a screenshot needs to be made. The kotlin program makes the screenshot and then uploads it to the backend. Then the image can be served to the user.

If I put this in root.ts
const wss: WebSocketServer = new WebSocketServer({ port: 8080 });

wss.on("connection", (ws) => {
  console.log("test");
  ws.on("message", (message: string) => {
    console.log(`Received message => ${message}`);
    ws.send(`Received your message: ${message}`);
  });

  ws.send("Hello! Message from server!!");
});

wss.on("error", console.error);

this code runs each time a web page is visited or something. Instead I want this to be called when the T3 server starts and then keep running. Is that possible? Is that correct usage of NextJs? Should I take a whole different approach?
Solution
ChatGPT
Great answer
Was this page helpful?