<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: STEVE ADOLF</title>
    <description>The latest articles on DEV Community by STEVE ADOLF (@steve_adolf_c8df300913217).</description>
    <link>https://dev.to/steve_adolf_c8df300913217</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2002542%2Fa1e4d31c-2193-4695-aaa4-122ca7944970.jpg</url>
      <title>DEV Community: STEVE ADOLF</title>
      <link>https://dev.to/steve_adolf_c8df300913217</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/steve_adolf_c8df300913217"/>
    <language>en</language>
    <item>
      <title>I Really like Middleware in NodeJs/Express.</title>
      <dc:creator>STEVE ADOLF</dc:creator>
      <pubDate>Sat, 11 Jan 2025 07:06:34 +0000</pubDate>
      <link>https://dev.to/steve_adolf_c8df300913217/i-really-like-middleware-in-nodejsexpress-14hk</link>
      <guid>https://dev.to/steve_adolf_c8df300913217/i-really-like-middleware-in-nodejsexpress-14hk</guid>
      <description>&lt;h2&gt;
  
  
  Middleware to attach a user to the request object because nodejs/express does not do that for you out of the box.
&lt;/h2&gt;

&lt;p&gt;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 &lt;code&gt;user.role === &amp;lt;some_role&amp;gt; ? do_something: do_this&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Here is how i might implement it.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * @param {Request} req
 * @param {Response} res
 */
const userIsAuthenticatedMiddleware = async (req, res, next) =&amp;gt; {
  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) =&amp;gt; {
      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" });
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>middleware</category>
      <category>node</category>
      <category>express</category>
    </item>
  </channel>
</rss>
