1

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.

Elon Conner
  • 11
  • 1
  • 2
  • 1
    It runs on literally every request, for static files, for GET requests, for everything. Is that what you expect or not? What are you trying to achieve? – Danila Jul 10 '21 at 12:52
  • Thanks for the quick reply. Yes i know that middlewares at application-level runs at every request. but in my case i didn't send request but still got the messages in the console! – Elon Conner Jul 10 '21 at 12:58
  • So you have started the server, didn't open browser with `localhost:3000` and got several console.logs from your middleware? – Danila Jul 10 '21 at 13:02
  • it did open the browser with localhost:3000, everything goes well but i got several console logs – Elon Conner Jul 10 '21 at 23:27
  • 1
    As I said, your middleware runs for every request, if you opened the page then console.logs are already expected, your middleware was already invoked there. And for every static file etc. – Danila Jul 11 '21 at 09:59

0 Answers0