Secure authentication API using short-lived access tokens, rotating refresh tokens, MongoDB, and HttpOnly cookies.
- User registration, login, current-user, refresh, and logout endpoints
- 15-minute access tokens
- Seven-day refresh tokens with bcrypt-hashed storage
- Refresh token rotation and reuse invalidation
- Secure configurable HttpOnly cookies
- Password hashing and input validation
- Helmet security headers and authentication rate limiting
- Configurable CORS with credentials
- Safe errors, request limits, standardized API responses, and request logs
- Node.js 18 or newer
- MongoDB running locally or a hosted MongoDB connection
npm install
copy .env.example .envSet two different random JWT secrets with at least 32 characters each.
npm run devThe default port is 1198.
| Variable | Required | Description |
|---|---|---|
PORT |
No | Server port, defaults to 1198 |
MONGO_URI |
Yes | MongoDB connection string |
JWT_ACCESS_SECRET |
Yes | Access token secret, minimum 32 characters |
JWT_REFRESH_SECRET |
Yes | Refresh token secret, minimum 32 characters |
NODE_ENV |
No | Use production to enable Secure cookies |
CLIENT_ORIGINS |
No | Comma-separated trusted frontend origins |
COOKIE_SAME_SITE |
No | Cookie policy, defaults to lax |
| Method | Endpoint | Access | Purpose |
|---|---|---|---|
| GET | / |
Public | API status |
| GET | /health |
Public | Health response |
| POST | /api/auth/register |
Public | Register and authenticate |
| POST | /api/auth/login |
Public | Login and rotate tokens |
| POST | /api/auth/refresh-token |
Refresh cookie | Rotate access and refresh tokens |
| GET | /api/auth/me |
Access cookie | Get current user |
| POST | /api/auth/logout |
Public | Revoke refresh token and clear cookies |
All JSON responses include apiUrl as the first field. Browser clients must use credentials: "include" for cookie-based requests.
MIT. See LICENSE.
Ashish Ranjan
Full-Stack Web Developer
- Portfolio: https://www.ashishranjan.net
- GitHub: https://github.com/a2rp
- CodePen: https://codepen.io/ash1198
- LinkedIn: https://www.linkedin.com/in/aashishranjan
- Facebook: https://www.facebook.com/theash.ashish/
- YouTube: https://www.youtube.com/@ashishranjan-ashz?sub_confirmation=1
- Email: ash.ranjan09@gmail.com
- Support: https://a2rp-donation-page.netlify.app/
- Buy Me a Coffee: https://buymeacoffee.com/a2rp
- Patreon: https://www.patreon.com/a2rp