Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts
file where I merge them into a single router before exporting. However, I am facing an issue where the imported file is returning undefined
.
Despite TypeScript correctly inferring the type of the imported file without any errors during development, the problem only arises when attempting to run the code:
TypeError:
app.use()
requires a middleware function
The snippet of code causing the error is as follows:
// 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
};
The code from the imported router
file is as follows:
// 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
};
Although I came across a related question mentioning that the issue of returning undefined
used to happen in Express version 3, I am using version 4.17.13
, ruling out that possibility. I am currently unsure of what might be causing this problem. I attempted to log the content of the router using console.log(router)
in the index.ts
file before it was imported by expressInstance.ts
, but the code didn't execute at all.