Simple Node.js + Express API with user authentication, JWT, roles (admin/user), and CRUD for products.
- Node.js
- Express
- MongoDB
- JWT
- Bcrypt
- Jest + Supertest
- User registration and login
- Password hashing with bcrypt
- JWT token authentication
- Role system (admin, user)
- Auth middleware
- Role middleware (for example: only admin can add products)
- Product CRUD (Create, Read, Update, Delete)
- Authorization: only product owner or admin can edit/delete
/controllers → logic for auth and products
/routes → API endpoints
/models → Mongoose schemas
/middleware → auth and role checks
/tests → basic auth + product tests
app.js → express app setup
server.js → DB connection + app start
npm test
- Runs Jest tests for auth and products
- Uses test database (
api-test,api-test-products)
- Clone the repo
- Install packages:
npm install
-
Create
.envfile in the main folder -
Copy and paste the following into your .env file:
PORT=5000
MONGO_URI=mongodb://localhost:27017/api-forge
JWT_SECRET=yourSecretKeyHere
To seed the database with a default admin, a normal user, and example products, run:
node seed.js
- Start server:
npm run dev
POST /api/auth/register– register userPOST /api/auth/login– login and get token
GET /api/products– publicPOST /api/products– admin onlyPUT /api/products/:id– owner or adminDELETE /api/products/:id– owner or admin
Add token in header:
Authorization: Bearer your_token_here