TypeError: app.use() requires a middleware function but got a undefined

Express.js·Sep 12, 2026·beginner·
Quick answer

You're passing `undefined` to `app.use()` — almost always because the thing you imported doesn't actually export what you think it does. Check for a missing `export default`, a mismatched named vs. default import, or a typo in the import path.

What causes this error

Express validates that whatever you pass to app.use() is actually a function. If your import resolves to undefined — the module doesn't export what you expected — Express throws this specific, fairly clear error rather than failing silently later.

The Fix

// Wrong — forgot to export default from the router file
// routes/index.ts:
// const router = Router();
// (missing: export default router;)

import routes from './routes'; // undefined!
app.use('/api', routes); // throws

// Fix — make sure the file actually exports it
// routes/index.ts:
const router = Router();
export default router;

Common causes / variations

  • Forgetting export default on a router file
  • Mixing up import routes from './routes' (default) with import { routes } from './routes' (named) when only one actually matches how it's exported
  • A typo in the import path resolving to the wrong file, or a file that doesn't exist and silently imports as undefined depending on your bundler config

Related errors

See also: Cannot set headers after they are sent, CORS error.

Was this fix helpful?

Comments

Loading comments...