Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions using-ngrok-with/websockets.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot add a line after this sentence that says "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."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3f22611 — added the sentence after line 7.

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://<your-ngrok-domain>');
```