{"id":3712,"date":"2026-11-04T00:11:13","date_gmt":"2026-11-03T16:11:13","guid":{"rendered":"http:\/\/www.simorghict.com\/blog\/?p=3712"},"modified":"2026-11-04T00:11:13","modified_gmt":"2026-11-03T16:11:13","slug":"how-to-protect-routes-with-express-and-jwt-470f-11d1f5","status":"publish","type":"post","link":"http:\/\/www.simorghict.com\/blog\/2026\/11\/04\/how-to-protect-routes-with-express-and-jwt-470f-11d1f5\/","title":{"rendered":"How to protect routes with Express and JWT?"},"content":{"rendered":"<p>Hey folks, if you\u2019ve been running an Express app and worrying about who\u2019s hitting your private endpoints\u2014like your users\u2019 dashboards, payment processing stuff, or internal admin tools\u2014you\u2019re not alone. I\u2019ve been in your shoes. For years, I\u2019ve helped small to mid-sized dev teams fix the exact same problem: their Express routes were wide open, so any random person could snoop or mess with sensitive data. That\u2019s where JWT (JSON Web Tokens) comes in, and today I\u2019m breaking down how we do it at our Express shop\u2014no fancy jargon, no overcomplicated steps, just real stuff that works for day-to-day builds. <a href=\"https:\/\/www.fsshijielogistics.com\/express\/\">Express<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.fsshijielogistics.com\/uploads\/44940\/small\/railway-railroad-trucking-to-mexico1e4b5.jpg\"><\/p>\n<p>First, let\u2019s get one thing straight: JWT isn\u2019t magic. It\u2019s just a little token your app gives a user when they log in (or sign up, or even just authenticate a request) that they send back every time they hit a protected route. Think of it like a digital keycard\u2014your app issues it, and only people with the right key can get into the rooms (routes) that matter. And since I\u2019m an Express specialist, I\u2019m gonna skip the \u201cwhat is JWT?\u201d Wikipedia-level explanation and jump straight into how to plug this into your Express app without breaking anything.<\/p>\n<p>Let\u2019s start with the basics you\u2019ll need first. I\u2019m assuming you already have an Express app set up, right? If not, that\u2019s on you for starting from scratch, but I\u2019ll keep this focused on the actual route protection part. First, you\u2019ll need two npm packages: jsonwebtoken for generating and verifying tokens, and bcrypt (or whatever hashing library you use) to hash passwords before storing \u2019em in your database\u2014never store plain text passwords, that\u2019s basic security 101. Oh, and express, obviously, since we\u2019re talkin\u2019 Express here.<\/p>\n<p>Wait, let\u2019s not skip the login step\u2014you can\u2019t protect routes if you don\u2019t have tokens to give out. Let\u2019s say you have a POST \/login route. When a user sends their email and password, you check if the password matches the hashed one in your DB. If it does, you generate a JWT with jsonwebtoken\u2019s sign() method. What goes into the token? Just the necessary stuff\u2014like the user\u2019s ID, maybe their role (admin vs regular user) if you need role-based access later. Never put sensitive data (credit card info, SSNs) in a JWT, \u2019cause those are easy to decode even if you can\u2019t tamper with \u2019em. Here\u2019s a quick example of that:<br \/>\nconst jwt = require(&#8216;jsonwebtoken&#8217;);<br \/>\nconst bcrypt = require(&#8216;bcrypt&#8217;);<\/p>\n<p>app.post(&#8216;\/login&#8217;, async (req, res) =&gt; {<br \/>\nconst { email, password } = req.body;<br \/>\n\/\/ Grab user from DB (pseudo-code here, just to make it real)<br \/>\nconst user = await User.findOne({ email });<br \/>\nif (!user) return res.status(401).json({ msg: &#8216;Invalid credentials&#8217; });<\/p>\n<p>\/\/ Check password hash<br \/>\nconst validPass = await bcrypt.compare(password, user.passwordHash);<br \/>\nif (!validPass) return res.status(401).json({ msg: &#8216;Invalid credentials&#8217; });<\/p>\n<p>\/\/ Generate token: sign with a secret (keep this in env vars, never hardcode!)<br \/>\nconst token = jwt.sign(<br \/>\n{ userId: user._id, role: user.role },<br \/>\nprocess.env.JWT_SECRET,<br \/>\n{ expiresIn: &#8216;1h&#8217; } \/\/ Super important\u2014tokens shouldn\u2019t live forever!<br \/>\n);<\/p>\n<p>res.json({ token });<br \/>\n});<\/p>\n<p>That\u2019s the login flow. Now, the key part: how do you protect a route so only people with a valid token can hit it? You make a middleware function. Middleware in Express is just a function that runs before your route handler\u2014perfect for checking if the token is there and valid. That way, you don\u2019t have to copy-paste the same token check into every private route.<\/p>\n<p>Here\u2019s the middleware we use every day, refined over a million test runs with client apps:<br \/>\nconst jwt = require(&#8216;jsonwebtoken&#8217;);<\/p>\n<p>\/\/ Auth middleware to protect routes<br \/>\nconst protect = (req, res, next) =&gt; {<br \/>\n\/\/ Get token from the Authorization header\u2014format is usually &quot;Bearer [token]&quot;<br \/>\nconst authHeader = req.headers.authorization;<br \/>\nlet token;<\/p>\n<p>\/\/ Check if the header exists and starts with Bearer<br \/>\nif (authHeader &amp;&amp; authHeader.startsWith(&#8216;Bearer&#8217;)) {<br \/>\n\/\/ Split the header to get just the token<br \/>\ntoken = authHeader.split(&#8216; &#8216;)[1];<br \/>\n}<\/p>\n<p>\/\/ If no token, no access<br \/>\nif (!token) {<br \/>\nreturn res.status(401).json({ msg: &#8216;No token, authorization denied&#8217; });<br \/>\n}<\/p>\n<p>\/\/ Verify the token\u2014if it\u2019s tampered with or expired, this throws an error<br \/>\ntry {<br \/>\nconst decoded = jwt.verify(token, process.env.JWT_SECRET);<br \/>\n\/\/ Attach the user\u2019s data to the request so we can use it in the route<br \/>\nreq.user = decoded;<br \/>\nnext(); \/\/ Move on to the actual route handler<br \/>\n} catch (err) {<br \/>\nres.status(401).json({ msg: &#8216;Token is not valid or expired&#8217; });<br \/>\n}<br \/>\n};<\/p>\n<p>Boom. That middleware is reusable for any route you wanna lock down. Let\u2019s test it with a private route\u2014say, \/api\/users\/me, which lets a user see their own profile. You just add the protect function as a second argument to the route, like this:<br \/>\n\/\/ Protected route\u2014only works if you send a valid token<br \/>\napp.get(&#8216;\/api\/users\/me&#8217;, protect, (req, res) =&gt; {<br \/>\n\/\/ We can access req.user.userId here, \u2019cause the middleware added it<br \/>\nres.json({ id: req.user.userId, role: req.user.role });<br \/>\n});<\/p>\n<p>Wait, that\u2019s it? It seems simple, but there are a few gotchas that trip up a lot of new devs (and even some old heads, tbh). Let\u2019s talk about those, \u2019cause I\u2019ve fixed so many apps that broke over these small mistakes.<\/p>\n<p>First, the JWT secret. Never hardcode it in your app file, never commit it to Git. Use environment variables\u2014dotenv is your friend here. I\u2019ve had clients come to me last minute \u2019cause they accidentally pushed their JWT secret to GitHub and some hacker was spamming their login endpoints. Just keep that secret in a .env file (add .env to your .gitignore!) and pull it with process.env.JWT_SECRET. If you lose or leak your secret, just rotate it\u2014all existing tokens will become invalid, which is a pain but way better than getting hacked.<\/p>\n<p>Second, token expiration. I set mine to 1 hour max for most apps, some even 15 minutes for super sensitive stuff like payment routes. Why? \u2019Cause if a token gets stolen, the hacker only has a small window to use it. But what if a user is logged in and the token expires while they\u2019re using the app? You can add a refresh token flow\u2014refresh tokens are longer-lived, stored in an HTTP-only cookie (so they can\u2019t be stolen via XSS) that lets the user get a new access token without logging in again. We don\u2019t always implement that for small apps, but it\u2019s a nice touch for production.<\/p>\n<p>Third, where do you send the token? A lot of devs try to put it in the request body or a query parameter, but that\u2019s a bad idea. Query params get logged in server logs, browser history, all that stuff. The best place is the Authorization header, formatted as Bearer [token]\u2014that\u2019s standard, most APIs expect it, and it\u2019s easy to access with the middleware.<\/p>\n<p>Another gotcha: CORS. If your Express app is running on a different domain than your frontend (like your frontend is on frontend.com and Express is on api.yourapp.com), you need to make sure the Authorization header is allowed in CORS. If you don\u2019t set that, your frontend will send the token but the browser will block the request. So in your CORS setup, add &#8216;Authorization&#8217; to the allowed headers. Example with cors package:<br \/>\nconst cors = require(&#8216;cors&#8217;);<br \/>\napp.use(cors({<br \/>\norigin: &#8216;https:\/\/yourfrontend.com&#8217;,<br \/>\nallowedHeaders: [&#8216;Content-Type&#8217;, &#8216;Authorization&#8217;]<br \/>\n}));<\/p>\n<p>Skip that part, and you\u2019ll spend hours wondering why your token isn\u2019t coming through\u2014trust me, I\u2019ve been there.<\/p>\n<p>Now, what about role-based access? Like, only admins can hit \/api\/admin, not regular users. Easy to add to the protect middleware, or make a second middleware for roles. Let\u2019s say your token has a role field\u2014you can add a restrictTo middleware:<br \/>\nconst restrictTo = (&#8230;roles) =&gt; {<br \/>\nreturn (req, res, next) =&gt; {<br \/>\n\/\/ req.user.role comes from the decoded token, remember?<br \/>\nif (!roles.includes(req.user.role)) {<br \/>\nreturn res.status(403).json({ msg: &#8216;You don\u2019t have permission to do that&#8217; });<br \/>\n}<br \/>\nnext();<br \/>\n};<br \/>\n};<\/p>\n<p>Then use it on your admin route:<br \/>\napp.delete(&#8216;\/api\/admin\/users\/:id&#8217;, protect, restrictTo(&#8216;admin&#8217;), (req, res) =&gt; {<br \/>\n\/\/ Only admins can delete users<br \/>\nres.json({ msg: &#8216;User deleted&#8217; });<br \/>\n});<\/p>\n<p>That\u2019s perfect for splitting routes between regular users and admins\u2014no messy checks in every route handler.<\/p>\n<p>Wait, let\u2019s test this whole flow end-to-end to make sure it makes sense. A user goes to your login page, enters their email and password. The frontend sends that to POST \/login, gets a token back. Now, when the user clicks \u201cView My Dashboard\u201d, the frontend sends a GET request to \/api\/dashboard with the Authorization header: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9&#8230; The protect middleware runs, checks that the token is valid, decodes it, adds the user data to req, and the dashboard route sends back the user\u2019s stats. If the token is expired, or the header is missing, the middleware sends a 401 error, and the frontend can kick the user back to the login page.<\/p>\n<p>I\u2019ve used this exact setup for dozens of client Express apps\u2014from small side projects to enterprise-level tools with 10k+ active users. It\u2019s lightweight, doesn\u2019t slow down your Express app (JWT verify is super fast), and it\u2019s easy to adjust as your app grows.<\/p>\n<p>Now, let\u2019s talk about common mistakes I see devs making that make this less secure. First, storing sensitive data in JWT. I\u2019ve seen tokens with password hashes or credit card info\u2014totally unnecessary. JWTs are just base64-encoded, so anyone can decode them with a free tool online. They can\u2019t tamper with the signature (if you set a proper secret), but they can read the data. So stick to non-sensitive stuff: user ID, role, maybe a tiny username, that\u2019s it.<\/p>\n<p>Second, not handling token expiration gracefully. If your frontend just sends an expired token, the middleware throws an error, so your frontend should catch that and redirect to login, or use a refresh token to get a new one. If you ignore that, your users will get random 401 errors and get frustrated\u2014make the error messages clear, like \u201cYour session expired, please log in again\u201d.<\/p>\n<p>Third, using the same secret for all tokens. Wait, no\u2014just don\u2019t use a weak secret. A string like \u201cmyappsecret\u201d is easy to crack. Use a long, random string\u2014like 32+ characters, mix letters, numbers, symbols. You can generate one with crypto in Node.js: require(&#8216;crypto&#8217;).randomBytes(64).toString(&#8216;hex&#8217;)\u2014that\u2019ll give you a super strong secret. Never use default secrets, never reuse the same secret across different apps.<\/p>\n<p>Another thing: if you\u2019re using HTTPS (and you should be, all Express apps need HTTPS these days), make sure the cookies or headers are only sent over HTTPS. If you don\u2019t, tokens can be stolen via man-in-the-middle attacks. Most JWT libraries will handle that if you set the right options when signing, but it\u2019s just something to keep in mind.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.fsshijielogistics.com\/uploads\/44940\/small\/air-freight-air-express-to-us9454f.jpg\"><\/p>\n<p>Now, if you\u2019re building an Express app and need help setting this up\u2014whether it\u2019s debugging a broken middleware, adding refresh tokens, or even building the login flow from scratch\u2014we\u2019re here to help. We specialize in Express builds, from small prototypes to production-grade apps with secure route protection. Don\u2019t waste hours figuring out JWT auth on your own, reach out to our team to talk through your needs and get set up right the first time.<\/p>\n<p><a href=\"https:\/\/www.fsshijielogistics.com\/railway\/railway-railroad-trucking\/\">Railway Railroad Trucking<\/a> References<\/p>\n<ol>\n<li>jsonwebtoken Official Documentation<\/li>\n<li>Express.js Middleware Guide<\/li>\n<li>OWASP JWT Best Practices<\/li>\n<li>bcrypt npm Package Documentation<\/li>\n<\/ol>\n<hr>\n<p><a href=\"https:\/\/www.fsshijielogistics.com\/\">Foshan Shijie International Logistics Co., Ltd.<\/a><br \/>With abundant experience, we are one of the most professional express service suppliers in China. We are committed to offering reliable express service and logistics solutions with low price. If you have any enquiry about quote, please feel free to email us.<br \/>Address: Room 701A, Office Building, Jinbo Commercial Center, No. 88, Guiye Road, Guicheng Street, Nanhai District, Foshan City, Guangdong Province<br \/>E-mail: alicesmith.tradingbusiness@gmail.com<br \/>WebSite: <a href=\"https:\/\/www.fsshijielogistics.com\/\">https:\/\/www.fsshijielogistics.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey folks, if you\u2019ve been running an Express app and worrying about who\u2019s hitting your private &hellip; <a title=\"How to protect routes with Express and JWT?\" class=\"hm-read-more\" href=\"http:\/\/www.simorghict.com\/blog\/2026\/11\/04\/how-to-protect-routes-with-express-and-jwt-470f-11d1f5\/\"><span class=\"screen-reader-text\">How to protect routes with Express and JWT?<\/span>Read more<\/a><\/p>\n","protected":false},"author":756,"featured_media":3712,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3675],"class_list":["post-3712","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-express-4e2b-120831"],"_links":{"self":[{"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/posts\/3712","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/users\/756"}],"replies":[{"embeddable":true,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/comments?post=3712"}],"version-history":[{"count":0,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/posts\/3712\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/posts\/3712"}],"wp:attachment":[{"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/media?parent=3712"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/categories?post=3712"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.simorghict.com\/blog\/wp-json\/wp\/v2\/tags?post=3712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}