Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Serving the Client, CORS and Server Options

Learn how to serve the Socket.IO client, fix CORS errors, change the path, and tune the most useful server and client options such as transports, pingInterval and maxHttpBufferSize.

Your first server worked on one machine with one origin. Real projects split a front-end (for example a Vite dev server on port 5173) from a back-end (port 3000), run behind proxies, and need tuning. This lesson covers the options you will touch most often and the number-one error beginners hit: CORS.

Getting the client into the page

You have four common choices:

  1. Same server, bundled script. The server serves /socket.io/socket.io.js automatically (the option serveClient defaults to true). Write <script src="/socket.io/socket.io.js"></script> and a global io function appears.
  2. A CDN script. <script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script> works for quick demos.
  3. An npm package with a bundler. npm install socket.io-client, then import { io } from 'socket.io-client'. This is best for real apps because you control the exact version and tree-shaking.
  4. Node.js. The same npm package runs in Node scripts, which is handy for bots and tests.

Pick one, and keep the major version identical on both sides. A v2 client against a v4 server fails during the handshake.

CORS in one minute

Browsers block a page from reading responses of another origin. An origin is scheme + host + port: http://localhost:5173 and http://localhost:3000 are different origins. The long-polling transport uses ordinary HTTP requests, so the server must reply with CORS headers that explicitly allow the page's origin.

JavaScript
const io = new Server(httpServer, {
  cors: {
    origin: ['http://localhost:5173', 'https://app.example.com'],
    methods: ['GET', 'POST'],
    credentials: true, // allow cookies on cross-origin requests
  },
});

Three rules prevent most CORS headaches:

  • origin can be a string, an array of strings, a regular expression, or true to reflect any origin. Avoid '*' for production apps that use cookies; browsers refuse * together with credentials: true.
  • If your front-end and back-end share an origin (for example the same domain behind a reverse proxy), you need no cors option at all.
  • WebSocket handshakes are not governed by CORS the way fetch requests are, so a missing header may appear to "work" over WebSocket but fail on polling. Always allow the origin properly.

The program below implements the origin-matching idea in plain Node. It is not the real middleware, just the same decision logic, so you can see which values pass.

Node.js Which origins are allowed?

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.

The trailing-slash row shows a classic mistake: browsers send origins without a trailing slash, so a configured value with one never matches.

Server options you will actually use

Pass these as the second argument of new Server(...):

Option Default What it does
path /socket.io/ URL path the server answers on; must match the client's path.
cors none CORS headers (see above).
transports ['polling', 'websocket'] Allowed transports, in upgrade order.
pingInterval 25000 ms How often the server pings each client.
pingTimeout 20000 ms How long to wait for the pong before closing.
maxHttpBufferSize 1e6 bytes Largest accepted message. Bigger ones disconnect the client.
connectTimeout 45000 ms How long a client may stay connected to the server but not yet to a namespace.
serveClient true Serve /socket.io/socket.io.js. Set false if you bundle the client yourself.
connectionStateRecovery off Let reconnecting clients receive events they missed (covered later).

A production-leaning example (read-only):

JavaScript
const io = new Server(httpServer, {
  cors: { origin: process.env.WEB_ORIGIN },
  maxHttpBufferSize: 1e5,   // 100 kB is plenty for chat messages
  pingInterval: 20000,
  pingTimeout: 10000,
  serveClient: false,
});

Lowering maxHttpBufferSize is a cheap defence: it limits how much memory a single misbehaving client can make the server buffer.

Client options

The second argument of io(url, options) configures the client. The most used:

JavaScript
const socket = io('https://api.example.com', {
  path: '/socket.io/',
  transports: ['websocket'],
  autoConnect: false,       // do not connect until socket.connect()
  auth: { token: 'abc' },   // sent in the handshake (see the authentication chapter)
  query: { room: 'lobby' }, // added to the URL; visible in logs, so no secrets
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
  withCredentials: true,    // send cookies cross-origin
});

With autoConnect: false you decide when to open the connection, for example after the user logs in. Call socket.connect() then, and socket.disconnect() to stop.

What the handshake URL looks like

Every option eventually shows up in the first HTTP request. This stand-in builds the polling URL from the client options so you can see the pieces. It is a simplified model of the real client.

Node.js Building the handshake URL

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.

If your reverse proxy only forwards certain paths to the Node process, this is the URL it must allow, including the WebSocket upgrade.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Your page at http://localhost:5173 cannot connect to a Socket.IO server at http://localhost:3000 and the console shows a CORS error. What do you fix?

    The two ports are different origins, so the server must send CORS headers that allow http://localhost:5173.
  2. 2. Which cors origin value never matches a browser's Origin header?

    Browsers send origins without a trailing slash, so a configured value ending in / is never equal.
  3. 3. What does autoConnect: false do on the client?

    The socket object is created but stays disconnected until you connect it, which suits connect-after-login flows.
  4. 4. What happens when a client sends a message larger than maxHttpBufferSize?

    Oversized messages are rejected and the connection is closed, protecting server memory.

Summary

  • Serve the client from the Socket.IO server, a CDN, or npm; keep both sides on the same major version.
  • Different origins need the cors option; match origins exactly, with no trailing slash.
  • Useful server options: path, transports, pingInterval, pingTimeout, maxHttpBufferSize, serveClient.
  • Useful client options: autoConnect, auth, query, transports, reconnection settings, withCredentials.
  • Options end up in the handshake URL and headers, which is what proxies and firewalls see.

Next: Choosing a Real-Time Technology