I'm trying to create a custom server in NextJS with ExpressJS. First i tried to create routes, it goes so well. Next i tried to create a middleware and set it as application-level middleware, here's the middleware:
const mymiddleware = (req, res, next) => {
console.log("this is a middleware");
next();
};
module.exports = mymiddleware;
Next in the server.js file i called the middleware created:
const express = require("express");
const next = require("next");
const user_routes = require("./routes/users");
const mymiddleware = require("./middlewares/mymiddleware");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(express.json());
server.use(mymiddleware);
server.use("/users", user_routes);
server.get("/ok", (req, res) => {
res.json({ msg: "Hello World!! " });
});
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
The problem here is the middleware keeps running even when i don't call any api, it keeps show the message "this is a middleware" in the console.