While learning Node.js and the Express framework, I tried to build a simple project, represented by a login & crud APP. ✨The key features are:
- Full Authentication Flow: Secure Login/Register system using Passport.js (Local Strategy).
- Security: Passwords never stored in plain text; they are hashed and salted using bcrypt.
- Roles: Users can view their profile, while admin can delete and update users(CRUD capabilities). Of course, admin users cannot be deleted to ensure system stability.
- Database security: Connection to a MySQL database and all the users are saved into a database via phpMyAdmin
- Basic paginated API to handle large datasets.
| Components | Technology |
|---|---|
| Backend | Node.js, Express, Passport.js |
| Front-end | Embedded JavaScript, Bootstrap 5 |
| Database | MySQL created via phpMyAdmin (Pool Connection) |
| Auth | Passport.js, Express sessions |
| Security | BCrypt, Flash |
- Clone this repository.
- Install dependencies:
npm install. - Create a MySQL database named nodejs and run the following command to create the users table used in this project:
CREATE TABLE persons(
PersonID INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
email VARCHAR(255) UNIQUE,
password VARCHAR(255),
role VARCHAR(50) DEFAULT 'user');
- Create a .env file in your root directory:
ACCESS_SECRET=your_super_secret_key
HOST=localhost
user=root
database=nodejs
- Run the application with:
npm startornpm run dev
| Method | Endpoint | Description |
|---|---|---|
GET |
/users/login |
Login page |
POST |
/users/register |
Create a new account |
PATCH |
/users/update/:id |
Update user details (Admin only) |
DELETE |
/users/delete/:id |
Delete a user (Admin only) |
GET |
/users/:limit/:page |
API Paginated with users |
So, the main file server.jsinitializes the express server, uses a global middleware for error handling, uses the json and the urlencoded middleware,
and the router, which centralizes traffic through a modular router. In the views folder(frontend), there are the .ejs files, to render dynamic content, which might contain some embedded ejs, displaying
user-specific data passed from the server and overrides the form method.
In the routes/route.js, it is the main functionality, it contains a route for every functionality, the connection to the database
using a MySQL Connection Pool, and the route handlers for registration, profile updates and deletions.
In the utils/passportconfig.js, I implemented a strategy to authenticate the user, comparing the plain-text password with the password
from the database. It also contains serializeUser and deserializeUser to maintain user state across requests, identifying the user by their PersonID.. Also, in this file there is the logic implemented for the authorization logic
(isItAdmin) to protect sensitive routes, ensuring only users with the 'admin' role can modify or delete data.
Author: Moldovan Alex