A comprehensive, educational Express.js application that demonstrates JWT (JSON Web Token) authentication concepts with MongoDB integration.
Include in yoru .env file in the root directory:
# MongoDB connection string from MongoDB Atlas
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority
# JWT Secret Key - GENERATE A NEW ONE FOR PRODUCTION!
# You can generate a secure secret with this command:
# node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
JWT_SECRET=your-super-secret-jwt-key-here-make-it-long-and-random
# Optional: Set port (defaults to 3000)
PORT=3000
βββ app.mjs # Main server with detailed JWT education
βββ package.json # Dependencies and scripts
βββ .env.example # Environment variable template
βββ public/ # Frontend files
βββ index.html # Landing page
βββ auth.html # Authentication interface
βββ protected-demo.html # Protected route demonstration
βββ student-crud.html # Authenticated CRUD operations
βββ styles/ # Organized CSS files
β βββ auth.css
β βββ index.css
β βββ protected-demo.css
β βββ student-crud.css
βββ scripts/ # Organized JavaScript files
βββ auth.js
βββ index.js
βββ protected-demo.js
βββ student-crud.js
// What happens when a user registers:
POST /api/auth/register
{
"username": "student123",
"password": "mypassword"
}
// Server process:
1. Validates input (username exists, password length)
2. Checks if username is already taken
3. Hashes password with bcrypt (NEVER store plain passwords!)
4. Saves user to MongoDB
5. Returns success message
// What happens when a user logs in:
POST /api/auth/login
{
"username": "student123",
"password": "mypassword"
}
// Server process:
1. Finds user in database
2. Compares provided password with stored hash using bcrypt
3. If valid, creates JWT token with user info
4. Returns token to client
// JWT Token Structure (3 parts):
// header.payload.signature
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2M...
// Client sends token in Authorization header:
GET /api/auth/me
Headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
// Server middleware process:
1. Extracts token from "Bearer TOKEN" format
2. Verifies token signature using JWT_SECRET
3. Checks if token is expired
4. If valid, adds user info to req.user
5. Calls next() to continue to route handler
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
Visit: https://jwt.io/ and use their secret generator
openssl rand -hex 64
Important:
// Add CORS middleware if needed:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
next();
});