Websocket with authentication

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

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

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.

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' +
      _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?

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?

@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.

@Steve-Mcl @TotallyInformation

Finally, I have the access working :grinning:

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);


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