diff --git a/using-ngrok-with/websockets.mdx b/using-ngrok-with/websockets.mdx index ebc47a7c9f..dfe924906c 100644 --- a/using-ngrok-with/websockets.mdx +++ b/using-ngrok-with/websockets.mdx @@ -6,3 +6,53 @@ description: ngrok HTTP endpoints support WebSockets without any special configu WebSocket endpoints work through ngrok's HTTP endpoints without any changes. However, there is currently no support for introspecting WebSockets beyond the initial `101 Switching Protocols` response. +If you want to use WebSockets with HTTP, you only need one ngrok endpoint: you can start a server where listeners for both protocols share a single port. + +## What you'll need + +- Node.js installed on your machine. +- An [ngrok account](https://dashboard.ngrok.com/signup). +- Your [ngrok authtoken](https://dashboard.ngrok.com/get-started/your-authtoken). + +## 1. Install dependencies + +```sh +npm install ws +``` + +## 2. Create the server + +Create a `server.js` file: + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +const server = createServer((req, res) => { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('OK\n'); +}); + +const wss = new WebSocketServer({ server }); + +wss.on('connection', (ws) => { + ws.on('message', (data) => ws.send(`Echo: ${data}`)); + ws.send('Hello from WebSocket'); +}); + +server.listen(8000); +``` + +## 3. Start ngrok + +A single ngrok endpoint handles traffic for both protocols. + +```sh +ngrok http 8000 +``` + +Connect to your WebSocket using the `wss://` scheme: + +```js +const ws = new WebSocket('wss://'); +```