Next.js Discord

Discord Forum

Using Socket.io with Next js

Unanswered
Tonkinese posted this in #help-forum
Open in Discord
TonkineseOP
Hey Guys,

I am using the App Router and want now Websockets in my Project.

Why?
I want to send Data between another running Js Project that is sharded and this Server.

For example for a Status page where i show, which shards are currently offline / stopped.

So how can i achieve that?

Do i need a Route?

23 Replies

TonkineseOP
import { Server } from "socket.io";

const SocketHandler = (req, res) => {
  if (res.socket.server.io) {
    console.log("Socket is already running");
  } else {
    console.log("Socket is initializing");
    const io = new Server(res.socket.server);
    res.socket.server.io = io;

    io.on("connection", (socket) => {
      console.log(socket);
    });
  }
  res.end();
};

export { SocketHandler as GET, SocketHandler as POST };
@ncls. So that doesnt work 😦
@Tonkinese <@602953499407286331> So that doesnt work 😦
How does it not work?
TonkineseOP
404
Could you show me your folder structure and your client-side connection code?
TonkineseOP
import { Server } from "socket.io";

const SocketHandler = (req, res) => {
  if (res.socket.server.io) {
    console.log("Socket is already running");
  } else {
    console.log("Socket is initializing");
    const io = new Server(res.socket.server);
    res.socket.server.io = io;

    io.on("connection", (socket) => {
      console.log(socket);
    });
  }
  res.end();
};

export { SocketHandler as GET, SocketHandler as POST };
// ROUTE.js
const {io} = require('socket.io-client');
const socket = io('http://localhost:3000/api/socket');

socket.on('connect', () => {
  console.log('Connected to the server');
  socket.emit('hello', 'world');
});

socket.on('disconnect', () => {
  console.log('Disconnected from the server');
});

// CLIENTSIDE TEST CONNECTOR
Yeah. I think App router requires a NextResponse but I don't know how to do that correctly for socket.io.
Does it work in /pages?
TonkineseOP
Created it
doesnt work
TonkineseOP
😦
And i really would like to send data between the app and the program
i mean yeah only for the status page posting every 30 seconds would work
but websockets would offer so much more
If no one else has a solution on how to run socket.io on Next.js, I would suggest creating a seperate Express-Server for running socket.io
TonkineseOP
@not-milo.tsx You helped me very good with internationalization
Did you ever do something like this?