Hey folks, if you’ve been running an Express app and worrying about who’s hitting your private endpoints—like your users’ dashboards, payment processing stuff, or internal admin tools—you’re not alone. I’ve been in your shoes. For years, I’ve 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’s where JWT (JSON Web Tokens) comes in, and today I’m breaking down how we do it at our Express shop—no fancy jargon, no overcomplicated steps, just real stuff that works for day-to-day builds. Express

First, let’s get one thing straight: JWT isn’t magic. It’s 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—your app issues it, and only people with the right key can get into the rooms (routes) that matter. And since I’m an Express specialist, I’m gonna skip the “what is JWT?” Wikipedia-level explanation and jump straight into how to plug this into your Express app without breaking anything.
Let’s start with the basics you’ll need first. I’m assuming you already have an Express app set up, right? If not, that’s on you for starting from scratch, but I’ll keep this focused on the actual route protection part. First, you’ll need two npm packages: jsonwebtoken for generating and verifying tokens, and bcrypt (or whatever hashing library you use) to hash passwords before storing ’em in your database—never store plain text passwords, that’s basic security 101. Oh, and express, obviously, since we’re talkin’ Express here.
Wait, let’s not skip the login step—you can’t protect routes if you don’t have tokens to give out. Let’s 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’s sign() method. What goes into the token? Just the necessary stuff—like the user’s 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, ’cause those are easy to decode even if you can’t tamper with ’em. Here’s a quick example of that:
const jwt = require(‘jsonwebtoken’);
const bcrypt = require(‘bcrypt’);
app.post(‘/login’, async (req, res) => {
const { email, password } = req.body;
// Grab user from DB (pseudo-code here, just to make it real)
const user = await User.findOne({ email });
if (!user) return res.status(401).json({ msg: ‘Invalid credentials’ });
// Check password hash
const validPass = await bcrypt.compare(password, user.passwordHash);
if (!validPass) return res.status(401).json({ msg: ‘Invalid credentials’ });
// Generate token: sign with a secret (keep this in env vars, never hardcode!)
const token = jwt.sign(
{ userId: user._id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: ‘1h’ } // Super important—tokens shouldn’t live forever!
);
res.json({ token });
});
That’s 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—perfect for checking if the token is there and valid. That way, you don’t have to copy-paste the same token check into every private route.
Here’s the middleware we use every day, refined over a million test runs with client apps:
const jwt = require(‘jsonwebtoken’);
// Auth middleware to protect routes
const protect = (req, res, next) => {
// Get token from the Authorization header—format is usually "Bearer [token]"
const authHeader = req.headers.authorization;
let token;
// Check if the header exists and starts with Bearer
if (authHeader && authHeader.startsWith(‘Bearer’)) {
// Split the header to get just the token
token = authHeader.split(‘ ‘)[1];
}
// If no token, no access
if (!token) {
return res.status(401).json({ msg: ‘No token, authorization denied’ });
}
// Verify the token—if it’s tampered with or expired, this throws an error
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Attach the user’s data to the request so we can use it in the route
req.user = decoded;
next(); // Move on to the actual route handler
} catch (err) {
res.status(401).json({ msg: ‘Token is not valid or expired’ });
}
};
Boom. That middleware is reusable for any route you wanna lock down. Let’s test it with a private route—say, /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:
// Protected route—only works if you send a valid token
app.get(‘/api/users/me’, protect, (req, res) => {
// We can access req.user.userId here, ’cause the middleware added it
res.json({ id: req.user.userId, role: req.user.role });
});
Wait, that’s 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’s talk about those, ’cause I’ve fixed so many apps that broke over these small mistakes.
First, the JWT secret. Never hardcode it in your app file, never commit it to Git. Use environment variables—dotenv is your friend here. I’ve had clients come to me last minute ’cause 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—all existing tokens will become invalid, which is a pain but way better than getting hacked.
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? ’Cause 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’re using the app? You can add a refresh token flow—refresh tokens are longer-lived, stored in an HTTP-only cookie (so they can’t be stolen via XSS) that lets the user get a new access token without logging in again. We don’t always implement that for small apps, but it’s a nice touch for production.
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’s 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]—that’s standard, most APIs expect it, and it’s easy to access with the middleware.
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’t set that, your frontend will send the token but the browser will block the request. So in your CORS setup, add ‘Authorization’ to the allowed headers. Example with cors package:
const cors = require(‘cors’);
app.use(cors({
origin: ‘https://yourfrontend.com’,
allowedHeaders: [‘Content-Type’, ‘Authorization’]
}));
Skip that part, and you’ll spend hours wondering why your token isn’t coming through—trust me, I’ve been there.
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’s say your token has a role field—you can add a restrictTo middleware:
const restrictTo = (…roles) => {
return (req, res, next) => {
// req.user.role comes from the decoded token, remember?
if (!roles.includes(req.user.role)) {
return res.status(403).json({ msg: ‘You don’t have permission to do that’ });
}
next();
};
};
Then use it on your admin route:
app.delete(‘/api/admin/users/:id’, protect, restrictTo(‘admin’), (req, res) => {
// Only admins can delete users
res.json({ msg: ‘User deleted’ });
});
That’s perfect for splitting routes between regular users and admins—no messy checks in every route handler.
Wait, let’s 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 “View My Dashboard”, the frontend sends a GET request to /api/dashboard with the Authorization header: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9… 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’s 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.
I’ve used this exact setup for dozens of client Express apps—from small side projects to enterprise-level tools with 10k+ active users. It’s lightweight, doesn’t slow down your Express app (JWT verify is super fast), and it’s easy to adjust as your app grows.
Now, let’s talk about common mistakes I see devs making that make this less secure. First, storing sensitive data in JWT. I’ve seen tokens with password hashes or credit card info—totally unnecessary. JWTs are just base64-encoded, so anyone can decode them with a free tool online. They can’t 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’s it.
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—make the error messages clear, like “Your session expired, please log in again”.
Third, using the same secret for all tokens. Wait, no—just don’t use a weak secret. A string like “myappsecret” is easy to crack. Use a long, random string—like 32+ characters, mix letters, numbers, symbols. You can generate one with crypto in Node.js: require(‘crypto’).randomBytes(64).toString(‘hex’)—that’ll give you a super strong secret. Never use default secrets, never reuse the same secret across different apps.
Another thing: if you’re 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’t, 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’s just something to keep in mind.

Now, if you’re building an Express app and need help setting this up—whether it’s debugging a broken middleware, adding refresh tokens, or even building the login flow from scratch—we’re here to help. We specialize in Express builds, from small prototypes to production-grade apps with secure route protection. Don’t 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.
Railway Railroad Trucking References
- jsonwebtoken Official Documentation
- Express.js Middleware Guide
- OWASP JWT Best Practices
- bcrypt npm Package Documentation
Foshan Shijie International Logistics Co., Ltd.
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.
Address: Room 701A, Office Building, Jinbo Commercial Center, No. 88, Guiye Road, Guicheng Street, Nanhai District, Foshan City, Guangdong Province
E-mail: alicesmith.tradingbusiness@gmail.com
WebSite: https://www.fsshijielogistics.com/