PageSourceSearch

https://socket.io/assets/js/400f1b51.48f273af.js

js socket.io collected 2026-09-24 07:26:03 UTC 13,926 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunksample_website=self.webpackChunksample_website||[]).push([[5814],{3905:(e,t,n)=>{n.d(t,{Zo:()=>d,kt:()=>m});var a=n(7294);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t){if(null==e)return{};var n,a,o=function(e,t){if(null==e)return{};var n,a,o={},r=Object.keys(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var c=a.createContext({}),l=function(e){var t=a.useContext(c),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},d=function(e){var t=l(e.components);return a.createElement(c.Provider,{value:t},e.children)},p="mdxType",k={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},u=a.forwardRef((function(e,t){var n=e.components,o=e.mdxType,r=e.originalType,c=e.parentName,d=s(e,["components","mdxType","originalType","parentName"]),p=l(n),u=o,m=p["".concat(c,".").concat(u)]||p[u]||k[u]||r;return n?a.createElement(m,i(i({ref:t},d),{},{components:n})):a.createElement(m,i({ref:t},d))}));function m(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var r=n.length,i=new Array(r);i[0]=u;var s={};for(var c in t)hasOwnProperty.call(t,c)&&(s[c]=t[c]);s.originalType=e,s[p]="string"==typeof e?e:o,i[1]=s;for(var l=2;l<r;l++)i[l]=n[l];return a.createElement.apply(null,i)}return a.createElement.apply(null,n)}u.displayName="MDXCreateElement"},5103:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>c,contentTitle:()=>i,default:()=>k,frontMatter:()=>r,metadata:()=>s,toc:()=>l});var a=n(3117),o=(n(7294),n(3905));const r={title:"The Socket instance (server-side)",sidebar_label:"The Socket instance",sidebar_position:4,slug:"/server-socket-instance/"},i=void 0,s={unversionedId:"categories/Server/server-socket-instance",id:"version-3.x/categories/Server/server-socket-instance",title:"The Socket instance (server-side)",description:"Besides:",source:"@site/versioned_docs/version-3.x/categories/02-Server/server-socket-instance.md",sourceDirName:"categories/02-Server",slug:"/server-socket-instance/",permalink:"/docs/v3/server-socket-instance/",draft:!1,editUrl:"https://github.com/socketio/socket.io-website/edit/main/versioned_docs/version-3.x/categories/02-Server/server-socket-instance.md",tags:[],version:"3.x",lastUpdatedAt:1784117104,formattedLastUpdatedAt:"Jul 15, 2026",sidebarPosition:4,frontMatter:{title:"The Socket instance (server-side)",sidebar_label:"The Socket instance",sidebar_position:4,slug:"/server-socket-instance/"},sidebar:"version-3.x/sidebar",previous:{title:"The Server instance",permalink:"/docs/v3/server-instance/"},next:{title:"Middlewares",permalink:"/docs/v3/middlewares/"}},c={},l=[{value:"Socket#id",id:"socketid",level:2},{value:"Socket#handshake",id:"sockethandshake",level:2},{value:"Socket#rooms",id:"socketrooms",level:2},{value:"Additional attributes",id:"additional-attributes",level:2},{value:"Socket middlewares",id:"socket-middlewares",level:2},{value:"Events",id:"events",level:2},{value:"<code>disconnect</code>",id:"disconnect",level:3},{value:"<code>disconnecting</code>",id:"disconnecting",level:3},{value:"Complete API",id:"complete-api",level:2}],d={toc:l},p="wrapper";function k(e){let{components:t,...n}=e;return(0,o.kt)(p,(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("p",null,"Besides:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("a",{parentName:"li",href:"/docs/v3/emitting-events/#Basic-emit"},"emitting")," and ",(0,o.kt)("a",{parentName:"li",href:"/docs/v3/listening-to-events/"},"listening to")," events"),(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("a",{parentName:"li",href:"/docs/v3/broadcasting-events/#To-all-connected-clients-excepting-the-sender"},"broadcasting events")),(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("a",{parentName:"li",href:"/docs/v3/rooms/#Joining-and-leaving"},"joining and leaving rooms"))),(0,o.kt)("p",null,"The Socket instance has a few attributes that may be of use in your application:"),(0,o.kt)("h2",{id:"socketid"},"Socket#id"),(0,o.kt)("p",null,"Each new connection is assigned a random 20-ch
1aracters identifier."),(0,o.kt)("p",null,"This identifier is synced with the value on the client-side."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'// server-side\nio.on("connection", (socket) => {\n  console.log(socket.id); // ojIckSD2jqNzOqIrAGzL\n});\n\n// client-side\nsocket.on("connect", () => {\n  console.log(socket.id); // ojIckSD2jqNzOqIrAGzL\n});\n')),(0,o.kt)("p",null,"Upon creation, the Socket joins the room identified by its own id, which means you can use it for private messaging:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'io.on("connection", socket => {\n  socket.on("private message", (anotherSocketId, msg) => {\n    socket.to(anotherSocketId).emit("private message", socket.id, msg);\n  });\n});\n')),(0,o.kt)("p",null,"Note: you can't overwrite this identifier, as it is used in several parts of the Socket.IO codebase."),(0,o.kt)("h2",{id:"sockethandshake"},"Socket#handshake"),(0,o.kt)("p",null,"This object contains some details about the handshake that happens at the beginning of the Socket.IO session."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},"{\n  headers: /* the headers of the initial request */\n  query: /* the query params of the initial request */\n  auth: /* the authentication payload */\n  time: /* the date of creation (as string) */\n  issued: /* the date of creation (unix timestamp) */\n  url: /* the request URL string */\n  address: /* the ip of the client */\n  xdomain: /* whether the connection is cross-domain */\n  secure: /* whether the connection is secure */\n}\n")),(0,o.kt)("p",null,"Example:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-json"},'{\n  "headers": {\n    "user-agent": "xxxx",\n    "accept": "*/*",\n    "host": "example.com",\n    "connection": "close"\n  },\n  "query": {\n    "EIO": "4",\n    "transport": "polling",\n    "t": "NNjNltH"\n  },\n  "auth": {\n    "token": "123"\n  },\n  "time": "Sun Nov 22 2020 01:33:46 GMT+0100 (Central European Standard Time)",\n  "issued": 1606005226969,\n  "url": "/socket.io/?EIO=4&transport=polling&t=NNjNltH",\n  "address": "::ffff:1.2.3.4",\n  "xdomain": false,\n  "secure": true\n}\n')),(0,o.kt)("h2",{id:"socketrooms"},"Socket#rooms"),(0,o.kt)("p",null,"This is a reference to the ",(0,o.kt)("a",{parentName:"p",href:"/docs/v3/rooms/"},"rooms")," the Socket is currently in."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'io.on("connection", (socket) => {\n  console.log(socket.rooms); // Set { <socket.id> }\n  socket.join("room1");\n  console.log(socket.rooms); // Set { <socket.id>, "room1" }\n});\n')),(0,o.kt)("h2",{id:"additional-attributes"},"Additional attributes"),(0,o.kt)("p",null,"As long as you do not overwrite any existing attribute, you can attach any attribute to the Socket instance and use it later:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'// in a middleware\nio.use(async (socket, next) => {\n  try {\n    const user = await fetchUser(socket);\n    socket.user = user;\n  } catch (e) {\n    next(new Error("unknown user"));\n  }\n});\n\nio.on("connection", (socket) => {\n  console.log(socket.user);\n\n  // in a listener\n  socket.on("set username", (username) => {\n    socket.username = username;\n  });\n});\n\n')),(0,o.kt)("h2",{id:"socket-middlewares"},"Socket middlewares"),(0,o.kt)("p",null,"Those middlewares look a lot like the usual ",(0,o.kt)("a",{parentName:"p",href:"/docs/v3/middlewares/"},"middlewares"),", except that they are called for each incoming packet:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},"socket.use(([event, ...args], next) => {\n  // do something with the packet (logging, authorization, rate limiting...)\n  // do not forget to call next() at the end\n  next();\n});\n")),(0,o.kt)("p",null,"The ",(0,o.kt)("inlineCode",{parentName:"p"},"next")," method can also be called with an error object. In that case, the event will not reach the registered event handlers and an ",(0,o.kt)("inlineCode",{parentName:"p"},"error")," event will be emitted instead:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'io.on("connection", (socket) => {\n  socket.use(([event, ...args], next) => {\n    if (isUnauthorized(event)) {\n      return next(new Error("unauthorized event"));\n    }\n    next();\n  });\n\n  socket.on("error", (err) => {\n    if (err && err.message === "unauthorized event") {\n      socket.disconnect();\n    }\n  });\n});\n')),(0,o.kt)("p",null,"Note: this feature only exists on the server-side. For the client-side, you might be interested in ",(0,o.kt)("a",{parentName:"p",href:"/docs/v3/listening-to-events/#Catch-all-listeners"},"catch-all listeners"),"."),(0,o.kt)("h2",{id:"events"},"Events"),(0,o.kt)("p",null,"On the server-side, the Socket instance emits two special events:"),(0,o.kt)("ul",null,(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("a",{parentName:"li",href:"#disconnect"},(0,o.kt)("inlineCode",{parentName:"a"},"disconnect"))),(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("a",{parentName:"li",href:"#disconnecting"},(0,o.kt)("inlineCode",{parentName:"a"},"disconnecting")))),(0,o.kt)("h3",{id:"disconnect"},(0,o.kt)("inlineCode",{parentName:"h3"},"disconnect")),(0,o.kt)("p",null,"This event is fired by the Socket instance upon disconnection."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'io.on("connection", (socket) => {\n  socket.on("disconnect", (reason) =>
1 {\n    // ...\n  });\n});\n')),(0,o.kt)("p",null,"Here is the list of possible reasons:"),(0,o.kt)("table",null,(0,o.kt)("thead",{parentName:"table"},(0,o.kt)("tr",{parentName:"thead"},(0,o.kt)("th",{parentName:"tr",align:null},"Reason"),(0,o.kt)("th",{parentName:"tr",align:null},"Description"))),(0,o.kt)("tbody",{parentName:"table"},(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"server namespace disconnect")),(0,o.kt)("td",{parentName:"tr",align:null},"The socket was forcefully disconnected with ",(0,o.kt)("a",{parentName:"td",href:"/docs/v3/server-api/#socket-disconnect-close"},"socket.disconnect()"))),(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"client namespace disconnect")),(0,o.kt)("td",{parentName:"tr",align:null},"The client has manually disconnected the socket using ",(0,o.kt)("a",{parentName:"td",href:"/docs/v3/client-api/#socket-disconnect"},"socket.disconnect()"))),(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"server shutting down")),(0,o.kt)("td",{parentName:"tr",align:null},"The server is, well, shutting down")),(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"ping timeout")),(0,o.kt)("td",{parentName:"tr",align:null},"The client did not send a PONG packet in the ",(0,o.kt)("inlineCode",{parentName:"td"},"pingTimeout")," delay")),(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"transport close")),(0,o.kt)("td",{parentName:"tr",align:null},"The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)")),(0,o.kt)("tr",{parentName:"tbody"},(0,o.kt)("td",{parentName:"tr",align:null},(0,o.kt)("inlineCode",{parentName:"td"},"transport error")),(0,o.kt)("td",{parentName:"tr",align:null},"The connection has encountered an error")))),(0,o.kt)("h3",{id:"disconnecting"},(0,o.kt)("inlineCode",{parentName:"h3"},"disconnecting")),(0,o.kt)("p",null,"This event is similar to ",(0,o.kt)("inlineCode",{parentName:"p"},"disconnect")," but is fired a bit earlier, when the ",(0,o.kt)("a",{parentName:"p",href:"/docs/v3/server-socket-instance/#Socket-rooms"},"Socket#rooms")," set is not empty yet"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'io.on("connection", (socket) => {\n  socket.on("disconnecting", (reason) => {\n    for (const room of socket.rooms) {\n      if (room !== socket.id) {\n        socket.to(room).emit("user has left", socket.id);\n      }\n    }\n  });\n});\n')),(0,o.kt)("p",null,"Note: those events, along with ",(0,o.kt)("inlineCode",{parentName:"p"},"connect"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"connect_error"),", ",(0,o.kt)("inlineCode",{parentName:"p"},"newListener")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"removeListener"),", are special events that shouldn't be used in your application:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-js"},'// BAD, will throw an error\nsocket.emit("disconnect");\n')),(0,o.kt)("h2",{id:"complete-api"},"Complete API"),(0,o.kt)("p",null,"The complete API exposed by the Socket instance can be found ",(0,o.kt)("a",{parentName:"p",href:"/docs/v3/server-api/#socket"},"here"),"."))}k.isMDXComponent=!0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.