### Install next-ws and ws dependencies Source: https://github.com/apteryxxyz/next-ws/blob/main/README.md Commands to install the `next-ws` package and its peer dependency `ws` using various package managers. These dependencies are essential for adding WebSocket support to a Next.js app. ```bash npm install next-ws ws ``` ```bash pnpm add next-ws ws ``` ```bash yarn add next-ws ws ``` -------------------------------- ### Configure package.json for next-ws patching Source: https://github.com/apteryxxyz/next-ws/blob/main/README.md JSON snippet to add a `prepare` script to `package.json`. This script ensures that `next-ws` patches the Next.js installation automatically whenever dependencies are installed. ```json { "scripts": { "prepare": "next-ws patch" } } ``` -------------------------------- ### Implement a WebSocket echo server in Next.js API route Source: https://github.com/apteryxxyz/next-ws/blob/main/README.md A complete TypeScript example demonstrating a simple WebSocket echo server. This code snippet shows how to handle client connections, process incoming messages by echoing them back, and manage client disconnections within a Next.js API route file. ```ts // app/api/ws/route.ts (can be any route file in the app directory) export function SOCKET( client: import("ws").WebSocket, request: import("http").IncomingMessage, server: import("ws").WebSocketServer ) { console.log("A client connected"); client.on("message", (message) => { console.log("Received message:", message); client.send(message); }); client.on("close", () => { console.log("A client disconnected"); }); } ``` -------------------------------- ### Define the SOCKET function for WebSocket handling Source: https://github.com/apteryxxyz/next-ws/blob/main/README.md The basic signature for the `SOCKET` function, which is exported from Next.js API routes. This function serves as the entry point for handling WebSocket connections, receiving the client, request, server, and context objects. ```ts export function SOCKET( client: import('ws').WebSocket, request: import('http').IncomingMessage, server: import('ws').WebSocketServer, context: { params: Record }, ) { // ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.