Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Websocket connection fails on localhost because of Content Security Policy?

So, I'm using ws package for my backend, and this is my server that I copied from getting started page:

import { WebSocketServer } from 'ws'

const wss = new WebSocketServer({ port: 8080 })

wss.on('connection', function connection(ws) {
  ws.on('message', function message(data) {
    console.log('received: %s', data)
  })

  ws.send('something')
})

Now, in my browser console I run this :

const socket = new WebSocket("ws://localhost:8080")

I get an error:

Content Security Policy: The page’s settings blocked the loading of a resource at ws://localhost:8080/ (“connect-src”).

I've done some googling, and it seems like the connection should be secure in order it to work? However, MDN and other sources do not mention it anywhere. Am I doing something wrong? I'd appreciate any help.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This error is due to Content Security Policy (mdn) as it's written over there. And if you were running a local server and tried this in that, it would've been worked.

in my browser console I run this

So, here is a problem. The new tab, or wherever you've run this, might have blocked this request to protect against XSS or something like that. The easiest thing to make this work is to add a meta tag <meta http-equiv="Content-Security-Policy" content="connect-src 'ws://localhost:8080';"> to the HTML page or run a local server.

about 4 years ago · Juan Pablo Isaza Report

0

Creating a websocket connection in a browser console was failing for some reason, however, after I created a simple html page with a script it worked without any problems:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    const socket = new WebSocket('ws://localhost:8080')
    console.log(socket)
  </script>
</html>

I hope it saves some time for other people.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!