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();
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With