PageSourceSearch

https://socket.io/assets/js/815365cb.c1bbc4ad.js

js socket.io collected 2026-09-24 07:23:47 UTC 15,778 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunksample_website=self.webpackChunksample_website||[]).push([[762],{3905:(e,t,a)=>{a.d(t,{Zo:()=>c,kt:()=>u});var n=a(7294);function r(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function s(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function o(e){for(var t=1;t<arguments.length;t++){var a=null!=arguments[t]?arguments[t]:{};t%2?s(Object(a),!0).forEach((function(t){r(e,t,a[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):s(Object(a)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(a,t))}))}return e}function p(e,t){if(null==e)return{};var a,n,r=function(e,t){if(null==e)return{};var a,n,r={},s=Object.keys(e);for(n=0;n<s.length;n++)a=s[n],t.indexOf(a)>=0||(r[a]=e[a]);return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)a=s[n],t.indexOf(a)>=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}var i=n.createContext({}),l=function(e){var t=n.useContext(i),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},c=function(e){var t=l(e.components);return n.createElement(i.Provider,{value:t},e.children)},m="mdxType",k={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},d=n.forwardRef((function(e,t){var a=e.components,r=e.mdxType,s=e.originalType,i=e.parentName,c=p(e,["components","mdxType","originalType","parentName"]),m=l(a),d=r,u=m["".concat(i,".").concat(d)]||m[d]||k[d]||s;return a?n.createElement(u,o(o({ref:t},c),{},{components:a})):n.createElement(u,o({ref:t},c))}));function u(e,t){var a=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var s=a.length,o=new Array(s);o[0]=d;var p={};for(var i in t)hasOwnProperty.call(t,i)&&(p[i]=t[i]);p.originalType=e,p[m]="string"==typeof e?e:r,o[1]=p;for(var l=2;l<s;l++)o[l]=a[l];return n.createElement.apply(null,o)}return n.createElement.apply(null,a)}d.displayName="MDXCreateElement"},3861:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>i,contentTitle:()=>o,default:()=>k,frontMatter:()=>s,metadata:()=>p,toc:()=>l});var n=a(3117),r=(a(7294),a(3905));const s={title:"Custom parser",sidebar_position:2,slug:"/custom-parser/"},o=void 0,p={unversionedId:"categories/Advanced/custom-parser",id:"categories/Advanced/custom-parser",title:"Custom parser",description:"Since Socket.IO v2.0.0, it is now possible to provide your own parser, in order to control the marshalling / unmarshalling of packets.",source:"@site/docs/categories/06-Advanced/custom-parser.md",sourceDirName:"categories/06-Advanced",slug:"/custom-parser/",permalink:"/docs/v4/custom-parser/",draft:!1,editUrl:"https://github.com/socketio/socket.io-website/edit/main/docs/categories/06-Advanced/custom-parser.md",tags:[],version:"current",lastUpdatedAt:1784117104,formattedLastUpdatedAt:"Jul 15, 2026",sidebarPosition:2,frontMatter:{title:"Custom parser",sidebar_position:2,slug:"/custom-parser/"},sidebar:"sidebar",previous:{title:"Namespaces",permalink:"/docs/v4/namespaces/"},next:{title:"Admin UI",permalink:"/docs/v4/admin-ui/"}},i={},l=[{value:"Available parsers",id:"available-parsers",level:2},{value:"Implementing your own parser",id:"implementing-your-own-parser",level:2},{value:"The default parser",id:"the-default-parser",level:2},{value:"The msgpack parser",id:"the-msgpack-parser",level:2}],c={toc:l},m="wrapper";function k(e){let{components:t,...a}=e;return(0,r.kt)(m,(0,n.Z)({},c,a,{components:t,mdxType:"MDXLayout"}),(0,r.kt)("p",null,"Since Socket.IO v2.0.0, it is now possible to provide your own parser, in order to control the marshalling / unmarshalling of packets."),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Server")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'import { Server } from "socket.io";\n\nconst io = new Server({\n  parser: myParser\n});\n')),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Client")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'import { io } from "socket.io-client";\n\nconst socket = io({\n  parser: myParser\n});\n')),(0,r.kt)("h2",{id:"available-parsers"},"Available parsers"),(0,r.kt)("p",null,"Besides ",(0,r.kt)("a",{parentName:"p",href:"#the-default-parser"},"the default parser"),", here is the list of available parsers:"),(0,r.kt)("table",null,(0,r.kt)("thead",{parentName:"table"},(0,r.kt)("tr",{parentName:"thead"},(0,r.kt)("th",{parentName:"tr",align:null},"Package"),(0,r.kt)("th",{parentName:"tr",align:null},"Description"))),(0,r.kt)("tbody",{parentName:"table"},(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/socket.io-circular-parser"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io-circular-parser"))),(0,r.kt)("td",{parentName:"tr",align:null},"Similar to the default parser, but handles circular references.")),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/socket.io-msgpack-parser"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io-msgpack-parser"))),(0,r.kt)("td",{parentName:"tr",align:null},"Uses ",(0,r.kt)("a",{parentName:"td",href:"https://msgpack.org/"},"MessagePack")," to encode the packets (based on the ",(0,r.kt)("a",{parentName:"td",href:"https://github.com/darrachequesne/notepack"},(0,r.kt)("inlineCode",{parentName:"a"},"notepack.io"))," package).")),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/@skgdev/socket.io-msgpack-javascript"},(0,r.kt)("inlineCode",{parentName:"a"},"@skgdev/socket.io-msgpack-javascript"))),(0,r.kt)("td",{parentName:"tr",align:null},"Uses ",(0,r.kt)("a",{parentName:"td",href:"https://msgpack.org/"},"MessagePack")," to encode the packets (based on the ",(0,r.kt)("a",{parentName:"td",href:"https://github.com/msgpack/msgpack-javascript"},(0,r.kt)("inlineCode",{parentName:"a"},"@msgpack/msgpack"))," package).")),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/socket.io-json-parser"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io-json-parser"))),(0,r.kt)("td",{parentName:"tr",align:null},"Uses ",(0,r.kt)("inlineCode",{parentName:"td"},"JSON.stringify()")," and ",(0,r.kt)("inlineCode",{parentName:"td"},"JSON.parse()")," to encode the packets.")),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/socket.io-cbor-x-parser"},(0,r.kt)("inlineCode",{parentName:"a"},"socket.io-cbor-x-parser"))),(0,r.kt)("td",{parentName:"tr",align:null},"Uses ",(0,r.kt)("a",{parentName:"td",href:"https://github.com/kriszyp/cbor-x"},"cbor-x")," to encode the packets.")),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://www.npmjs.com/package/@socket.io/devalue-parser"},(0,r.kt)("inlineCode",{parentName:"a"},"@socket.io/devalue-parser"))),(0,r.kt)("td",{parentName:"tr",align:null},"Uses ",(0,r.kt)("a",{parentName:"td",href:"https://github.com/Rich-Harris/devalue"},"devalue")," to encode the packets.")))),(0,r.kt)("h2",{id:"implementing-your-own-parser"},"Implementing your own parser"),(0,r.kt)("p",null,"Here is a basic example with a parser that uses the ",(0,r.kt)("inlineCode",{parentName:"p"},"JSON.stringify()")," and ",(0,r.kt)("inlineCode",{parentName:"p"},"JSON.parse()")," methods:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'import { Emitter } from "@socket.io/component-emitter"; // polyfill of Node.js EventEmitter in the browser\n\nclass Encoder {\n  /**\n   * Encode a packet into a list of strings/buffers\n   */\n  encode(packet) {\n    return [JSON.stringify(packet)];\n  }\n}\n\nfunction isObject(value) {\n  return Object.prototype.toString.call(value) === "[object Object]";\n}
1\n\nclass Decoder extends Emitter {\n  /**\n   * Receive a chunk (string or buffer) and optionally emit a "decoded" event with the reconstructed packet\n   */\n  add(chunk) {\n    const packet = JSON.parse(chunk);\n    if (this.isPacketValid(packet)) {\n      this.emit("decoded", packet);\n    } else {\n      throw new Error("invalid format");\n    }\n  }\n  isPacketValid({ type, data, nsp, id }) {\n    const isNamespaceValid = typeof nsp === "string";\n    const isAckIdValid = id === undefined || Number.isInteger(id);\n    if (!isNamespaceValid || !isAckIdValid) {\n      return false;\n    }\n    switch (type) {\n      case 0: // CONNECT\n        return data === undefined || isObject(data);\n      case 1: // DISCONNECT\n        return data === undefined;\n      case 2: // EVENT\n        return Array.isArray(data) && typeof data[0] === "string";\n      case 3: // ACK\n        return Array.isArray(data);\n      case 4: // CONNECT_ERROR\n        return isObject(data);\n      default:\n        return false;\n    }\n  }\n  /**\n   * Clean up internal buffers\n   */\n  destroy() {}\n}\n\nexport const parser = { Encoder, Decoder };\n')),(0,r.kt)("h2",{id:"the-default-parser"},"The default parser"),(0,r.kt)("p",null,"The source code of the default parser (the ",(0,r.kt)("inlineCode",{parentName:"p"},"socket.io-parser")," package) can be found here: ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/socketio/socket.io-parser"},"https://github.com/socketio/socket.io-parser")),(0,r.kt)("p",null,"Example of output:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"basic emit")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'socket.emit("test", 42);\n')),(0,r.kt)("p",null,"will be encoded as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'2["test",42]\n||\n|\u2514\u2500 JSON-encoded payload\n\u2514\u2500 packet type (2 => EVENT)\n')),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"emit with binary, acknowledgement and custom namespace")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'socket.emit("test", Uint8Array.from([42]), () => {\n  console.log("ack received");\n});\n')),(0,r.kt)("p",null,"will be encoded as:"),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre"},'51-/admin,13["test",{"_placeholder":true,"num":0}]\n||||     || \u2514\u2500 JSON-encoded payload with placeholders for binary attachments\n||||     |\u2514\u2500 acknowledgement id\n||||     \u2514\u2500 separator\n|||\u2514\u2500 namespace (not included when it\'s the main namespace)\n||\u2514\u2500 separator\n|\u2514\u2500 number of binary attachments\n\u2514\u2500 packet type (5 => BINARY EVENT)\n\nand an additional attachment (the extracted Uint8Array)\n')),(0,r.kt)("p",null,"Pros:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"the binary attachments is then base64-encoded, so this parser is compatible with browsers that ",(0,r.kt)("a",{parentName:"li",href:"https://caniuse.com/mdn-javascript_builtins_arraybuffer"},"do not support Arraybuffers"),", like IE9")),(0,r.kt)("p",null,"Cons:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"packets with binary content are sent as two distinct WebSocket frames (if the WebSocket connection is established)")),(0,r.kt)("h2",{id:"the-msgpack-parser"},"The msgpack parser"),(0,r.kt)("p",null,"This parser uses the ",(0,r.kt)("a",{parentName:"p",href:"https://msgpack.org/"},"MessagePack")," serialization format."),(0,r.kt)("p",null,"The source code of this parser can be found here: ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/socketio/socket.io-msgpack-parser"},"https://github.com/socketio/socket.io-msgpack-parser")),(0,r.kt)("p",null,"Sample usage:"),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Server")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'import { Server } from "socket.io";\nimport customParser from "socket.io-msgpack-parser";\n\nconst io = new Server({\n  parser: customParser\n});\n')),(0,r.kt)("p",null,(0,r.kt)("em",{parentName:"p"},"Client (Node.js)")),(0,r.kt)("pre",null,(0,r.kt)("code",{parentName:"pre",className:"language-js"},'import { io } from "socket.io-client";\nimport customParser from "socket.io-msgpack-parser";\n\nconst socket = io("https://example.com", {\n  parser: customParser\n});\n')),(0,r.kt)("p",null,"In the browser, there is now an official bundle which includes this parser:"),(0,r.kt)("table",null,(0,r.kt)("thead",{parentName:"table"},(0,r.kt)("tr",{parentName:"thead"},(0,r.kt)("th",{parentName:"tr",align:null},"CDN"),(0,r.kt)("th",{parentName:"tr",align:null},"URL"))),(0,r.kt)("tbody",{parentName:"table"},(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},"Socket.IO CDN"),(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://cdn.socket.io/4.8.3/socket.io.msgpack.min.js"},"https://cdn.socket.io/4.8.3/socket.io.msgpack.min.js"))),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},"cdnjs"),(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.3/socket.io.msgpack.min.js"},"https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.3/socket.io.msgpack.min.js"))),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},"jsDelivr"),(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://cdn.jsdelivr.net/npm/[email protected]/dist/socket.io.msgpack.min.js"},"https://cdn.jsdelivr.net/npm/[email protected]/dist/socket.io.msgpack.min.js"))),(0,r.kt)("tr",{parentName:"tbody"},(0,r.kt)("td",{parentName:"tr",align:null},"unpkg"),(0,r.kt)("td",{parentName:"tr",align:null},(0,r.kt)("a",{parentName:"td",href:"https://unpkg.com/[email protected]/dist/socket.io.msgpack.min.js"},"https://unpkg.com/[email protected]/dist/socket.io.msgpack.min.js"))))),(0,r.kt)("p",null,"In that case, you don't need to specify the ",(0,r.kt)("inlineCode",{parentName:"p"},"parser")," option."),(0,r.kt)("p",null,"Pros:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"packets with binary content are sent as one single WebSocket frame (if the WebSocket connection is established)"),(0,r.kt)("li",{parentName:"ul"},"may result in smaller payloads (especially when using a lot of numbers)")),(0,r.kt)("p",null,"Cons:"),(0,r.kt)("ul",null,(0,r.kt)("li",{parentName:"ul"},"incompatible with browsers that ",(0,r.kt)("a",{parentName:"li",href:"https://caniuse.com/mdn-javascript_builtins_arraybuffer"},"do not support Arraybuffers"),", like IE9"),(0,r.kt)("li",{parentName:"ul"},"harder to debug in the Network tab of the browser")),(0,r.kt)("admonition",{type:"info"},(0,r.kt)("p",{parentName:"admonition"},"Please note that ",(0,r.kt)("inlineCode",{parentName:"p"},"socket.io-msgpack-parser")," relies on the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/darrachequesne/notepack"},(0,r.kt)("inlineCode",{parentName:"a"},"notepack.io"))," MessagePack implementation. This implementation mainly focu
1ses on performance and minimal bundle size, and thus does not support features like extension types. For a parser based on the ",(0,r.kt)("a",{parentName:"p",href:"https://github.com/msgpack/msgpack-javascript"},"official JavaScript implementation"),", please check ",(0,r.kt)("a",{parentName:"p",href:"https://www.npmjs.com/package/@skgdev/socket.io-msgpack-javascript"},"this package"),".")))}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.