How to implement authentication in Node.js
Implementing secure authentication is crucial for protecting user data and controlling access to application resources. As the creator of CoreUI with 25 years of development experience, I’ve built authentication systems for countless enterprise applications. The most secure and scalable approach combines JWT tokens for stateless authentication with bcrypt for password hashing. This method provides excellent security while maintaining performance and scalability.
Use JWT tokens with bcrypt password hashing for secure stateless authentication.
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const express = require('express')
const app = express()
app.use(express.json())
// Register user
app.post('/register', async (req, res) => {
const { email, password } = req.body
const hashedPassword = await bcrypt.hash(password, 10)
// Save user to database (implementation depends on your DB)
const user = { id: 1, email, password: hashedPassword }
const token = jwt.sign({ userId: user.id }, 'your-secret-key', { expiresIn: '24h' })
res.json({ token, user: { id: user.id, email } })
})
// Login user
app.post('/login', async (req, res) => {
const { email, password } = req.body
// Find user in database
const user = await findUserByEmail(email)
if (!user || !await bcrypt.compare(password, user.password)) {
return res.status(401).json({ error: 'Invalid credentials' })
}
const token = jwt.sign({ userId: user.id }, 'your-secret-key', { expiresIn: '24h' })
res.json({ token, user: { id: user.id, email } })
})
This implementation uses bcrypt to hash passwords with a salt rounds of 10, ensuring secure password storage. JWT tokens are generated with user ID payload and expiration time. The login endpoint compares the provided password with the hashed version using bcrypt.compare(). Always store the secret key in environment variables and never expose sensitive user data in responses.
Best Practice Note:
This is the same robust authentication pattern we implement in CoreUI enterprise applications. Always use environment variables for secret keys, implement rate limiting on auth endpoints, and consider adding refresh token functionality for enhanced security.



