D
Deno

help

Headers for WebSocket client

TtheANDYM2/9/2024
I need to connect Deno (as a client) to a WebSocket server that requires custom headers on connection. I can't seem to find any currently supported method to accomplish this since the WebSocket API only allows for the url and protocols parameters. Is there any known best practice to accomplish this?
DAHDeno AI Helper2/9/2024
The documentation indicates that as of Deno 1.18, users have the ability to set custom headers on outbound WebSockets. This feature is available through the use of the unstable WebSocketStream API. Here's an example from the documentation on how to use this feature:
const ws = new WebSocketStream("wss://example.com", {
headers: { "X-Custom-Header": "foo" },
});
const ws = new WebSocketStream("wss://example.com", {
headers: { "X-Custom-Header": "foo" },
});
The headers property in the options object has the same signature as the headers property in the fetch function, and Request/Response constructors. However, it's important to note that this is a non-standard extension and should be used with care. To use this unstable feature, you might need to run your Deno script with the --unstable flag. Here's an example command to run your Deno script with the necessary permissions:
deno run --unstable --allow-net your_script.ts
deno run --unstable --allow-net your_script.ts
Remember to replace your_script.ts with the path to your actual Deno script file. 🦕

Looking for more? Join the community!