Node.js JWT Auth with Express
Implement JWT authentication flow in Node.js Express with bcrypt password hashing, token signing and verification, refresh token endpoint, and protected.
Code
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
export async function login(email, password) {
const user = await User.findByEmail(email);
if (!user || !await bcrypt.compare(password, user.hash)) {
throw new Error('Invalid credentials');
}
const token = jwt.sign({ sub: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
return { token, user: { id: user.id, email: user.email } };
}
export function requireAuth(req, res, next) {
try {
const payload = jwt.verify(req.headers.authorization.split(' ')[1], process.env.JWT_SECRET);
req.userId = payload.sub;
next();
} catch { res.status(401).json({ error: 'Unauthorized' }); }
}How the snippet works
Node.js JWT Auth with Express comes down to the functions login and requireAuth.
Await points sequence the asynchronous work; a rejection lands at the awaiting line. A guard precedes the Error: bad state stops the flow there instead of continuing.
Configuration comes from the environment — it reads JWT_SECRET, so the same code switches behavior between environments without edits.
The result is a fresh construction, so callers can keep their originals.
Caveats
- Dependency check:
jsonwebtokenandbcryptjs— not built-in, must be present in the project.
Using it
The main signature reads export async function login(email, password)
login is what another module would consume; nothing else here is load-bearing for callers.
Key statements
return { token, user: { id: user.id, email: user.email } };
if (!user || !await bcrypt.compare(password, user.hash)) {
throw new Error('Invalid credentials');
}
const user = await User.findByEmail(email);
Interactive Tools for This Topic
FAQ
- Does `login` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- How does the snippet fail?
- Validation comes first — `Error` marks the failure, before any partial work happens.
- What does this need from the package registry?
- These are real dependencies: `jsonwebtoken` and `bcryptjs`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.