javascript – TypeError: app.use() requires middleware functions

javascript – TypeError: app.use() requires middleware functions

I had this problem when I left out

module.exports = router;

in my Routes.js.We need to export all the routes.

In my server.js, I had

var mainRoutes = require(./Routes.js)

So check your app/routes/api file to see if it has proper export.

Middleware is a function with access to the request object (req), the response object (res), and the next middleware in the application’s request-response cycle, commonly denoted by a variable named next.

Middleware can:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware, otherwise the request will be left hanging.

In api.js line number 10 is invalid


app.use must have a function with 3 params

// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {

if you want only few selected paths to use this middleware you can do something like this

// a middleware mounted on /user/:id; will be executed for any type of HTTP request to /user/:id
app.use(/user/:id, function (req, res, next) {
   console.log(Request Type:, req.method);

// a route and its handler function (middleware system) which handles GET requests to /user/:id
app.get(/user/:id, function (req, res, next) {

Take a look at the expressjs documents it is pretty good.

javascript – TypeError: app.use() requires middleware functions

You need to export your router in bottom of route file

like this module.exports = router;

and use in app.js file

const mainRoutes = require(./Routes.js)


Leave a Reply

Your email address will not be published.