I have a NextJS Project that uses instrumentations.ts to create a websocket server. I am trying to access the connected clients from a server action however, any exported variables are defaulted to null even after they have been modified in a function.
WebSocketServer Code:
export let wss: WebSocketServer;
export function createWS() {
if(Boolean(wss)) return wss;
wss = new WebSocketServer({ port: 7777 });
wss.on('listening', () => {
console.log('listening on port 7777');
});
wss.on('message', (message) => {
console.log('message received');
console.log(message);
});
wss.on('connection', connectedToWSS);
return wss;
}
Server Action Code:
'use server';
import { wss } from "@/utils/websocket";
export async function testWebSocket() {
console.log(wss?.clients.size);
}
Instrumentation Code:
import { createWS } from './utils/websocket';
export async function register() {
createWS();
}
I expect that the wss imported from the websocket file would exist after calling createWS from instrumentation, however wss only exists within the websocket file and I cannot import it without it being undefined
.