next-ws 1.0.1 → 1.1.0-next.2
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/dist/chunk-6VWOYYWX.mjs +11 -0
- package/dist/chunk-6VWOYYWX.mjs.map +1 -0
- package/dist/chunk-PFW3KWBF.cjs +14 -0
- package/dist/chunk-PFW3KWBF.cjs.map +1 -0
- package/dist/client/index.cjs +38 -0
- package/dist/client/index.cjs.map +1 -0
- package/dist/client/index.d.cts +25 -0
- package/dist/client/index.d.ts +25 -0
- package/dist/client/index.mjs +29 -0
- package/dist/client/index.mjs.map +1 -0
- package/dist/server/index.cjs +162 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +38 -0
- package/dist/server/index.d.ts +38 -0
- package/dist/server/index.mjs +134 -0
- package/dist/server/index.mjs.map +1 -0
- package/package.json +27 -36
- package/readme.md +241 -0
- package/README.md +0 -198
- package/client/context.d.ts +0 -24
- package/client/context.js +0 -43
- package/client/index.d.ts +0 -1
- package/client/index.js +0 -4
- package/index.d.ts +0 -1
- package/index.js +0 -3
- package/server/index.d.ts +0 -3
- package/server/index.js +0 -5
- package/server/setup.d.ts +0 -3
- package/server/setup.js +0 -42
- package/server/utilities/next.d.ts +0 -31
- package/server/utilities/next.js +0 -106
- package/server/utilities/patch.d.ts +0 -13
- package/server/utilities/patch.js +0 -37
- package/server/utilities/server.d.ts +0 -33
- package/server/utilities/server.js +0 -50
- package/server/utilities/workspace.d.ts +0 -1
- package/server/utilities/workspace.js +0 -44
- package/server/utilities/ws.d.ts +0 -15
- package/server/utilities/ws.js +0 -13
package/package.json
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-ws",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.1.0-next.2",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"description": "Add support for WebSockets in Next.js 13 app directory",
|
|
5
|
-
"keywords": [
|
|
6
|
-
"next",
|
|
7
|
-
"websocket",
|
|
8
|
-
"ws",
|
|
9
|
-
"server",
|
|
10
|
-
"client"
|
|
11
|
-
],
|
|
12
6
|
"license": "MIT",
|
|
7
|
+
"keywords": ["next", "websocket", "ws", "server", "client"],
|
|
13
8
|
"homepage": "https://github.com/apteryxxyz/next-ws#readme",
|
|
14
9
|
"repository": {
|
|
15
10
|
"type": "git",
|
|
@@ -19,19 +14,25 @@
|
|
|
19
14
|
"bugs": {
|
|
20
15
|
"url": "https://github.com/apteryxxyz/next-ws/issues"
|
|
21
16
|
},
|
|
22
|
-
"files": [
|
|
23
|
-
|
|
24
|
-
"
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
17
|
+
"files": ["dist"],
|
|
18
|
+
"exports": {
|
|
19
|
+
"./client": {
|
|
20
|
+
"import": "./dist/client/index.mjs",
|
|
21
|
+
"require": "./dist/client/index.cjs",
|
|
22
|
+
"types": "./dist/client/index.d.ts"
|
|
23
|
+
},
|
|
24
|
+
"./server": {
|
|
25
|
+
"import": "./dist/server/index.mjs",
|
|
26
|
+
"require": "./dist/server/index.cjs",
|
|
27
|
+
"types": "./dist/server/index.d.ts"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
30
|
"scripts": {
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
31
|
+
"lint": "biome lint . --write",
|
|
32
|
+
"format": "biome format . --write",
|
|
33
|
+
"check": "tsc --noEmit",
|
|
34
|
+
"build": "cp ../../readme.md . && tsup",
|
|
35
|
+
"dev": "pnpm build --watch"
|
|
35
36
|
},
|
|
36
37
|
"peerDependencies": {
|
|
37
38
|
"next": ">=13.1.1",
|
|
@@ -39,21 +40,11 @@
|
|
|
39
40
|
"ws": "*"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
|
-
"@
|
|
43
|
-
"@types/react
|
|
44
|
-
"@types/ws": "^8",
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"react": "^18.2.0",
|
|
49
|
-
"react-dom": "^18.2.0",
|
|
50
|
-
"rimraf": "^5.0.1",
|
|
51
|
-
"typescript": "<5.1.0"
|
|
52
|
-
},
|
|
53
|
-
"eslintConfig": {
|
|
54
|
-
"root": true,
|
|
55
|
-
"extends": [
|
|
56
|
-
"../../.eslintrc.js"
|
|
57
|
-
]
|
|
43
|
+
"@configs/tsup": "workspace:^",
|
|
44
|
+
"@types/react": "^18.3.3",
|
|
45
|
+
"@types/ws": "^8.5.10",
|
|
46
|
+
"next": "^14.2.4",
|
|
47
|
+
"react": "^18.3.1",
|
|
48
|
+
"ws": "^8.17.1"
|
|
58
49
|
}
|
|
59
50
|
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
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/vZQbMhwsKY"><img src="https://discordapp.com/api/guilds/829836158007115806/widget.png?style=shield" alt="discord shield"/></a>
|
|
14
|
+
</div>
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## 🤔 About
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
|
|
22
|
+
> [!IMPORTANT]
|
|
23
|
+
> 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.
|
|
24
|
+
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## 🏓 Table of Contents
|
|
29
|
+
|
|
30
|
+
## 📦 Installation
|
|
31
|
+
|
|
32
|
+
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.
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
npx next-ws-cli@latest patch
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
> [!NOTE]
|
|
39
|
+
> If at any point your local Next.js installation is changed or updated you will need to re-run the patch command.
|
|
40
|
+
|
|
41
|
+
After successfully patching Next.js, install the Next WS package along with its peer dependency, ws, into your project:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npm install next-ws ws
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 🚀 Usage
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
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.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
export function SOCKET(
|
|
55
|
+
client: import('ws').WebSocket,
|
|
56
|
+
request: import('http').IncomingMessage,
|
|
57
|
+
server: import('ws').WebSocketServer,
|
|
58
|
+
) {
|
|
59
|
+
// ...
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### With a Custom Server
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
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).
|
|
68
|
+
|
|
69
|
+
## 🌀 Examples
|
|
70
|
+
|
|
71
|
+
For more detailed examples, refer the [`examples` directory](https://github.com/apteryxxyz/next-ws/tree/main/examples).
|
|
72
|
+
|
|
73
|
+
### Creating a Socket
|
|
74
|
+
|
|
75
|
+
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.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
// app/api/ws/route.ts (can be any route file in the app directory)
|
|
79
|
+
|
|
80
|
+
export function SOCKET(
|
|
81
|
+
client: import('ws').WebSocket,
|
|
82
|
+
request: import('http').IncomingMessage,
|
|
83
|
+
server: import('ws').WebSocketServer,
|
|
84
|
+
) {
|
|
85
|
+
console.log('A client connected');
|
|
86
|
+
|
|
87
|
+
client.on('message', (message) => {
|
|
88
|
+
console.log('Received message:', message);
|
|
89
|
+
client.send(message);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
client.on('close', () => {
|
|
93
|
+
console.log('A client disconnected');
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Using a Custom Server
|
|
99
|
+
|
|
100
|
+
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.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// server.js
|
|
104
|
+
|
|
105
|
+
const { setHttpServer, setWebSocketServer } = require('next-ws/server');
|
|
106
|
+
const { Server } = require('node:http');
|
|
107
|
+
const { parse } = require('node:url');
|
|
108
|
+
const next = require('next');
|
|
109
|
+
const { WebSocketServer } = require('ws');
|
|
110
|
+
|
|
111
|
+
const dev = process.env.NODE_ENV !== 'production';
|
|
112
|
+
const hostname = 'localhost';
|
|
113
|
+
const port = 3000;
|
|
114
|
+
|
|
115
|
+
const httpServer = new Server();
|
|
116
|
+
const webSocketServer = new WebSocketServer({ noServer: true });
|
|
117
|
+
// Tell Next WS about the HTTP and WebSocket servers before starting the custom server
|
|
118
|
+
setHttpServer(httpServer);
|
|
119
|
+
setWebSocketServer(webSocketServer);
|
|
120
|
+
|
|
121
|
+
const app = next({ dev, hostname, port, customServer: httpServer });
|
|
122
|
+
const handle = app.getRequestHandler();
|
|
123
|
+
|
|
124
|
+
app.prepare().then(() => {
|
|
125
|
+
httpServer
|
|
126
|
+
.on('request', async (req, res) => {
|
|
127
|
+
const parsedUrl = parse(req.url, true);
|
|
128
|
+
await handle(req, res, parsedUrl);
|
|
129
|
+
})
|
|
130
|
+
.listen(port, () => {
|
|
131
|
+
console.log(` ▲ Ready on http://${hostname}:${port}`);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Accessing the WebSocket Server
|
|
137
|
+
|
|
138
|
+
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.
|
|
139
|
+
|
|
140
|
+
> [!IMPORTANT]
|
|
141
|
+
> 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).
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// app/api/stats/route.ts
|
|
145
|
+
|
|
146
|
+
import { getWebSocketServer } from 'next-ws/server';
|
|
147
|
+
// There is also a `getHttpServer` function available
|
|
148
|
+
|
|
149
|
+
export function GET() {
|
|
150
|
+
const wsServer = getWebSocketServer();
|
|
151
|
+
// Response with the number of connected clients
|
|
152
|
+
return Response.json({ count: wsServer.clients.size });
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Client-Side Utilities
|
|
157
|
+
|
|
158
|
+
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.
|
|
159
|
+
|
|
160
|
+
```tsx
|
|
161
|
+
// layout.tsx
|
|
162
|
+
'use client';
|
|
163
|
+
|
|
164
|
+
import { WebSocketProvider } from 'next-ws/client';
|
|
165
|
+
|
|
166
|
+
export default function Layout({ children }: React.PropsWithChildren) {
|
|
167
|
+
return <html>
|
|
168
|
+
<body>
|
|
169
|
+
<WebSocketProvider
|
|
170
|
+
url="ws://localhost:3000/api/ws"
|
|
171
|
+
>
|
|
172
|
+
{children}
|
|
173
|
+
</WebSocketProvider>
|
|
174
|
+
</body>
|
|
175
|
+
</html>;
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The following is the props interface for the `WebSocketProvider` component, containing all the available options.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
interface WebSocketProviderProps {
|
|
183
|
+
children: React.ReactNode;
|
|
184
|
+
|
|
185
|
+
/** The URL for the WebSocket to connect to. */
|
|
186
|
+
url: string;
|
|
187
|
+
/** The subprotocols to use. */
|
|
188
|
+
protocols?: string[] | string;
|
|
189
|
+
/** The binary type to use. */
|
|
190
|
+
binaryType?: BinaryType;
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Now you can use the `useWebSocket` hook to get the WebSocket instance, and send and receive messages.
|
|
195
|
+
|
|
196
|
+
```tsx
|
|
197
|
+
// page.tsx
|
|
198
|
+
'use client';
|
|
199
|
+
|
|
200
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
201
|
+
import { useWebSocket } from 'next-ws/client';
|
|
202
|
+
|
|
203
|
+
export default function Page() {
|
|
204
|
+
const ws = useWebSocket();
|
|
205
|
+
// ^? WebSocket on the client, null on the server
|
|
206
|
+
|
|
207
|
+
const inputRef = useRef<HTMLInputElement>(null);
|
|
208
|
+
const [message, setMessage] = useState<string | null>(null);
|
|
209
|
+
|
|
210
|
+
useEffect(() => {
|
|
211
|
+
async function onMessage(event: MessageEvent) {
|
|
212
|
+
const payload =
|
|
213
|
+
typeof event.data === 'string' ? event.data : await event.data.text();
|
|
214
|
+
const message = JSON.parse(payload) as Message;
|
|
215
|
+
setMessages((p) => [...p, message]);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
ws?.addEventListener('message', onMessage);
|
|
219
|
+
return () => ws?.removeEventListener('message', onMessage);
|
|
220
|
+
}, [ws]);
|
|
221
|
+
|
|
222
|
+
return <>
|
|
223
|
+
<input
|
|
224
|
+
ref={inputRef}
|
|
225
|
+
type="text"
|
|
226
|
+
/>
|
|
227
|
+
|
|
228
|
+
<button
|
|
229
|
+
onClick={() => ws?.send(inputRef.current?.value ?? '')}
|
|
230
|
+
>
|
|
231
|
+
Send message to server
|
|
232
|
+
</button>
|
|
233
|
+
|
|
234
|
+
<p>
|
|
235
|
+
{message === null
|
|
236
|
+
? 'Waiting to receive message...'
|
|
237
|
+
: `Got message: ${message}`}
|
|
238
|
+
</p>
|
|
239
|
+
</>;
|
|
240
|
+
}
|
|
241
|
+
```
|
package/README.md
DELETED
|
@@ -1,198 +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/vZQbMhwsKY"><img src="https://discordapp.com/api/guilds/829836158007115806/widget.png?style=shield" alt="discord shield"/></a>
|
|
14
|
-
</div>
|
|
15
|
-
|
|
16
|
-
---
|
|
17
|
-
|
|
18
|
-
## 🤔 About
|
|
19
|
-
|
|
20
|
-
Next WS (`next-ws`) is an advanced Next.js plugin designed to seamlessly integrate WebSocket server functionality into API routes within the **app directory**. With Next WS, you no longer require a separate server for WebSocket functionality.
|
|
21
|
-
|
|
22
|
-
It's **important** to note that this module can only be used when working with a server. Unfortunately, in serverless environments like Vercel, WebSocket servers cannot be used. Additionally, this module was built for the app directory and is incompatible with the older pages directory.
|
|
23
|
-
|
|
24
|
-
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.
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
## 🏓 Table of Contents
|
|
29
|
-
|
|
30
|
-
- [🤔 About](#-about)
|
|
31
|
-
- [🏓 Table of Contents](#-table-of-contents)
|
|
32
|
-
- [📦 Installation](#-installation)
|
|
33
|
-
- [🚀 Usage](#-usage)
|
|
34
|
-
- [🚓 Verify Patch](#-verify-patch)
|
|
35
|
-
- [🌀 Example](#-example)
|
|
36
|
-
- [📁 Server](#-server)
|
|
37
|
-
- [📁 Client](#-client)
|
|
38
|
-
|
|
39
|
-
---
|
|
40
|
-
|
|
41
|
-
## 📦 Installation
|
|
42
|
-
|
|
43
|
-
In order to setup a WebSocket server, Next WS needs to patch your local Next.js installation. Next WS provides a CLI command to do this for you, it will automatically detect your Next.js version and patch it accordingly, however a minimum version of Next.js 13.1.1 is required.
|
|
44
|
-
|
|
45
|
-
```sh
|
|
46
|
-
npx next-ws-cli@latest patch
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
> If at any point your local Next.js installation is changed or updated you will need to re-run the patch command.
|
|
50
|
-
|
|
51
|
-
Once the patch is complete, you will need to install the Next WS package into your project.
|
|
52
|
-
|
|
53
|
-
```sh
|
|
54
|
-
npm install next-ws ws
|
|
55
|
-
# ws is a peer dependency, you must install it as well
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
### 🚓 Verify Patch (Optional)
|
|
59
|
-
|
|
60
|
-
It is recommended to add the following code to the top level of your `next.config.js`.
|
|
61
|
-
|
|
62
|
-
This will verify that Next WS has been patched correctly, and throw an error if it has not. Preventing you from accidentally deploying a broken setup.
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
require('next-ws/server').verifyPatch();
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
---
|
|
69
|
-
|
|
70
|
-
## 🚀 Usage
|
|
71
|
-
|
|
72
|
-
Using Next WS is a breeze, requiring zero configuration. Simply export a `SOCKET` function from any API route. This function gets called whenever a client connects to the WebSocket server at the respective API path.
|
|
73
|
-
|
|
74
|
-
The `SOCKET` function receives three arguments: the WebSocket client, the HTTP request - which you can use to get the URL path, query parameters, and headers - and the WebSocket server that `next-ws` created.
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
export function SOCKET(
|
|
78
|
-
client: import('ws').WebSocket,
|
|
79
|
-
request: import('http').IncomingMessage,
|
|
80
|
-
server: import('ws').WebSocketServer,
|
|
81
|
-
) {
|
|
82
|
-
// ...
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
With this straightforward setup, you can fully leverage the capabilities of Next WS and efficiently handle WebSocket connections within your Next.js application.
|
|
87
|
-
|
|
88
|
-
---
|
|
89
|
-
|
|
90
|
-
## 🌀 Example
|
|
91
|
-
|
|
92
|
-
### 📁 Server
|
|
93
|
-
|
|
94
|
-
Create an API route anywhere within the app directory, and export a `SOCKET` function from it, below is an example of a simple echo server, which sends back any message it receives.
|
|
95
|
-
|
|
96
|
-
```ts
|
|
97
|
-
// app/api/ws/route.ts (can be any route file in the app directory)
|
|
98
|
-
export function SOCKET(
|
|
99
|
-
client: import('ws').WebSocket,
|
|
100
|
-
request: import('http').IncomingMessage,
|
|
101
|
-
server: import('ws').WebSocketServer,
|
|
102
|
-
) {
|
|
103
|
-
console.log('A client connected!');
|
|
104
|
-
|
|
105
|
-
client.on('message', message => {
|
|
106
|
-
client.send(message);
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
client.on('close', () => {
|
|
110
|
-
console.log('A client disconnected!');
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
You are pretty much done at this point, you can now connect to the WebSocket server using the native WebSocket API in the browser.
|
|
116
|
-
|
|
117
|
-
### 📁 Client
|
|
118
|
-
|
|
119
|
-
To make it easier to connect to your new WebSocker server, Next WS also provides some client-side utilities. These are completely optional, you can use your own implementation if you wish.
|
|
120
|
-
|
|
121
|
-
```tsx
|
|
122
|
-
// layout.tsx
|
|
123
|
-
'use client';
|
|
124
|
-
|
|
125
|
-
import { WebSocketProvider } from 'next-ws/client';
|
|
126
|
-
|
|
127
|
-
export default function Layout() {
|
|
128
|
-
return <WebSocketProvider
|
|
129
|
-
url="ws://localhost:3000/api/ws"
|
|
130
|
-
// ... other props
|
|
131
|
-
>
|
|
132
|
-
{...}
|
|
133
|
-
</WebSocketProvider>;
|
|
134
|
-
}
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
The following is the props interface for the `WebSocketProvider` component, containing all the available options.
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
interface WebSocketProviderProps {
|
|
141
|
-
children: React.ReactNode;
|
|
142
|
-
|
|
143
|
-
/** The URL for the WebSocket to connect to. */
|
|
144
|
-
url: string;
|
|
145
|
-
/** The subprotocols to use. */
|
|
146
|
-
protocols?: string[] | string;
|
|
147
|
-
/** The binary type to use. */
|
|
148
|
-
binaryType?: BinaryType;
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
Now you can use the `useWebSocket` hook to get the WebSocket instance, and send and receive messages.
|
|
153
|
-
|
|
154
|
-
```tsx
|
|
155
|
-
// page.tsx
|
|
156
|
-
'use client';
|
|
157
|
-
|
|
158
|
-
import { useWebSocket } from 'next-ws/client';
|
|
159
|
-
import { useCallback, useEffect, useState } from 'react';
|
|
160
|
-
|
|
161
|
-
export default function Page() {
|
|
162
|
-
const ws = useWebSocket();
|
|
163
|
-
// ^? WebSocket on the client, null on the server
|
|
164
|
-
|
|
165
|
-
const [value, setValue] = useState('');
|
|
166
|
-
const [message, setMessage] = useState<string | null>(null);
|
|
167
|
-
|
|
168
|
-
const onMessage = useCallback(
|
|
169
|
-
(event: MessageEvent<Blob>) =>
|
|
170
|
-
void event.data.text().then(setMessage),
|
|
171
|
-
[],
|
|
172
|
-
);
|
|
173
|
-
|
|
174
|
-
useEffect(() => {
|
|
175
|
-
ws?.addEventListener('message', onMessage);
|
|
176
|
-
return () => ws?.removeEventListener('message', onMessage);
|
|
177
|
-
}, [onMessage, ws]);
|
|
178
|
-
|
|
179
|
-
return <>
|
|
180
|
-
<input
|
|
181
|
-
type="text"
|
|
182
|
-
value={value}
|
|
183
|
-
onChange={event => setValue(event.target.value)}
|
|
184
|
-
/>
|
|
185
|
-
|
|
186
|
-
<button onClick={() => ws?.send(value)}>
|
|
187
|
-
Send message to server
|
|
188
|
-
</button>
|
|
189
|
-
|
|
190
|
-
<p>
|
|
191
|
-
{message === null
|
|
192
|
-
? 'Waiting to receive message...'
|
|
193
|
-
: `Got message: ${message}`}
|
|
194
|
-
</p>
|
|
195
|
-
</>;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
```
|
package/client/context.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/// <reference types="react" />
|
|
2
|
-
export declare const WebSocketContext: import("react").Context<WebSocket | null>;
|
|
3
|
-
export interface WebSocketProviderProps {
|
|
4
|
-
children: React.ReactNode;
|
|
5
|
-
/** The URL for the WebSocket to connect to. */
|
|
6
|
-
url: string;
|
|
7
|
-
/** The subprotocols to use. */
|
|
8
|
-
protocols?: string[] | string;
|
|
9
|
-
/** The binary type to use. */
|
|
10
|
-
binaryType?: BinaryType;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Provides a WebSocket instance to its children via context,
|
|
14
|
-
* allowing for easy access to the WebSocket from anywhere in the app.
|
|
15
|
-
* @param props WebSocket parameters and children.
|
|
16
|
-
* @returns JSX Element
|
|
17
|
-
*/
|
|
18
|
-
export declare function WebSocketProvider({ children, url, protocols, binaryType, }: WebSocketProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
19
|
-
export declare const WebSocketConsumer: import("react").Consumer<WebSocket | null>;
|
|
20
|
-
/**
|
|
21
|
-
* Access the websocket from anywhere in the app, so long as it's wrapped in a WebSocketProvider.
|
|
22
|
-
* @returns WebSocket instance when connected, null when disconnected.
|
|
23
|
-
*/
|
|
24
|
-
export declare function useWebSocket(): WebSocket | null;
|
package/client/context.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.useWebSocket = exports.WebSocketConsumer = exports.WebSocketProvider = exports.WebSocketContext = void 0;
|
|
4
|
-
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
5
|
-
const react_1 = require("react");
|
|
6
|
-
exports.WebSocketContext = (0, react_1.createContext)(null);
|
|
7
|
-
exports.WebSocketContext.displayName = 'WebSocketContext';
|
|
8
|
-
/**
|
|
9
|
-
* Provides a WebSocket instance to its children via context,
|
|
10
|
-
* allowing for easy access to the WebSocket from anywhere in the app.
|
|
11
|
-
* @param props WebSocket parameters and children.
|
|
12
|
-
* @returns JSX Element
|
|
13
|
-
*/
|
|
14
|
-
function WebSocketProvider({ children, url, protocols, binaryType, }) {
|
|
15
|
-
const isBrowser = typeof window !== 'undefined';
|
|
16
|
-
const instance = (0, react_1.useMemo)(() => {
|
|
17
|
-
if (!isBrowser)
|
|
18
|
-
return null;
|
|
19
|
-
const client = new WebSocket(url, protocols);
|
|
20
|
-
if (binaryType)
|
|
21
|
-
client.binaryType = binaryType;
|
|
22
|
-
return client;
|
|
23
|
-
}, [isBrowser, url, protocols]);
|
|
24
|
-
(0, react_1.useEffect)(() => {
|
|
25
|
-
if (instance?.readyState !== WebSocket.OPEN)
|
|
26
|
-
return;
|
|
27
|
-
return () => instance.close();
|
|
28
|
-
}, []);
|
|
29
|
-
return ((0, jsx_runtime_1.jsx)(exports.WebSocketContext.Provider, { value: instance, children: children }));
|
|
30
|
-
}
|
|
31
|
-
exports.WebSocketProvider = WebSocketProvider;
|
|
32
|
-
exports.WebSocketConsumer = exports.WebSocketContext.Consumer;
|
|
33
|
-
/**
|
|
34
|
-
* Access the websocket from anywhere in the app, so long as it's wrapped in a WebSocketProvider.
|
|
35
|
-
* @returns WebSocket instance when connected, null when disconnected.
|
|
36
|
-
*/
|
|
37
|
-
function useWebSocket() {
|
|
38
|
-
const context = (0, react_1.useContext)(exports.WebSocketContext);
|
|
39
|
-
if (context === undefined)
|
|
40
|
-
throw new Error('useWebSocket must be used within a WebSocketProvider');
|
|
41
|
-
return context;
|
|
42
|
-
}
|
|
43
|
-
exports.useWebSocket = useWebSocket;
|
package/client/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './context';
|
package/client/index.js
DELETED
package/index.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/index.js
DELETED
package/server/index.d.ts
DELETED
package/server/index.js
DELETED
package/server/setup.d.ts
DELETED
package/server/setup.js
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.hookNextNodeServer = exports.setupWebSocketServer = void 0;
|
|
4
|
-
const tslib_1 = require("tslib");
|
|
5
|
-
const Log = tslib_1.__importStar(require("next/dist/build/output/log"));
|
|
6
|
-
const next_1 = require("./utilities/next");
|
|
7
|
-
const ws_1 = require("./utilities/ws");
|
|
8
|
-
function setupWebSocketServer(nextServer) {
|
|
9
|
-
const httpServer = (0, next_1.getHttpServer)(nextServer);
|
|
10
|
-
const wsServer = (0, ws_1.getWsServer)();
|
|
11
|
-
Log.ready('[next-ws] websocket server started successfully');
|
|
12
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
13
|
-
httpServer.on('upgrade', async (request, socket, head) => {
|
|
14
|
-
const url = new URL(request.url ?? '', 'ws://next');
|
|
15
|
-
const pathname = url.pathname;
|
|
16
|
-
if (pathname.startsWith('/_next'))
|
|
17
|
-
return;
|
|
18
|
-
const fsPathname = (0, next_1.resolvePathname)(nextServer, pathname);
|
|
19
|
-
if (!fsPathname) {
|
|
20
|
-
Log.error(`[next-ws] could not find module for page ${pathname}`);
|
|
21
|
-
return socket.destroy();
|
|
22
|
-
}
|
|
23
|
-
const pageModule = await (0, next_1.getPageModule)(nextServer, fsPathname);
|
|
24
|
-
if (!pageModule) {
|
|
25
|
-
Log.error(`[next-ws] could not find module for page ${pathname}`);
|
|
26
|
-
return socket.destroy();
|
|
27
|
-
}
|
|
28
|
-
const socketHandler = pageModule?.routeModule?.userland?.SOCKET;
|
|
29
|
-
if (!socketHandler || typeof socketHandler !== 'function') {
|
|
30
|
-
Log.error(`[next-ws] ${pathname} does not export a SOCKET handler`);
|
|
31
|
-
return socket.destroy();
|
|
32
|
-
}
|
|
33
|
-
return wsServer.handleUpgrade(request, socket, head, (client, request) => void socketHandler(client, request, wsServer));
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
exports.setupWebSocketServer = setupWebSocketServer;
|
|
37
|
-
// Next WS versions below 0.2.0 used a different method of setup
|
|
38
|
-
// This remains for backwards compatibility, but may be removed in a future version
|
|
39
|
-
function hookNextNodeServer() {
|
|
40
|
-
setupWebSocketServer(this);
|
|
41
|
-
}
|
|
42
|
-
exports.hookNextNodeServer = hookNextNodeServer;
|