sam3d / next-plugin-websocket

Add WebSocket support to Next.js API routes
https://www.npmjs.com/package/next-plugin-websocket
58 stars 8 forks source link

Full example #3

Open Maragouin opened 1 year ago

Maragouin commented 1 year ago

Hello please could you provide to me a complete example ( client / api) ? thanks in advance Joseph

yoieh commented 1 year ago

After created a fis for #4 with my PR #6 i got this working.

Using nextjs v13.3.0 with appDir: true but it needs to be added to the old pages structure which is still supported.

Example from readme:

// pages/api/ws.ts

import { NextApiHandler } from "next";
import { NextWebSocketHandler } from "next-plugin-websocket";

export const socket: NextWebSocketHandler = (client, req) => {
  console.log("Client connected");

  client.on("message", (msg) => {
    client.send(msg);
  });

  client.on("close", () => {
    console.log("Client disconnected");
  });
};

// You still need to expose a regular HTTP handler, even if you only intend to
// use this API route for WebSocket connections.
const handler: NextApiHandler = (req, res) => {
  res.status(426).send("Upgrade Required");
};

export default handler;

Very simple client component:

// components/WebSocketClient.tsx
"use client";

import { useEffect, useState } from "react";

export const WebSocketClient = () => {
  const ws = useWebSocketClient();

  return null;
};

export const useWebSocketClient = () => {
  const [ws, setWs] = useState<WebSocket | null>(null);

  useEffect(() => {
    const onMessage = (message: string) => {
      console.log("Received WebSocket message:", message);
      // Update your UI or state based on the received message
    };

    const client = new WebSocket("ws://localhost:3000/api/ws");

    client.onopen = () => {
      console.log("WebSocket client connected");
    };

    client.onmessage = (event) => {
      onMessage(event.data);
    };

    client.onclose = () => {
      console.log("WebSocket client disconnected");
    };

    setWs(client);

    return () => {
      client.close();
    };
  }, []);

  return ws;
};