The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED.

Nginx configuration:

server {
  server_name    domain.domain;
  access_log     /var/log/nginx/domain.domain.access.log;
  error_log      /var/log/nginx/domain.domain.error.log;
  location / {
      proxy_connect_timeout 1d;
      proxy_send_timeout 1d;
      proxy_read_timeout 1d;
      proxy_pass http://localhost:3001;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      proxy_set_header Host $host;
  }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.domain/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.domain/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = domain.domain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


  server_name    domain.domain;
    listen 80;
    return 404; # managed by Certbot


}

Sample server code:

import { WebSocketServer } from 'ws';
this.connection = new WebSocketServer(args, () => {
  log('info', 'Server listen at port:', args.port, true);
});
this.connection.on('connection', (ws, req) => {
  // Event is triggered fine 
  console.log('Client connected');
})

Sample client code:

const connection = new WebSocket(
  'wss://domain.domain:443', 'json'
);
connection.onopen = () => {
  // Although the event is triggered, connection.readyState remains CLOSED
  setInterval(() => {
    console.log(connection.readyState);
  }, 1000)
}
connection.onerror = () => {
  // This event is never triggered
}
connection.onclose = () => {
  // This event is never triggered
}

Prior to this occurrence, the same code functioned seamlessly with identical server configurations. However, after recreating the virtual server from a backup, this issue emerged, despite all other functionality remaining consistent.

Answer №1

Upon reviewing my code once more, I noticed that after the last successful test, I implemented a CORS check on the server. However, it turns out that the configuration of this CORS check was not properly set up in the environment variables.

this.connection.on('connection', (ws, req) => {
  // Event is triggered fine 
  console.log('Client connected');
  const { origin } = req.headers;
  const notAllowed = process.env.CORS.split(',').indexOf(origin || '') === -1;
  if (cors && notAllowed) {
    log('warn', 'Block CORS attempt', { headers: req.headers });
    ws.close();
    return;
  }
})

Another issue to address is why the onclose event did not trigger on the client and why the warn message was not displayed on the server. It's possible that the output method to stdout may have also failed due to incorrect environment variables. However, this specific issue will be investigated separately and does not require immediate attention here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with synchronizing Firebase and Node.js?

https://i.stack.imgur.com/3fwRO.png Here is the code snippet I used in my Node.js application: for(var v in sna.val()){ console.log("each "+va); console.log(v); var fourthRef = ref.child(val+'/reservation/&apos ...

Unique text: "Custom sorting of JavaScript objects in AngularJS using a special JavaScript order

I'm working with an array structured like this: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = { start: '10:00', end: '11:30' } var item3 = { start: '12:00& ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Using JavaScript to place markers on a Google Map may encounter an issue with a for

Close to solving a three-day challenge. Currently working on placing markers on a Google Map using latitudes and longitudes stored in a Django model. This is my first time using AJAX, but I'm giving it a shot to make this work. Firebug is pointing out ...

Issue with populating dropdown menu inside jquery modal dialog box

When I click on the 'create new button', a modal window form pops up with a dropdown menu. The dropdown is supposed to be populated via ajax with the help of the populateUserData() function. Even though the ajax call seems to be successful, I am ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

The expected property 'label' is not found in the object type '{ handleClick: () => void; }', but it is required in the object type '{ handleClick: () => void; label: string; }'

I'm encountering difficulties when describing the types of my props. The issue arises with the following code: <PostButton handleClick={props.upvote}/> <PostButton2 handleClick={props.downvote}/> An error message is displayed: Pro ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

Tips for Identifying Different ID Values of HTML Elements with jQuery

Currently, I have two different divs on my webpage, each containing buttons and hidden fields. When I try to pass the value of the hidden field attached to the button in a jQuery function, I encounter an issue where clicking on the second div results in pa ...

Combining input streams using node.js and ffmpeg

Currently, I'm in the process of developing a basic and straightforward Video-Web-Chat platform. My approach involves utilizing the getUserMedia API call on the client side to capture webcam data and transmit it as data-blob to my server. My plan is ...

Implement a React Component as a unique OverlayView within the Google Maps application

Utilizing the Google Maps JavaScript API V3, I have created a map with clustered and draggable map markers. Instead of relying on React libraries that interact with the google maps API, we chose to build our own solution due to limitations in drag function ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...

Tips for minimizing unnecessary rerenders in child components that rely on cached information from the parent component

check out the sandbox here Application maintains state to compute a memoized value, which is then passed as props to the Options. When a change occurs in the state triggered by a callback function in Option, it causes a rerender of the main Application, r ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

The act of transferring non-textual information into web-based applications

Is it possible for a user to copy and paste a selection of pixels from MSPaint into a browser-based app using JavaScript in current browsers? If not, will HTML5 make this possible in the future? Alternatively, could something like Flex or Silverlight be us ...

What is the most effective method to arrange absolute divs generated randomly in a grid-like formation?

Hey there! I'm facing an intriguing challenge with my app. It's designed to generate a variable number of divs which are always in absolute positioning. Unfortunately, making them relative is not an option due to some other factors within the app ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...