jsdrop.

WebSockets starter

A realtime chat room: an HTTP page plus a WebSocket server on one port.

Open in editor Free. Runs in your browser, no sign-up.
  • ws
WebSockets

The code

Two files, exactly what you get in the editor.

import { createServer } from 'node:http'
import { WebSocketServer, WebSocket } from 'ws'

const page = `<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chat</title>
<style>
  body { font: 16px system-ui, sans-serif; max-width: 560px; margin: 32px auto; padding: 0 16px; }
  #log { border: 1px solid #ddd; border-radius: 10px; height: 300px; overflow: auto; padding: 10px; }
  form { display: flex; gap: 8px; margin-top: 10px; } input { flex: 1; padding: 8px; }
</style>
<h1>Chat</h1>
<div id="log"></div>
<form><input placeholder="Say something…" autofocus><button>Send</button></form>
<script>
  const log = document.getElementById('log')
  const input = document.querySelector('input')
  const socket = new WebSocket(location.href.replace(/^http/, 'ws'))
  socket.onmessage = (event) => {
    const line = document.createElement('div')
    line.textContent = event.data
    log.append(line)
    log.scrollTop = log.scrollHeight
  }
  document.querySelector('form').onsubmit = (event) => {
    event.preventDefault()
    if (input.value) socket.send(input.value)
    input.value = ''
  }
</script>`

const server = createServer((_req, res) => {
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
  res.end(page)
})

const wss = new WebSocketServer({ server })
let guest = 0
wss.on('connection', (socket) => {
  const name = `guest-${++guest}`
  const broadcast = (text: string) => {
    for (const client of wss.clients)
      if (client.readyState === WebSocket.OPEN) client.send(text)
  }
  broadcast(`${name} joined`)
  socket.on('message', (data) => broadcast(`${name}: ${data}`))
  socket.on('close', () => broadcast(`${name} left`))
})

const port = Number(process.env.PORT) || 3000
server.listen(port, () => console.log(`Chat on port ${port}`))
{
  "name": "websocket-chat",
  "private": true,
  "type": "module",
  "dependencies": {
    "ws": "^8.18.0"
  }
}

Questions

Can I run WebSockets in the browser?

Yes. Press Run and the program runs in a Node.js-compatible runtime, compiled to WebAssembly, right in your browser tab. npm packages install in the browser too.

How do I start a WebSockets project online?

Click Open in editor. jsdrop copies this starter into a new drop with index.ts and package.json. Press Run to start it, and edit as you go.

Can other people reach my server?

Yes. When the program calls listen(), the preview shows the server and a public tunnel URL that works while your tab runs it. With Pro, deploy the drop to run around the clock at its own address.

Is it free?

Yes. Public drops, running in the browser, live collaboration, versions, and embeds are free, and you do not need an account to start.

More starter kits