A simple Node.js + Express + MongoDB application for managing contacts with JWT authentication and user-based access control.
This project demonstrates how to build a REST API using Express with the following features:
- REST API convention (clear endpoints, CRUD structure)
- Contact management (CRUD)
- User authentication with JWT
- Route protection and role-based access
- MongoDB integration with Mongoose
- Error handling middleware and async handlers
git clone <your-repo-url>
cd contact-management-appnpm installCreate a .env file in the root directory:
PORT=5000
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=your_secret_keynpm start- Built an Express server
- Configured middleware for JSON parsing and error handling
- Used
express.Router()for modular route management
- GET /api/contacts → Fetch all contacts
- POST /api/contacts → Create a new contact
- GET /api/contacts/:id → Fetch a single contact by ID
- PUT /api/contacts/:id → Update a contact
- DELETE /api/contacts/:id → Delete a contact
- Contact Controller → Handles CRUD logic for contacts
- User Controller → Handles registration, login, and current user retrieval
- Custom error handling middleware
- Async handler (
express-async-handler) for managing async/await - JWT verification middleware (
verifyJWT) for protecting routes
- Mongoose schema for Contact
- Mongoose schema for User with password hashing
- Established relationship between User and Contact
- User registration (
/api/users/register) - User login with JWT access token (
/api/users/login) - Route protection with JWT verification
- User-specific contacts → Only logged-in users can manage their own contacts
You can use Thunder Client (VS Code extension) or Postman:
- Register a user →
/api/users/register - Login with credentials →
/api/users/login- Copy the JWT token
- Add
Authorization: Bearer <your_token>in headers - Access protected routes (Contacts CRUD)
- Building an Express server
- REST API conventions
- Using routers for modular code
- Middleware for error handling and async requests
- MongoDB integration with Mongoose
- User authentication with JWT
- Protecting routes with middleware
- Relationship between users and contacts in MongoDB
- Node.js
- Express.js
- MongoDB + Mongoose
- JWT (jsonwebtoken)
- bcryptjs
This project is for learning purposes and can be freely used or extended.