Replies: 2 comments
-
|
I would recommend this in API routes: // ./app/api/foo.ts
export function socket(socket:Socket) {
socket.on("message", msg => {
socket.emit("response", msg);
});
};
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// normal HTTP request to /api/foo
res.end();
};Enabling Web sockets could be done through Next's configuration. For example: const config = {
// ...
webSocket: {
port: 3100, // optional, defaults to same server port
}
};
export default config;When API endpoints are setup, Next should also create websocket endpoints if the |
Beta Was this translation helpful? Give feedback.
-
|
I've just created a package, next-plugin-websocket, that adds support for WebSocket handlers in Next.js API routes with no extra configuration: import { appRouter } from "@/server/routers/_app";
import { NextApiHandler } from "next";
import { NextWebSocketHandler } from "next-plugin-websocket";
export const socket: NextWebSocketHandler = (client, req) => {
client.on("message", (msg) => {
client.send(msg);
});
};
const handler: NextApiHandler = (req, res) => {
res.status(426).end();
};
export default handler;It's still very much in beta, and I've only managed to test it on Next.js 13 (with and without I've been using it in production without issue for a little while now without any issues 😊 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Describe the feature you'd like to request
I would like a new package that will allow you to easily make websockets in the backend. I want it to easier implement the WebSocket communication between the client and the server.
Describe the solution you'd like
A new package that allows you to easily setup websockets in API Routes.
Describe alternatives you've considered
I am currently using socket IO in an API route like this:
But it is having some issues when connecting from a different process.
Beta Was this translation helpful? Give feedback.
All reactions