Simple Node + Express + Mongoose example implementing JWT Bearer auth using ES modules.
- Clone
npm install
- Create
.env
withPORT
,MONGO_URI
,JWT_SECRET
npm run dev
- POST /api/auth/register
- POST /api/auth/login
- GET /api/users/me (protected)
- Passwords are hashed using bcrypt.
- JWT token expiry controlled via
JWT_EXPIRY
env var. - For production: use HTTPS, strong JWT secret, refresh tokens, rate limiting, helmet, input validation, logging.
- Register User
Request Method: POST URL: {{baseUrl}}/auth/register Headers:Content-Type: application/json Body (raw JSON) :
{ "username": "test", "email": "test@example.com", "password": "secret123" }
Success Response (201): { "message": "User registered successfully" }
Failure Response (409 – Email exists): { "message": "Email already registred" }
- Login User:
Request Method: POST URL: {{baseUrl}}/auth/login Headers:Content-Type: application/json Body (raw JSON): { "email": "test@example.com", "password": "secret123" " } Success Response (200):
{ "message": "Login Successful", "token": "eyJhbGciOiJIUzI1........." }
Failure Response (401 – Wrong credentials): { "message": "Invalid credentials" }
- Access Protected User Route Method: GET URL: http://localhost:5000/api/users/me Headers: Authorization: Bearer Token Token: <paste_token_here> { "message": "Welcome test, you are authorized!", "user": { "_id": "68cd56dd1b22fe2696d68956", "username": "test", "email": "test@gmail.com", "createdAt": "2025-09-19T13:13:01.613Z", "__v": 0 } }