📢 Looking for Feedback on WebSocket Implementation with Next.js & Bun
Unanswered
Florida White posted this in #help-forum
Florida WhiteOP
Hey Next.js devs 👋,
I'm building a real-time chat system using WebSockets, and I’d love to get your thoughts on my implementation. My main concerns are performance and scalability as the project grows.
Here’s how I structured the setup:
websocket-server.js (Using Bun)
This file sets up a WebSocket server with Bun:
socket-server.js (Using Socket.IO)
This alternative uses Socket.IO instead of WebSockets:
src/websocket.js (Client WebSocket Connection)
I'm building a real-time chat system using WebSockets, and I’d love to get your thoughts on my implementation. My main concerns are performance and scalability as the project grows.
Here’s how I structured the setup:
websocket-server.js (Using Bun)
This file sets up a WebSocket server with Bun:
Bun.serve({
port: 3001,
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/ws") {
const username = url.searchParams.get("username") || "Anonymous";
const upgraded = server.upgrade(req, { data: { username } });
return upgraded ? undefined : new Response("Upgrade failed", { status: 400 });
}
return new Response("Not Found", { status: 404 });
},
websocket: {
open(ws) {
ws.subscribe("chat");
ws.publish("chat", `${ws.data.username} joined the chat`);
},
message(ws, message) {
ws.publish("chat", `${ws.data.username}: ${message}`);
},
close(ws) {
ws.unsubscribe("chat");
ws.publish("chat", `${ws.data.username} left the chat`);
},
},
});
socket-server.js (Using Socket.IO)
This alternative uses Socket.IO instead of WebSockets:
import { createServer } from "bun";
import { Server } from "socket.io";
const port = 4000;
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
socket.on("message", (data) => {
io.emit("message", data);
});
socket.on("disconnect", () => {});
});
httpServer.listen(port);
src/websocket.js (Client WebSocket Connection)
export const ws = new WebSocket("ws://localhost:3001/ws?username=NextUser");
ws.addEventListener("open", () => {});
ws.addEventListener("message", (event) => {});
ws.addEventListener("close", () => {});
ws.addEventListener("error", () => {});
14 Replies
Florida WhiteOP
"use client";
import { useEffect, useState } from "react";
import { ws } from "../../websocket";
export default function Chat() {
const [message, setMessage] = useState("");
const [chatLog, setChatLog] = useState<string[]>([]);
useEffect(() => {
const handleMessage = (event) => {
setChatLog((prev) => [...prev, event.data]);
};
ws.addEventListener("message", handleMessage);
return () => {
ws.removeEventListener("message", handleMessage);
};
}, []);
const sendMessage = () => {
if (message.trim() === "") return;
ws.send(message);
setMessage("");
};
return (
<div style={{ padding: "1rem" }}>
<h1>Real-time Chat</h1>
<div style={{ border: "1px solid #ccc", padding: "1rem", height: "300px", overflowY: "auto" }}>
{chatLog.map((msg, index) => (
<p key={index}>{msg}</p>
))}
</div>
<input type="text" value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Type a message..." />
<button onClick={sendMessage}>Send</button>
</div>
);
}
🔍 Questions for Feedback:
Scalability – Will this setup hold up well with many concurrent users?
Performance – Any optimizations you’d suggest for better efficiency?
Scalability – Will this setup hold up well with many concurrent users?
Performance – Any optimizations you’d suggest for better efficiency?
PS : Its working fine, this is a global questions
@Florida White PS : Its working fine, this is a global questions
Brown bear
Why don't you run some tests?
Florida WhiteOP
With what ?
Like a stress test ?
Brown bear
I'm a pythonist myself, so any starlette/httpx/aiohttp or even requests would be good
Florida WhiteOP
And to be honest im on client project, i dont have this time...
Brown bear
Basically anything what could send websocket requests
@Florida White And to be honest im on client project, i dont have this time...
Brown bear
It's simple: try to duplicate or do slight changes every time, and repeat this like 1k times
@Brown bear It's simple: try to duplicate or do slight changes every time, and repeat this like 1k times
Florida WhiteOP
Ok i will give it a try
thanks
But if anyone have something to say, I will be glad to hear it
@Florida White But if anyone have something to say, I will be glad to hear it
Brown bear
Well done, this is simple