Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing socket.io on NextJS 13 with App directory

How can initialize socket with App directory in app/api/socket/route.js ?

It doesnt return instance of http.ServerResponse like example below in pages/api/socket.js directory. It returns NextResponse which doesnt have socket property to create an io instance with.

import { Server } from "socket.io";

export default function 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("client connected", socket.id);
    });
  }
  res.end();
}
like image 641
Anıl Aksu Avatar asked May 03 '26 06:05

Anıl Aksu


2 Answers

It appears that after "13.2.5-canary.26", a trailing slash is appended to the end of the route.

Disabling "addTrailingSlash" in the Socket.IO Server constructor resolves this issue.

"pages/api/socket.js"

const io = new Server(res.socket.server, {
  path: '/api/socket_io',
  addTrailingSlash: false,
});

in page.jsx :

const socket = io(undefined, {
  path: '/api/socket_io',
});

More info can be found here: https://github.com/vercel/next.js/issues/49334#issuecomment-1539867051

like image 178
Tomer Almog Avatar answered May 05 '26 18:05

Tomer Almog


If you were having issues previously, Next.JS version 13.5 now fixes the issue that socket.io wasn't working since version 13.2.5-canary.27 but it is working now on 13.5.2

like image 24
aetheros Avatar answered May 05 '26 18:05

aetheros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!