A production-ready Authentication and Authorization API built from scratch with Node.js, Express, TypeScript, and MongoDB (Mongoose). Implements JWT-based authentication and role-based access control (RBAC).
- User registration with hashed passwords (bcrypt)
- JWT-based login (stateless authentication)
- Protected routes via
protectmiddleware (verifies JWT) - Role-based authorization via
authorizemiddleware (user/admin) - Strongly typed end-to-end with TypeScript (Mongoose models, Express
Request, JWT payloads) - Centralized, validated environment configuration (fails fast on missing secrets)
- Secure-by-default password handling (
select: falseon the password field)
| Layer | Technology |
|---|---|
| Runtime | Node.js |
| Framework | Express |
| Language | TypeScript |
| Database | MongoDB (via Mongoose) |
| Auth | JSON Web Tokens (jsonwebtoken) |
| Password hashing | bcryptjs |
| Dev tooling | tsx (dev server), tsc (build) |
src/
├── config/
│ ├── env.ts # Validated, typed environment variables
│ └── db.ts # MongoDB connection
├── controllers/
│ └── auth.controller.ts # register, login, getProfile, getAdminDashboard
├── middlewares/
│ └── auth.middleware.ts # protect (JWT verify), authorize (role check)
├── models/
│ └── User.ts # Mongoose schema + bcrypt pre-save hook
├── routes/
│ └── auth.routes.ts # Route definitions
├── types/
│ └── express/
│ └── index.d.ts # Extends Express Request with `user`
├── utils/
│ └── jwt.util.ts # JWT signing helper
└── server.ts # App entry point
- Node.js (v18+ recommended)
- MongoDB running locally, or a MongoDB Atlas connection string
git clone https://github.com/SaqibShah-dev/auth-system-ts.git
cd auth-system-ts
npm installCreate a .env file in the project root:
PORT=5000
NODE_ENV=development
MONGO_URI=mongodb://127.0.0.1:27017/auth-system
# Or, for MongoDB Atlas:
# MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/auth-system
JWT_SECRET=your_super_secret_key_change_me
JWT_EXPIRES_IN=1dThe app will refuse to start if
NODE_ENV,MONGO_URI, orJWT_SECRETare missing — this is intentional (fail fast at startup rather than failing later mid-request).
# Development (auto-restart on file changes)
npm run dev
# Production build
npm run build
npm startOn success, you should see:
✅ MongoDB connected successfully
🚀 Server running on http://localhost:5000
Base URL: http://localhost:5000/api/auth
Public. Creates a new user with role user by default.
Body:
{
"name": "John Doe",
"email": "[email protected]",
"password": "password123"
}Responses:
201 Created— user created, returnstoken+user400 Bad Request— missing fields409 Conflict— email already registered
Public. Authenticates a user and returns a JWT.
Body:
{
"email": "[email protected]",
"password": "password123"
}Responses:
200 OK— returnstoken+user400 Bad Request— missing fields401 Unauthorized— invalid email or password (same message for both, to prevent user enumeration)
Protected. Requires a valid JWT.
Headers:
Authorization: Bearer <token>
Responses:
200 OK— returns the current user's profile401 Unauthorized— missing/invalid/expired token404 Not Found— token is valid but the user no longer exists in the DB
Protected + role-restricted (admin only).
Headers:
Authorization: Bearer <token>
Responses:
200 OK— returns basic user stats401 Unauthorized— missing/invalid token403 Forbidden— valid token, but role is notadmin
New users cannot self-assign the
adminrole. To test this route, manually update a user'srolefield to"admin"directly in the database, then log in again to get a fresh token (existing tokens retain the role they were issued with).
- Passwords are hashed with
bcrypt(cost factor 10) before being saved — never stored in plain text. - The
passwordfield is excluded from all queries by default (select: false) and must be explicitly requested (.select('+password')) — used only internally during login. - Login failures return identical messages/status codes regardless of whether the email or password was wrong, to prevent account enumeration.
- JWTs are stateless: role changes made in the database do not affect already-issued tokens until they expire or the user logs in again.
- Centralized error-handling middleware (remove repeated
try/catchin controllers) - Request validation with a schema library (e.g. Zod)
- Refresh tokens / token revocation
- Rate limiting on
/loginto mitigate brute-force attempts - Password reset flow (email-based)
MIT