DEV Community

STEVE ADOLF
STEVE ADOLF

Posted on

I Really like Middleware in NodeJs/Express.

Middleware to attach a user to the request object because nodejs/express does not do that for you out of the box.

Say i have a controller that need to check whether a user is of certain role in order to let them access a certain resource. Then this middleware will be helpful as it makes a user available to this function. Then i can do something like user.role === <some_role> ? do_something: do_this

Here is how i might implement it.

/**
 * @param {Request} req
 * @param {Response} res
 */
const userIsAuthenticatedMiddleware = async (req, res, next) => {
  const token = req.headers["authorization"]?.split(" ")[1];
  if (!token) return res.status(401).json({ message: "Access denied" });

  try {
    jwt.verify(token, process.env.JWT_SECRET, (error, user) => {
      if (error) return res.status(401).json({ message: "Wrong token" });
      req.user = user;
      next();
    });
  } catch (error) {
    return res.status(500).json({ message: "Internal Server Error" });
  }
};

Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
joni_singh_e68a2d94d1aa98 profile image
Joni Singh • Edited

Enhanced User Management: Middleware allows the backend to authenticate users and control access to premium or admin-level features in apps like Instander APK.
Premium Features: Ensure that only users with the "premium" role can access advanced features such as high-quality media downloads.
Security: Middleware acts as a checkpoint to verify the legitimacy of users and their roles before processing sensitive requests.
This approach provides a scalable way to handle user roles and permissions for an app like Instander APK ensuring a secure and user-friendly experience.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay