User authentication is a crucial feature in web applications as it allows users to securely access their accounts and data. In this tutorial, we will learn how to implement user authentication using Node.js and Express.js.
- Install necessary packages
First, make sure you have Node.js and npm installed on your machine. Create a new directory for your project and run the following command to initialize a new Node.js project:
npm init -y
Next, install the required packages for user authentication:
npm install express body-parser bcrypt jsonwebtoken dotenv
- Set up Express server
Create a new fileserver.js
and set up an Express server:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Set up routes for user authentication
Create a new folderroutes
and addauth.js
file for handling user authentication routes:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();
router.post('/register', (req, res) => {
// Register new user
});
router.post('/login', (req, res) => {
// Login user
});
module.exports = router;
- Implement user registration
In theauth.js
file, implement the user registration route:
router.post('/register', async (req, res) => {
// Check if user already exists
// Hash the password
// Save user to database
// Generate JWT token
res.json({ message: 'User registered successfully', token });
});
- Implement user login
In theauth.js
file, implement the user login route:
router.post('/login', async (req, res) => {
// Find user in database
// Compare hashed password
// Generate JWT token
res.json({ message: 'User logged in successfully', token });
});
- Protect routes with authentication
To protect certain routes, create a middleware function to verify the JWT token:
const verifyToken = (req, res, next) => {
const token = req.header('Authorization');
if (!token) {
return res.status(401).json({ message: 'Access denied' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded.id;
next();
} catch (error) {
res.status(400).json({ message: 'Invalid token' });
}
};
- Test user authentication
Start the Express server by runningnode server.js
and test the user registration and login routes using tools like Postman.
This tutorial covers the basics of user authentication using Node.js and Express.js. You can further enhance security by adding features like password reset, email verification, and role-based access control. Remember to always store sensitive information securely and use best practices for authentication and authorization in your applications.