# Websocket with authentication

**URL:** https://discourse.nodered.org/t/websocket-with-authentication/78567
**Category:** Feature Requests
**Tags:** security
**Created:** [21 May 2023 07:54 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567 "2023-05-21T07:54:34Z")
**Posts on this page:** 5
**Page:** 2

<div class="post-metadata">

### Author: ![pbr](https://avatars.discourse-cdn.com/v4/letter/p/ba8739/32.png) [@pbr](https://discourse.nodered.org/u/pbr)
#### Post date: [25 May 2023 15:19 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567/21 "2023-05-25T15:19:37Z")

</div>

@Steve-Mcl thanks. Requiring **ws** in the setup of the node was an eye opener 😃

My code in the function is as follows (the company has advised using Sec-WebSocket-Protocol for sending the Authorization token)

```auto
const token = "xxxx";

const options = {
  headers: {
    "Sec-WebSocket-Protocol": "API-Authorization", token
  }
};

console.log("Trying to establish a websocket communication ....\n")

// Establish a WebSocket connection
const socket = new WebSocket("wss://unify-api.autostoresystem.com/v1/installations/a031v00001CTMX2AAP/", options);

// Handle incoming messages
socket.onmessage = (event) => {
  const message = JSON.parse(event.data);
  // Process the received message
  console.log("Received message: ", message);
};

// Handle connection close event
socket.onclose = (event) => {
  console.log( "Connection closed with code: ", event.code);
};

// Handle connection error event
socket.onerror = (error) => {
  console.error("WebSocket error: ", error);
};

return msg;

```

It still returns an error, but much more detailed information. At least I can see that the authentication token has been passed in the request header. However, I do not see what in my code has triggered the error response.

```auto
Trying to establish a websocket communication ....

WebSocket error: ErrorEvent {
  [Symbol(kTarget)]: WebSocket {
    _events: [Object: null prototype] {
      message: [Function],
      close: [Function],
      error: [Function]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _binaryType: 'nodebuffer',
    _closeCode: 1006,
    _closeFrameReceived: false,
    _closeFrameSent: false,
    _closeMessage: <Buffer >,
    _closeTimer: null,
    _extensions: {},
    _paused: false,
    _protocol: '',
    _readyState: 2,
    _receiver: null,
    _sender: null,
    _socket: null,
    _bufferedAmount: 0,
    _isServer: false,
    _redirects: 0,
    _url: 'wss://unify-api.autostoresystem.com/v1/installations/a031v00001CTMX2AAP/',
    _req: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: true,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'GET /v1/installations/a031v00001CTMX2AAP/ HTTP/1.1\r\n' +
        'Sec-WebSocket-Protocol: API-Authorization\r\n' +
        'token: xxxx\r\n‘ +
        'Sec-WebSocket-Version: 13\r\n' +
        'Sec-WebSocket-Key: bx/QZ1XM5NyAbFyhcdpsHg==\r\n' +
        'Connection: Upgrade\r\n' +
        'Upgrade: websocket\r\n' +
        'Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n' +
        'Host: unify-api.autostoresystem.com\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: undefined,
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/v1/installations/a031v00001CTMX2AAP/',
      _ended: false,
      res: [IncomingMessage],
      aborted: true,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'unify-api.autostoresystem.com',
      protocol: 'https:',
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kUniqueHeaders)]: null,
      [Symbol(kAborted)]: true,
      [Symbol(kError)]: undefined
    },
    [Symbol(kCapture)]: false
  },
  [Symbol(kType)]: 'error',
  [Symbol(kError)]: Error: Unexpected server response: 500
      at ClientRequest.<anonymous> (/Users/peikbremer/.node-red/node_modules/ws/lib/websocket.js:888:7)
      at ClientRequest.emit (node:events:513:28)
      at HTTPParser.parserOnIncomingClient (node:_http_client:701:27)
      at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
      at TLSSocket.socketOnData (node:_http_client:542:22)
      at TLSSocket.emit (node:events:513:28)
      at addChunk (node:internal/streams/readable:324:12)
      at readableAddChunk (node:internal/streams/readable:297:9)
      at TLSSocket.Readable.push (node:internal/streams/readable:234:10)
      at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23),
  [Symbol(kMessage)]: 'Unexpected server response: 500'
}
Connection closed with code: 1006

```

Anyone seeing what may be the problem?

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [25 May 2023 15:26 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567/22 "2023-05-25T15:26:28Z")

</div>

> [@pbr](#):
>
> `Connection closed with code: 1006`

Error 1006 means **there's a low-level issue with websocket itself, or rather the code used to create the websocket**

I wonder if the guys setting up this service could provide a minimal working nodejs WebSocket (or `ws`) demo repl for us to dissect and make work in a function node?

---

<div class="post-metadata">

### Author: ![pbr](https://avatars.discourse-cdn.com/v4/letter/p/ba8739/32.png) [@pbr](https://discourse.nodered.org/u/pbr)
#### Post date: [26 May 2023 08:46 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567/23 "2023-05-26T08:46:01Z")

</div>

@Steve-Mcl I do not have direct contact with them, all communication is routed via the storage system manufacturer, but I will try my best.

---

<div class="post-metadata">

### Author: ![pbr](https://avatars.discourse-cdn.com/v4/letter/p/ba8739/32.png) [@pbr](https://discourse.nodered.org/u/pbr)
#### Post date: [31 May 2023 10:53 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567/24 "2023-05-31T10:53:09Z")

</div>

@Steve-Mcl @TotallyInformation

Finally, I have the access working 😀

```auto
const serverUrl = 'wss://unify-api.autostoresystem.com/v1/installations/zzzzzz/';

// Create a new WebSocket instance and pass the server URL and header Sec-WebSocket-Secure

const socket = new WebSocket(serverUrl,["API-Authorization","Token-xxxx"]);

// Event: Connection established

socket.onopen = () => {

console.log("WebSocket connection established");

};

// Event: Message received from the server

socket.onmessage = (event) => {

console.log("Message from server:", event.data);

};

// Event: Connection closed

socket.onclose = (event) => {

console.log("WebSocket connection closed with code:", event.code);

};

// Event: Connection error

socket.onerror = (error) => {

console.error("WebSocket error:
", error);

};

```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [30 July 2023 10:53 UTC](https://discourse.nodered.org/t/websocket-with-authentication/78567/25 "2023-07-30T10:53:36Z")

</div>

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.

[Previous page](https://discourse.nodered.org/t/websocket-with-authentication/78567.md?page=1)
