I don't know why everyone overcomplicates the code examples for client sockets with Next.js or mixes up the idea that you need to run a socket server inside of Next.js when you don't. Even the socket.io documentation for Next.js is really bad, their documentation just tells you to stop using the Next.js web server with all of its great features and use a different HTTP server (very bad idea). People are looking for how to stream incoming socket data into Next.js components which they should have documentation for.
Here's a super simple client example for Next.js, it assumes you have a socket server running somewhere else which is recommended. It also assumes you have CORS configured correclty on your socket server to allow incoming connections from the Next.js server that is interacting with it. Once you set up the API, you can call that programmatically and feed data to your components however you like.
This is for the Page Router and not the App router. ChatGPT can probably give you good suggestions on how to refactor it for the AppRouter.
// src/pages/api/socketStatus.js
import { io } from "socket.io-client";
export const config = {
api: {
externalResolver: true,
},
};
export default function socketHandler() {
// my socket server is running on port 5174 with CORS configured there allowing requests from my Next.js origin of http://localhost:3000
let clientSocket = io('http://localhost:5174');
clientSocket.on("connect", () => {
console.log(clientSocket.id) // log the socket ID to the console.
return console.log("Connected")
})
// log all incoming socket data to a variable of 'data' from the socket topic of 'importantSocketTopic`, change this to the string name that you emit data with.
clientSocket.on("importantSocketTopic", data => {
console.log(data);
} )
}
Calling the socket API route from your Next.js index.tsx file as an example:
// src/pages/index.tsx
import { useEffect, useState } from 'react'
export default function Home() {
const [mounted, setMounted] = useState(false)
useEffect(() => {
initialize();
setMounted(true);
}, []);
async function initialize() {
// initialize any functions or services for the web dashboard
let socket_check = await fetch('/api/socketStatus');
console.log(socket_check);
}
if (!mounted) {
return <>Ehhh we are waiting for something to render</>
}
return (
<div>
<div>Your fancy nextjs app</div>
</div>
</div>
)
}