CodexBloom - Programming Q&A Platform

Next.js Custom Server with WebSocket scenarios to Reconnect After Page Refresh

👀 Views: 27 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
next.js websocket react express JavaScript

I'm wondering if anyone has experience with I'm working on a personal project and I'm currently implementing a custom server in Next.js that uses WebSocket for real-time communication... The server is set up correctly, but I've encountered a question where the WebSocket connection fails to reconnect after a page refresh. When I reload the page, I see the following behavior in the console: `WebSocket connection to 'ws://localhost:3000/socket' failed: behavior during WebSocket handshake: Unexpected response code: 404`. I've confirmed that the WebSocket server is running and accessible at `ws://localhost:3000/socket`. Here's the relevant code snippet for the WebSocket connection in my React component: ```javascript useEffect(() => { const socket = new WebSocket('ws://localhost:3000/socket'); socket.onopen = () => { console.log('WebSocket connection established'); }; socket.onmessage = (event) => { console.log('Message from server: ', event.data); }; socket.onclose = (event) => { console.log('WebSocket connection closed', event); }; return () => { socket.close(); }; }, []); ``` I've also verified that my custom server is handling WebSocket connections properly. It looks something like this: ```javascript const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const next = require('next'); const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); const httpServer = http.createServer(server); const wss = new WebSocket.Server({ server: httpServer }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (message) => { console.log('Received: %s', message); }); }); server.all('*', (req, res) => { return handle(req, res); }); httpServer.listen(3000, (err) => { if (err) throw err; console.log('> Ready on http://localhost:3000'); }); }); ``` I suspect that the scenario might be related to how Next.js handles routing and that it might not be properly directing WebSocket requests after a refresh. I've tried moving the WebSocket server setup outside of the Next.js handler, but the question continues. Has anyone faced this scenario or have suggestions on how to resolve the WebSocket reconnection question after a page refresh? What's the best practice here? This issue appeared after updating to Javascript 3.10. What's the correct way to implement this?