Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Connections and Events

Designing Events and Payloads

Design clean Socket.IO events. Learn naming conventions, payload shapes, versioning, validating untrusted input, sending binary data, and using deltas instead of full state.

Socket.IO lets you invent any event name and send any data, which is both a gift and a trap. Real-time apps grow quickly, and a messy event vocabulary becomes painful: nobody remembers whether it was newMsg, new_message or message-new, handlers receive half-filled objects, and one malformed payload from a client crashes the server. A little design up front prevents all of it.

Name events like an API

Your events are an API between client and server, so give them the same care as REST endpoints. A convention that scales:

  • Use noun:verb (or domain:action): message:send, message:new, room:join, cursor:move. Related events sort together and a reader instantly sees the domain.
  • Separate commands from notifications. A command is what a client asks for (message:send); a notification is what the server announces (message:new). Using different names avoids loops and shows who is allowed to emit what.
  • Past tense for facts, imperative for requests: user:joined, order:updated are facts; room:join, order:cancel are requests.
  • Keep names stable. Clients in the wild (old mobile apps, cached tabs) will keep emitting old names for months.

Collect names in one module both sides can import:

JavaScript
// events.js (shared)
export const EVENTS = {
  MESSAGE_SEND: 'message:send',
  MESSAGE_NEW: 'message:new',
  ROOM_JOIN: 'room:join',
  USER_JOINED: 'user:joined',
};

One object beats many arguments

You can emit several arguments, but long positional lists are fragile: socket.emit('move', 3, 4, true, 'north') tells a reader nothing and cannot gain a new field without breaking old clients. Prefer one payload object with named fields:

JavaScript
socket.emit('player:move', { x: 3, y: 4, running: true, heading: 'north' });

Adding { speed: 2 } later is harmless because old handlers ignore fields they do not know. Include an id and a timestamp (server time) where the order of events or deduplication matters.

If your protocol may change incompatibly, add a version field ({ v: 2, ... }) or version the event name (message:send:v2), and keep the old handler running until old clients are gone.

Never trust the client

Everything arriving from a socket is user input. A browser console lets anyone emit any event with any data, regardless of what your UI would send. Each handler should check:

  1. Shape: required fields exist and have the right types.
  2. Size and range: strings are not megabytes long; numbers are within bounds.
  3. Permission: this user may do this action (covered in the authentication chapter).

The program below validates payloads with a small hand-written schema helper (not a library) inside a server handler, and answers invalid input with an error event rather than crashing.

Node.js Validating payloads in a handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real project use a schema library such as Zod or Joi instead of hand-rolling, but the principle is the same: validate first, act second, and always give the sender a clear error.

An exception thrown inside a socket.on handler can crash the whole Node process if nothing catches it. Validate input and wrap risky work (database calls, JSON parsing) in try/catch. A later lesson covers error handling in depth.

Send changes, not the world

A frequent performance mistake is emitting the entire state on every change: the full list of 500 messages whenever one arrives. Send a delta (what changed) and let clients apply it. Plain Node can show the size difference:

Node.js Full state versus deltas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Deltas need a way to recover from missed events: after a reconnect the client should fetch a fresh snapshot (over HTTP or through an acknowledgement) and then continue applying deltas.

Binary data

When a payload is large and binary (an image, an audio chunk), send it as a Buffer or ArrayBuffer argument instead of base64 text. Base64 inflates data by about a third and costs CPU to encode and decode. Socket.IO ships binary parts as separate frames automatically:

JavaScript
// client
socket.emit('avatar:upload', { name: 'me.png', bytes: await file.arrayBuffer() });

// server
socket.on('avatar:upload', ({ name, bytes }) => {
  console.log(name, Buffer.from(bytes).length); // Buffer on Node
});

Mind maxHttpBufferSize (1 MB by default). For big files, use normal HTTP uploads (see file uploads in Node.js) and send only a notification event.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer one payload object over several positional arguments?

    A named-field object evolves safely: old code ignores new fields, and readers understand each value.
  2. 2. Which pair follows a clean command/notification split?

    Different names for the request and the announcement make clear who emits what and avoid accidental loops.
  3. 3. A client emits message:send with a 5 MB text field. Where should this be rejected?

    Any client can emit arbitrary data, so the server must validate sizes and shapes itself.
  4. 4. What is a sensible way to send a 200 kB PNG over Socket.IO?

    Binary arguments are sent as binary frames without the one-third overhead of base64.

Summary

  • Name events like an API: domain:action, stable, with separate command and notification names.
  • Send one payload object with named fields; add versions or new fields without breaking old clients.
  • Validate shape, size and permissions in every handler; reply with a clear error event.
  • Send deltas rather than full state, and re-sync after reconnects.
  • Use binary arguments for binary data and plain HTTP for large files.

Next: Reconnection, Heartbeats and State Recovery