If you’re developing with Express in Node.js and encounter the error TypeError: Router.use() requires middleware function but got a Object
, it typically means that you have passed an object where Express was expecting a middleware function. This can occur for several reasons. Below are some common causes and their solutions.
Common Causes and Solutions
1. Incorrect Export
One of the most common reasons for this error is that you might have forgotten to export a middleware function from a module, or you may have exported an object instead.
const express = require('express');
const router = express.Router();
// An incorrect export which will cause this error
module.exports = {
router
};
To fix it, ensure you’re exporting the middleware function correctly:
// Correct way to export the router
module.exports = router;
2. Importing Issue
You might have imported the module incorrectly. Make sure to import the exported router function and not the entire module as an object.
// Incorret import can lead to the error
const routes = require('./routes');
// Instead, make sure to import it correctly
const router = require('./routes').router;
3. Middleware Registration
Ensure you are registering your middleware function correctly. Using an object or a non-function as a middleware will cause the error.
// Incorrect use of middleware
app.use('/', {});
// Correct use of middleware
app.use('/', router);
Sample Correct Code Example
The following is a complete example of creating a router as middleware and using it in an Express app without error:
// Correctly exporting the router in routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Hello World!');
});
module.exports = router;
// Importing the router in app.js and using it
const express = require('express');
const app = express();
const router = require('./routes');
app.use('/', router);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
By addressing these common issues, you should be able to eliminate the TypeError: Router.use() requires middleware function but got a Object
in Express, and your application should start functioning correctly.