next-ws 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md DELETED
@@ -1,246 +0,0 @@
1
- <div align='center'>
2
- <h1><strong>Next WS</strong></h1>
3
- <i>Add support for WebSockets in Next.js app directory</i><br>
4
- <code>npm install next-ws ws</code>
5
- </div>
6
-
7
- <div align='center'>
8
- <img alt='package version' src='https://img.shields.io/npm/v/next-ws?label=version'>
9
- <img alt='total downloads' src='https://img.shields.io/npm/dt/next-ws'>
10
- <br>
11
- <a href='https://github.com/apteryxxyz/next-ws'><img alt='next-ws repo stars' src='https://img.shields.io/github/stars/apteryxxyz/next-ws?style=social'></a>
12
- <a href='https://github.com/apteryxxyz'><img alt='apteryxxyz followers' src='https://img.shields.io/github/followers/apteryxxyz?style=social'></a>
13
- <a href='https://discord.gg/B2rEQ9g2vf'><img src='https://discordapp.com/api/guilds/829836158007115806/widget.png?style=shield' alt='discord shield'/></a>
14
- </div>
15
-
16
- ## 🤔 About
17
-
18
- Next WS (`next-ws`) is an advanced Next.js plugin that seamlessly integrates WebSocket server capabilities directly into routes located in the **app directory**. With Next WS, you no longer require a separate server for WebSocket functionality.
19
-
20
- > [!IMPORTANT]
21
- > Next WS is designed for use in server-based environments. It is not suitable for serverless platforms like Vercel, where WebSocket servers are not supported. Furthermore, this plugin is built for the app directory and does not support the older pages directory.
22
-
23
- This module is inspired by the now outdated `next-plugin-websocket`, if you are using an older version of Next.js, that module may work for you.
24
-
25
- ## 🏓 Table of Contents
26
-
27
- - [📦 Installation](#-installation)
28
- - [🚀 Usage](#-usage)
29
- - [🌀 Examples](#-examples)
30
- - [Creating a Socket](#creating-a-socket)
31
- - [Using a Custom Server](#using-a-custom-server)
32
- - [Accessing the WebSocket Server](#accessing-the-websocket-server)
33
- - [Client-Side Utilities](#client-side-utilities)
34
-
35
- ## 📦 Installation
36
-
37
- Setting up a WebSocket server with Next WS involves patching your local Next.js installation. Next WS simplifies this process with a CLI command that automatically detects and patches your Next.js version, ensuring compatibility. Note that Next.js version 13.1.1 or higher is required.
38
-
39
- ```sh
40
- npx next-ws-cli@latest patch
41
- ```
42
-
43
- > [!NOTE]
44
- > If at any point your local Next.js installation is changed or updated you will need to re-run the patch command.
45
-
46
- After successfully patching Next.js, install the Next WS package along with its peer dependency, ws, into your project:
47
-
48
- ```sh
49
- npm install next-ws ws
50
- ```
51
-
52
- ## 🚀 Usage
53
-
54
- Using WebSocket functionality in your Next.js application with Next WS is simple and requires no additional configuration. Simply export a `SOCKET` function from any route file. This function will be invoked whenever a client establishes a WebSocket connection to that specific route.
55
-
56
- The `SOCKET` function receives three arguments: the WebSocket client instance, the incoming HTTP request - which you can use to get the URL path, query parameters, and headers - and the WebSocket server instance.
57
-
58
- ```ts
59
- export function SOCKET(
60
- client: import('ws').WebSocket,
61
- request: import('http').IncomingMessage,
62
- server: import('ws').WebSocketServer
63
- ) {
64
- // ...
65
- }
66
- ```
67
-
68
- ### With a Custom Server
69
-
70
- In production, Next.js uses a worker process for routes, which can make it difficult to access the WebSocket server from outside a `SOCKET` handler, especially when the WebSocket server exists on the main process. For those needing to overcome this challenge or preferring a custom server setup, Next WS provides a solution.
71
-
72
- The `next-ws/server` module offers functions for setting the HTTP and WebSocket servers. You use these functions to tell Next WS to use your server instances instead of creating its own. This allows you to then access the instances you created yourself from anywhere in your app. Refer to the [example below](#using-a-custom-server).
73
-
74
- ## 🌀 Examples
75
-
76
- For more detailed examples, refer the [`examples` directory](https://github.com/apteryxxyz/next-ws/tree/main/examples).
77
-
78
- ### Creating a Socket
79
-
80
- Creating an API route anywhere within the app directory and exporting a `SOCKET` function from it is all that is required. Below is an example of a simple echo server, which sends back any message it receives.
81
-
82
- ```ts
83
- // app/api/ws/route.ts (can be any route file in the app directory)
84
-
85
- export function SOCKET(
86
- client: import('ws').WebSocket,
87
- request: import('http').IncomingMessage,
88
- server: import('ws').WebSocketServer
89
- ) {
90
- console.log('A client connected');
91
-
92
- client.on('message', (message) => {
93
- console.log('Received message:', message);
94
- client.send(message);
95
- });
96
-
97
- client.on('close', () => {
98
- console.log('A client disconnected');
99
- });
100
- }
101
- ```
102
-
103
- ### Using a Custom Server
104
-
105
- > [!IMPORTANT]
106
- > Next WS was made to avoid the need for a custom server, if you are using one, you don't need this package and can just use a websocket server directly.
107
-
108
- To use a custom server, all you need to do is tell Next WS to use your server instead of creating its own. This can be done by calling the `setHttpServer` and `setWebSocketServer` functions from `next-ws/server` and passing your server instances.
109
-
110
- ```ts
111
- // server.js
112
-
113
- const { setHttpServer, setWebSocketServer } = require('next-ws/server');
114
- const { Server } = require('node:http');
115
- const { parse } = require('node:url');
116
- const next = require('next');
117
- const { WebSocketServer } = require('ws');
118
-
119
- const dev = process.env.NODE_ENV !== 'production';
120
- const hostname = 'localhost';
121
- const port = 3000;
122
-
123
- const httpServer = new Server();
124
- const webSocketServer = new WebSocketServer({ noServer: true });
125
- // Tell Next WS about the HTTP and WebSocket servers before starting the custom server
126
- setHttpServer(httpServer);
127
- setWebSocketServer(webSocketServer);
128
-
129
- const app = next({ dev, hostname, port, customServer: true });
130
- const handle = app.getRequestHandler();
131
-
132
- app.prepare().then(() => {
133
- httpServer
134
- .on('request', async (req, res) => {
135
- const parsedUrl = parse(req.url, true);
136
- await handle(req, res, parsedUrl);
137
- })
138
- .listen(port, () => {
139
- console.log(` ▲ Ready on http://${hostname}:${port}`);
140
- });
141
- });
142
- ```
143
-
144
- ### Accessing the WebSocket Server
145
-
146
- Along with setters, Next WS also provides getters for the HTTP and WebSocket servers. These functions can be used to access the servers from anywhere in your app.
147
-
148
- > [!IMPORTANT]
149
- > In order to use the `getWebSocketServer` and `getHttpServer` functions, you must be using a [custom server](https://nextjs.org/docs/advanced-features/custom-server), this is due to a limitation in Next.js. Refer to the [With a Custom Server](#with-a-custom-server).
150
-
151
- ```ts
152
- // app/api/stats/route.ts
153
-
154
- import { getWebSocketServer } from 'next-ws/server';
155
- // There is also a `getHttpServer` function available
156
-
157
- export function GET() {
158
- const wsServer = getWebSocketServer();
159
- // Response with the number of connected clients
160
- return Response.json({ count: wsServer.clients.size });
161
- }
162
- ```
163
-
164
- ### Client-Side Utilities
165
-
166
- To make it easier to connect to your new WebSocket server, Next WS also provides some client-side utilities. These are completely optional, you can use your own implementation if you wish.
167
-
168
- ```tsx
169
- // layout.tsx
170
- 'use client';
171
-
172
- import { WebSocketProvider } from 'next-ws/client';
173
-
174
- export default function Layout({ children }: React.PropsWithChildren) {
175
- return (
176
- <html>
177
- <body>
178
- <WebSocketProvider url='ws://localhost:3000/api/ws'>
179
- {children}
180
- </WebSocketProvider>
181
- </body>
182
- </html>
183
- );
184
- }
185
- ```
186
-
187
- The following is the props interface for the `WebSocketProvider` component, containing all the available options.
188
-
189
- ```ts
190
- interface WebSocketProviderProps {
191
- children: React.ReactNode;
192
-
193
- /** The URL for the WebSocket to connect to. */
194
- url: string;
195
- /** The subprotocols to use. */
196
- protocols?: string[] | string;
197
- /** The binary type to use. */
198
- binaryType?: BinaryType;
199
- }
200
- ```
201
-
202
- Now you can use the `useWebSocket` hook to get the WebSocket instance, and send and receive messages.
203
-
204
- ```tsx
205
- // page.tsx
206
- 'use client';
207
-
208
- import { useCallback, useEffect, useRef, useState } from 'react';
209
- import { useWebSocket } from 'next-ws/client';
210
-
211
- export default function Page() {
212
- const ws = useWebSocket();
213
- // ^? WebSocket on the client, null on the server
214
-
215
- const inputRef = useRef<HTMLInputElement>(null);
216
- const [message, setMessage] = useState<string | null>(null);
217
-
218
- useEffect(() => {
219
- async function onMessage(event: MessageEvent) {
220
- const payload =
221
- typeof event.data === 'string' ? event.data : await event.data.text();
222
- const message = JSON.parse(payload) as Message;
223
- setMessages((p) => [...p, message]);
224
- }
225
-
226
- ws?.addEventListener('message', onMessage);
227
- return () => ws?.removeEventListener('message', onMessage);
228
- }, [ws]);
229
-
230
- return (
231
- <>
232
- <input ref={inputRef} type='text' />
233
-
234
- <button onClick={() => ws?.send(inputRef.current?.value ?? '')}>
235
- Send message to server
236
- </button>
237
-
238
- <p>
239
- {message === null
240
- ? 'Waiting to receive message...'
241
- : `Got message: ${message}`}
242
- </p>
243
- </>
244
- );
245
- }
246
- ```