PageSourceSearch

https://socket.io/assets/js/ae42c98e.e429d3b0.js

js socket.io collected 2026-09-24 07:24:18 UTC 10,599 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunksample_website=self.webpackChunksample_website||[]).push([[1936],{3905:(e,n,t)=>{t.d(n,{Zo:()=>d,kt:()=>k});var r=t(7294);function a(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function i(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter((function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable}))),t.push.apply(t,r)}return t}function s(e){for(var n=1;n<arguments.length;n++){var t=null!=arguments[n]?arguments[n]:{};n%2?i(Object(t),!0).forEach((function(n){a(e,n,t[n])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach((function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}))}return e}function o(e,n){if(null==e)return{};var t,r,a=function(e,n){if(null==e)return{};var t,r,a={},i=Object.keys(e);for(r=0;r<i.length;r++)t=i[r],n.indexOf(t)>=0||(a[t]=e[t]);return a}(e,n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)t=i[r],n.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(a[t]=e[t])}return a}var l=r.createContext({}),c=function(e){var n=r.useContext(l),t=n;return e&&(t="function"==typeof e?e(n):s(s({},n),e)),t},d=function(e){var n=c(e.components);return r.createElement(l.Provider,{value:n},e.children)},p="mdxType",u={inlineCode:"code",wrapper:function(e){var n=e.children;return r.createElement(r.Fragment,{},n)}},m=r.forwardRef((function(e,n){var t=e.components,a=e.mdxType,i=e.originalType,l=e.parentName,d=o(e,["components","mdxType","originalType","parentName"]),p=c(t),m=a,k=p["".concat(l,".").concat(m)]||p[m]||u[m]||i;return t?r.createElement(k,s(s({ref:n},d),{},{components:t})):r.createElement(k,s({ref:n},d))}));function k(e,n){var t=arguments,a=n&&n.mdxType;if("string"==typeof e||a){var i=t.length,s=new Array(i);s[0]=m;var o={};for(var l in n)hasOwnProperty.call(n,l)&&(o[l]=n[l]);o.originalType=e,o[p]="string"==typeof e?e:a,s[1]=o;for(var c=2;c<i;c++)s[c]=t[c];return r.createElement.apply(null,s)}return r.createElement.apply(null,t)}m.displayName="MDXCreateElement"},9477:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>s,default:()=>u,frontMatter:()=>i,metadata:()=>o,toc:()=>c});var r=t(3117),a=(t(7294),t(3905));const i={title:"Middlewares",sidebar_position:5,slug:"/middlewares/"},s=void 0,o={unversionedId:"categories/Server/middlewares",id:"categories/Server/middlewares",title:"Middlewares",description:"A middleware function is a function that gets executed for every incoming connection.",source:"@site/docs/categories/02-Server/middlewares.md",sourceDirName:"categories/02-Server",slug:"/middlewares/",permalink:"/docs/v4/middlewares/",draft:!1,editUrl:"https://github.com/socketio/socket.io-website/edit/main/docs/categories/02-Server/middlewares.md",tags:[],version:"current",lastUpdatedAt:1784117104,formattedLastUpdatedAt:"Jul 15, 2026",sidebarPosition:5,frontMatter:{title:"Middlewares",sidebar_position:5,slug:"/middlewares/"},sidebar:"sidebar",previous:{title:"The Socket instance",permalink:"/docs/v4/server-socket-instance/"},next:{title:"Behind a reverse proxy",permalink:"/docs/v4/reverse-proxy/"}},l={},c=[{value:"Registering a middleware",id:"registering-a-middleware",level:2},{value:"Sending credentials",id:"sending-credentials",level:2},{value:"Handling middleware error",id:"handling-middleware-error",level:2},{value:"Compatibility with Express middleware",id:"compatibility-with-express-middleware",level:2}],d={toc:c},p="wrapper";
1function u(e){let{components:n,...t}=e;return(0,a.kt)(p,(0,r.Z)({},d,t,{components:n,mdxType:"MDXLayout"}),(0,a.kt)("p",null,"A middleware function is a function that gets executed for every incoming connection."),(0,a.kt)("p",null,"Middleware functions can be useful for:"),(0,a.kt)("ul",null,(0,a.kt)("li",{parentName:"ul"},"logging"),(0,a.kt)("li",{parentName:"ul"},"authentication / authorization"),(0,a.kt)("li",{parentName:"ul"},"rate limiting")),(0,a.kt)("p",null,"Note: this function will be executed only once per connection (even if the connection consists in multiple HTTP requests)."),(0,a.kt)("admonition",{type:"info"},(0,a.kt)("p",{parentName:"admonition"},"If you are looking for Express middlewares, please check ",(0,a.kt)("a",{parentName:"p",href:"#compatibility-with-express-middleware"},"this section"),".")),(0,a.kt)("h2",{id:"registering-a-middleware"},"Registering a middleware"),(0,a.kt)("p",null,"A middleware function has access to the ",(0,a.kt)("a",{parentName:"p",href:"/docs/v4/server-socket-instance/"},"Socket instance")," and to the next registered middleware function."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'io.use((socket, next) => {\n  if (isValid(socket.request)) {\n    next();\n  } else {\n    next(new Error("invalid"));\n  }\n});\n')),(0,a.kt)("p",null,"You can register several middleware functions, and they will be executed sequentially:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'io.use((socket, next) => {\n  next();\n});\n\nio.use((socket, next) => {\n  next(new Error("thou shall not pass"));\n});\n\nio.use((socket, next) => {\n  // not executed, since the previous middleware has returned an error\n  next();\n});\n')),(0,a.kt)("p",null,"Please make sure to call ",(0,a.kt)("inlineCode",{parentName:"p"},"next()")," in any case. Otherwise, the connection will be left hanging until it is closed after a given timeout."),(0,a.kt)("p",null,(0,a.kt)("strong",{parentName:"p"},"Important note"),": the Socket instance is not actually connected when the middleware gets executed, which means that no ",(0,a.kt)("inlineCode",{parentName:"p"},"disconnect")," event will be emitted if the connection eventually fails."),(0,a.kt)("p",null,"For example, if the client manually closes the connection:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'// server-side\nio.use((socket, next) => {\n  setTimeout(() => {\n    // next is called after the client disconnection\n    next();\n  }, 1000);\n\n  socket.on("disconnect", () => {\n    // not triggered\n  });\n});\n\nio.on("connection", (socket) => {\n  // not triggered\n});\n\n// client-side\nconst socket = io();\nsetTimeout(() => {\n  socket.disconnect();\n}, 500);\n')),(0,a.kt)("h2",{id:"sending-credentials"},"Sending credentials"),(0,a.kt)("p",null,"The client can send credentials with the ",(0,a.kt)("inlineCode",{parentName:"p"},"auth")," option:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'// plain object\nconst socket = io({\n  auth: {\n    token: "abc"\n  }\n});\n\n// or with a function\nconst socket = io({\n  auth: (cb) => {\n    cb({\n      token: "abc"\n    });\n  }\n});\n')),(0,a.kt)("p",null,"Those credentials can be accessed in the ",(0,a.kt)("a",{parentName:"p",href:"/docs/v4/server-socket-instance/#sockethandshake"},"handshake")," object on the server-side:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},"io.use((socket, next) => {\n  const token = socket.handshake.auth.token;\n  // ...\n});\n")),(0,a.kt)("h2",{id:"handling-middleware-error"},"Handling middleware error"),(0,a.kt)("p",null,"If the ",(0,a.kt)("inlineCode",{parentName:"p"},"next")," method is called with an Error object, the connection will be refused and the client will receive an ",(0,a.kt)("inlineCode",{parentName:"p"},"connect_error")," event."),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'// client-side\nsocket.on("connect_error", (err) => {\n  console.log(err.message); // prints the message associated with the error\n});\n')),(0,a.kt)("p",null,"You can attach additional details to the Error object:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'// server-side\nio.use((socket, next) => {\n  const err = new Error("not authorized");\n  err.data = { content: "Please retry later" }; // additional details\n  next(err);\n});\n\n// client-side\nsocket.on("connect_error", (err) => {\n  console.log(err instanceof Error); // true\n  console.log(err.message); // not authorized\n  console.log(err.data); // { content: "Please retry later" }\n});\n')),(0,a.kt)("h2",{id:"compatibility-with-express-middleware"},"Compatibility with Express middleware"),(0,a.kt)("p",null,"Since they are not bound to a usual HTTP request/response cycle, Socket.IO middlewares are not really compatible with ",(0,a.kt)("a",{parentName:"p",href:"https://expressjs.com/en/guide/using-middleware.html"},"Express middlewares"),"."),(0,a.kt)("p",null,"That being said, starting with version ",(0,a.kt)("inlineCode",{parentName:"p"},"4.6.0"),", Express middlewares are now supported by the underlying engine:"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},"io.engine.use((req, res, next) =>
1 {\n  // do something\n\n  next();\n});\n")),(0,a.kt)("p",null,"The middlewares will be called for each incoming HTTP requests, including upgrade requests."),(0,a.kt)("p",null,"Example with ",(0,a.kt)("a",{parentName:"p",href:"https://www.npmjs.com/package/express-session"},(0,a.kt)("inlineCode",{parentName:"a"},"express-session")),":"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'import session from "express-session";\n\nio.engine.use(session({\n  secret: "keyboard cat",\n  resave: false,\n  saveUninitialized: true,\n  cookie: { secure: true }\n}));\n')),(0,a.kt)("p",null,"Example with ",(0,a.kt)("a",{parentName:"p",href:"https://www.npmjs.com/package/helmet"},(0,a.kt)("inlineCode",{parentName:"a"},"helmet")),":"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'import helmet from "helmet";\n\nio.engine.use(helmet());\n')),(0,a.kt)("p",null,"If the middleware must be only applied to the handshake request (and not for each HTTP request), you can check for the existence of the ",(0,a.kt)("inlineCode",{parentName:"p"},"sid")," query parameter."),(0,a.kt)("p",null,"Example with ",(0,a.kt)("a",{parentName:"p",href:"https://www.npmjs.com/package/passport-jwt"},(0,a.kt)("inlineCode",{parentName:"a"},"passport-jwt")),":"),(0,a.kt)("pre",null,(0,a.kt)("code",{parentName:"pre",className:"language-js"},'io.engine.use((req, res, next) => {\n  const isHandshake = req._query.sid === undefined;\n  if (isHandshake) {\n    passport.authenticate("jwt", { session: false })(req, res, next);\n  } else {\n    next();\n  }\n});\n')))}u.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.