JavaScript Answers

How to set custom client ID with and JavaScript?

Spread the love

In, the client ID is automatically generated by the library when a client connects to the server.

However, you can create your own custom identification system by sending a custom identifier from the client to the server when the connection is established.

On the client-side (JavaScript using we have:

<script src=""></script>
  // Connect to the server
  const socket = io('http://localhost:3000', {
    query: {
      clientId: 'yourCustomClientIdHere' // Set your custom client ID here

  // Handle connection event
  socket.on('connect', () => {
    console.log('Connected to server');

  // Handle other events as needed

On the server-side (Node.js using

const io = require('')(3000);

// Handle connection event
io.on('connection', (socket) => {
  console.log('New client connected with ID:',;

  // Access custom client ID sent from client
  const clientId = socket.handshake.query.clientId;
  console.log('Custom client ID:', clientId);
  // Handle other events as needed

In this example, on the client-side, when establishing a connection to the server, we pass a query object to the io() function.

This query object contains the custom client ID (clientId) that we want to use.

On the server-side, when a new connection is established, provides access to the handshake object, which contains the query parameters sent from the client.

We can access the clientId from the handshake.query object.

By sending the custom client ID as a query parameter during the connection handshake, you can effectively set a custom client ID with

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *