0

How to use a middleware in NodeJS if you are using controllers? How to use middleware only for some specific request?

app.js

const express = require("express");
const { User } = require("./models/user");
const morgan = require("morgan");
const dotenv = require("dotenv").config();
const helmet = require("helmet");
const app = express();
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");

app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use("/api/user", userRoute);
app.use("/api/auth", authRoute);

app.listen({ port: 7999 }, () => {
  console.log("Up and running");
});

project/controllers/auth.js

    const verifyToken = async (req, res, next) => {
  const token = req.header("auth-token");
  if (!token) return res.status(403).send("NOT ALLOWED");
  try {
    const verified = jwt.verify(token, process.env.TOKEN_SECRET);
    req.user = verified;
    next();
  } catch (error) {
    return res.status(500).json("INVALID TOKEN");
  }
};
n9p4
  • 304
  • 8
  • 34
  • 1
    Just add it to that specific route mapping: `app.use("/my/route", middleware, moreMiddleware, routeHandler)`. See e.g. https://expressjs.com/en/guide/using-middleware.html#middleware.router. – jonrsharpe Aug 18 '21 at 13:37
  • Why are people insisting on separating routes (controllers) from controllers (controller body). What you people are calling "routes" are traditionally called **controllers** in other MVC frameworks. If you've ever used other web MVC frameworks in other languages controllers are **ALWAYS** defined as `url_path -> function`. So your route files are **ACTUALLY** your controllers. You got into this mess because you are separating the code for the controllers from your controllers. Please stop using this anti-pattern – slebetman Aug 18 '21 at 16:32

0 Answers0