WebSocket on Server Component

Lets say I want to have a websocket listening for messages from a different API on the server, could I do something like this? Or would I have add the websocket connection to a client component and put all of this in a useEffect?
import WebSocket from "ws";
import Link from "next/link";
import { revalidatePath } from "next/cache";

const sensors = async () => {
const sensorArray: Array<any> = [];
const ws = new WebSocket(...);

ws.on("sensor-data", (data) => {
sensors.push(...data);
revalidatePath("/");
});

return (
<Link href="/devices/sensors" >
{sensorArray.length}
</Link>
);
}

export { sensors };
import WebSocket from "ws";
import Link from "next/link";
import { revalidatePath } from "next/cache";

const sensors = async () => {
const sensorArray: Array<any> = [];
const ws = new WebSocket(...);

ws.on("sensor-data", (data) => {
sensors.push(...data);
revalidatePath("/");
});

return (
<Link href="/devices/sensors" >
{sensorArray.length}
</Link>
);
}

export { sensors };
Solution:
Everything is effectively a lambda function, none of your Api is long living so your websockets will die very quickly
Jump to solution
12 Replies
alexmartos
alexmartos•13mo ago
Yes, WebSockets are for clients only, you could use like pub/sub on server but the client has to listen to the server somehow
NinjaBunny
NinjaBunny•13mo ago
ahhh okay thanks I had a feeling I would have to use a client component, but it would be cool to do something like this on the server
Josh
Josh•13mo ago
Websockets are not ideal for next at all
Solution
Josh
Josh•13mo ago
Everything is effectively a lambda function, none of your Api is long living so your websockets will die very quickly
NinjaBunny
NinjaBunny•13mo ago
yea I know, but I'm forced into using websockets because I need a constant data feed for certain parts of my teams application. dealing with realtime events and stuff
Josh
Josh•13mo ago
Then next/Vercel is the wrong stack Or, if you still want to use next, you'll need to move your websocket onto a microservice that is long living / not next
NinjaBunny
NinjaBunny•13mo ago
even if it's on a client component?
Josh
Josh•13mo ago
No, client is fine
NinjaBunny
NinjaBunny•13mo ago
or something marked as "use client"
Josh
Josh•13mo ago
Client can do whatever you need I'm talking about websockets on the server If you don't have any server websockets your fine
NinjaBunny
NinjaBunny•13mo ago
nope the websocket server is from a different microservice, I just thought it would be cool if we can revalidate the path like that, but it makes sense Thank you for the help 🙂 I appreciate it
Josh
Josh•13mo ago
Yessir
Want results from more Discord servers?
Add your server