Created
April 18, 2023 07:31
-
-
Save huksley/e9047f0c606c263d85abed7358933950 to your computer and use it in GitHub Desktop.
NextJS websocket API route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Server } from "http"; | |
import { Socket } from "net"; | |
import { NextApiRequest, NextApiResponse } from "next"; | |
import { Server as SocketServer } from "socket.io"; | |
interface NextSocket extends Socket { | |
server?: Server & { io?: SocketServer }; | |
} | |
/** | |
* Only API routes with NodeJS runtime support socket.io, | |
* also deploying to Vercel does will not work. | |
* | |
* @link https://vercel.com/guides/do-vercel-serverless-functions-support-websocket-connections | |
* @link https://nextjs.org/docs/api-reference/edge-runtime | |
*/ | |
const SocketHandler = (req: NextApiRequest, res: NextApiResponse) => { | |
if (!res.socket) { | |
throw new Error("No socket found: " + req.url); | |
} | |
const socket = res.socket as NextSocket; | |
if (!socket.server) { | |
throw new Error("No NextJS server found: " + req.url); | |
} | |
if (!req.url) { | |
throw new Error("No URL specified for route: " + req.url); | |
} | |
if (!socket.server.io) { | |
console.info("Starting socket.io server", req.url); | |
const io = new SocketServer(socket.server, { path: req.url }); | |
socket.server.io = io; | |
io.on("connection", (socket) => { | |
const interval = setInterval(() => { | |
socket.emit("message", "Hello World!" + Date.now()); | |
}, 1000); | |
socket.on("disconnect", () => { | |
clearInterval(interval); | |
}); | |
}); | |
} | |
res.end(); | |
}; | |
export default SocketHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately, using Socket IO only possible when you deploy app to your own infrastructure such as VM, docker, etc.