WebSocket Basics in the Browser
new WebSocket(url), onopen/onmessage/onerror/onclose, send(), readyState.
WebSocket Basics in the Browser is a free Vue Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Real-Time in the Browser
HTTP is request/response: the client asks, the server answers, and the connection closes. For chat, live dashboards, or multiplayer games you need the server to push data without being asked.
The WebSocket protocol gives you a single long-lived, two-way connection between browser and server.
Opening a Connection
The browser ships a global WebSocket constructor. Pass a URL using the ws:// (plain) or wss:// (TLS) scheme.
Creating the object immediately starts the connection handshake.
const ws = new WebSocket("wss://echo.example.com/socket")
// Construction kicks off the connection.
// Nothing is sent yet — we wait for it to open.The onopen Handler
The connection is not ready the instant you construct it. The onopen event fires once the handshake completes and the socket is ready to carry data.
Send your first message from inside onopen, never before.
const ws = new WebSocket("wss://echo.example.com/socket")
ws.onopen = () => {
console.log("Connected!")
ws.send("hello server")
}Receiving Messages
Incoming data arrives through onmessage. The payload is on event.data and is a string by default.
Most apps send JSON, so you parse it back into an object.
ws.onmessage = (event) => {
const msg = JSON.parse(event.data)
console.log("Got:", msg.type, msg.payload)
}Sending Messages
Use ws.send() to transmit. WebSockets carry raw strings or binary, so encode objects with JSON.stringify first.
Both sides agree on a shape — here a type plus a payload.
function sendChat(text) {
const msg = { type: "chat", payload: { text } }
ws.send(JSON.stringify(msg))
}
sendChat("Good morning")A Full Round Trip
Putting open, send, and receive together gives you a complete echo client. Open the socket, send on open, log whatever comes back.
const ws = new WebSocket("wss://echo.example.com/socket")
ws.onopen = () => {
ws.send(JSON.stringify({ type: "ping" }))
}
ws.onmessage = (event) => {
const data = JSON.parse(event.data)
console.log("Server replied:", data)
}Closing the Connection
The onclose event fires when the connection ends — whether you called ws.close() or the network dropped. The event carries a numeric code and a reason string.
Code 1000 means a normal closure.
ws.onclose = (event) => {
console.log("Closed:", event.code, event.reason)
if (event.code !== 1000) {
console.log("Unexpected close — may want to reconnect")
}
}
// Trigger a clean close yourself:
// ws.close(1000, "done")Handling Errors
The onerror event fires on transport failures. The error event itself is intentionally light on detail for security; treat it as a signal that something went wrong and a close is likely coming.
ws.onerror = (event) => {
console.error("WebSocket error occurred")
// onclose usually fires right after onerror.
}The readyState Property
ws.readyState is a number telling you where the socket is in its lifecycle. Always check it before sending so you do not throw on a not-yet-open socket.
- 0 CONNECTING
- 1 OPEN
- 2 CLOSING
- 3 CLOSED
function safeSend(data) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data))
} else {
console.warn("Not open, readyState =", ws.readyState)
}
}Named readyState Constants
Instead of magic numbers, use the constants on the WebSocket class. They read far more clearly than 0, 1, or 3.
console.log(WebSocket.CONNECTING) // 0
console.log(WebSocket.OPEN) // 1
console.log(WebSocket.CLOSING) // 2
console.log(WebSocket.CLOSED) // 3
if (ws.readyState === WebSocket.OPEN) {
ws.send("ready to talk")
}Putting It Together in Vue
Inside a Vue component you usually create the socket in onMounted and tear it down in onUnmounted. The handlers update reactive refs that your template renders.
import { ref, onMounted, onUnmounted } from "vue"
const messages = ref([])
let ws
onMounted(() => {
ws = new WebSocket("wss://echo.example.com/socket")
ws.onmessage = (e) => messages.value.push(JSON.parse(e.data))
})
onUnmounted(() => ws && ws.close())Quick Check
Check your understanding of WebSocket readyState values.
Recap
In this lesson you learned:
new WebSocket(url)starts a two-way connection usingws://orwss://.onopenfires when the socket is ready; send only after it.onmessagedelivers data onevent.data— parse JSON to get an object.ws.send(JSON.stringify(msg))transmits data.oncloseandonerrorhandle teardown and failures.readyStateis 0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED.
Frequently asked questions
Is the “WebSocket Basics in the Browser” lesson free?
Yes — the full text of “WebSocket Basics in the Browser” is free to read here on the web, and the Vue Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.
What will I learn in “WebSocket Basics in the Browser”?
new WebSocket(url), onopen/onmessage/onerror/onclose, send(), readyState. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vue Academy?
No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “WebSocket Basics in the Browser” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vue Academy lesson?
Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- WebSocket Basics in the Browser
- Socket.io Client with Vue
- Building a Real-Time Chat Component
- useWebSocket Composable with Reconnection