Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

500
Views
Why is the Router() Express function returning undefined?

I'm using TypeScript and Express to create an API that follows the principles of Clean Architecture. I separated each route of my application in a folder, and then I import all of them into an index.ts file, merging each one inside an unique router and exporting the same. My problem is that the importation of this unique file is returning undefined.

I think that is isn't a problem of my code itself, since TypeScript can infer correctly the type of the imported file and doesn't report any error during development. The only error I get just happens when trying to run the code:

TypeError: app.use() requires a middleware function

This is the code snippet that causes the error:

// expressInstance.ts --> Imported by the "server.ts" file, where listening the server happens
import express from "express";
import cors from "cors";
import { router } from ".."; // File with all the routes

const expressInstance = express();

expressInstance.use(express.urlencoded({extended: false}));
expressInstance.use(express.json());
expressInstance.use(cors());

expressInstance.use(router); // Line where the error appears

export {
    expressInstance
};

And this is the code of the imported router file:

// index.ts
import { Router } from "express";
import { userRouter } from "./user.routes";
import { postRouter } from "./post.routes";

const router = Router();
router.use("/user", userRouter);
router.use("/post", postRouter);

export {
    router
};

I read in another question that the undefined return used to happen at Express version 3, but I use the 4.17.13 version, so I think this isn't the cause of the problem. In fact, I have no idea what could be. I tried to see the router content by using console.log(router) in the index.ts file (before being imported by expressInstance.ts), but it didn't work, because the code wasn't even executed.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try adding a path to your .use()

e.g:

expressInstance.use('/users', router);  // in the case you wanted the router to be for users  
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!