{"id":"e079cce1487169b8","repo":"expressjs/express","slug":"app-use-requires-a-middleware-function","errorCode":null,"errorMessage":"app.use() requires a middleware function","messagePattern":"app\\.use\\(\\) requires a middleware function","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/application.js","lineNumber":213,"sourceCode":"  // disambiguate app.use([fn])\n  if (typeof fn !== 'function') {\n    var arg = fn;\n\n    while (Array.isArray(arg) && arg.length !== 0) {\n      arg = arg[0];\n    }\n\n    // first arg is the path\n    if (typeof arg !== 'function') {\n      offset = 1;\n      path = fn;\n    }\n  }\n\n  var fns = flatten.call(slice.call(arguments, offset), Infinity);\n\n  if (fns.length === 0) {\n    throw new TypeError('app.use() requires a middleware function')\n  }\n\n  // get router\n  var router = this.router;\n\n  fns.forEach(function (fn) {\n    // non-express app\n    if (!fn || !fn.handle || !fn.set) {\n      return router.use(path, fn);\n    }\n\n    debug('.use app under %s', path);\n    fn.mountpath = path;\n    fn.parent = this;\n\n    // restore .app property on req and res\n    router.use(path, function mounted_app(req, res, next) {\n      var orig = req.app;","sourceCodeStart":195,"sourceCodeEnd":231,"githubUrl":"https://github.com/expressjs/express/blob/a3714473feb3d2908add734d340e7755fd85e0a3/lib/application.js#L195-L231","documentation":"app.use() flattens all arguments after the optional path (lib/application.js:210) and throws at line 212-213 if no middleware functions remain. Express requires at least one function per .use() call; registering nothing is treated as a bug at wiring time rather than being silently ignored.","triggerScenarios":"app.use('/api') with no function; app.use(undefined) or app.use('/x', undefined); app.use([]) or an array that flattens to empty; passing the result of a factory/require() that returned undefined instead of a middleware function.","commonSituations":"A middleware module whose export changed shape (e.g. forgetting to call the factory: app.use(cors) vs app.use(cors())) combined with a missing/undefined import; ESM/CJS interop where require(pkg).default was needed; conditional middleware like app.use(flag && mw) where flag is false; a typo'd import name yielding undefined. Frequently surfaces after upgrading a middleware package that moved to a default export.","solutions":["Check the value you pass: console.log(typeof mw) — if undefined, fix the import (often .default) or call the factory function.","For conditional registration, wrap in an if statement instead of passing a falsy expression: if (flag) app.use(mw).","Ensure arrays passed to app.use() actually contain functions and aren't empty."],"exampleFix":"// before\nconst logger = require('my-logger').logger; // undefined\napp.use(logger);\n// after\nconst { createLogger } = require('my-logger');\napp.use(createLogger());","handlingStrategy":"type-guard","validationCode":"if (typeof middleware !== 'function') {\n  throw new TypeError(`app.use() expected a function, got ${typeof middleware}`);\n}\napp.use(middleware);","typeGuard":"function isMiddleware(fn) {\n  return typeof fn === 'function';\n}","tryCatchPattern":"try {\n  app.use(require('./middleware/logger'));\n} catch (err) {\n  if (/requires a middleware function/.test(err.message)) {\n    // most often: module exported a factory or an object — check whether you need to CALL it, e.g. logger()\n  }\n  throw err;\n}","preventionTips":["Many middleware packages export factories — call them: app.use(cors()) not app.use(cors).","Check the module's export shape (default vs named export) when using ESM/CJS interop; require('x').default is a common miss.","Verify each element when spreading arrays of middleware into app.use.","Fail fast at startup: register all middleware synchronously so a bad value crashes on boot, not on first request."],"tags":["express","middleware","app-use","typeerror"],"analyzedSha":"a3714473feb3d2908add734d340e7755fd85e0a3","analyzedAt":"2026-07-31T18:55:36.968Z","schemaVersion":2}