1. Create express server that has authorized endpoint using JWT (JSON Web Token) library. 2. Create express server that connects to Mongo DB database to authenticate the user and generate the authorized token to access the protected endpoints. const mongoose = require("mongoose"); //models/User.js const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model("User", userSchema); //middleware/auth.js) const jwt = require('jsonwebtoken'); const dotenv = require('dotenv'); dotenv.config(); module.exports = function (req, res, next) { const token = req.header('Authorization')?.split(' ')[1]; if (!token) return res.status(401).json({ message: 'Access Denied: No Token Provided' }); try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; next(); } catch (err) { res.status(400).json({ message: 'Invalid Token' }); } }; //routes/auth.js const express = require('express'); const jwt = require('jsonwebtoken'); const User = require('../models/User'); const auth = require('../middleware/auth'); const dotenv = require('dotenv'); dotenv.config(); const router = express.Router(); // Register router.post('/register', async (req, res) => { const { username, password } = req.body; try { const user = new User({ username, password }); await user.save(); res.status(201).json({ message: 'User registered' }); } catch (err) { res.status(400).json({ message: 'User already exists' }); } }); // Login router.post('/login', async (req, res) => { const { username, password } = req.body; const user = await User.findOne({ username }); if (!user || !(await user.comparePassword(password))) return res.status(401).json({ message: 'Invalid credentials' }); const token = jwt.sign({ id: user._id, username: user.username }, process.env.JWT_SECRET, { expiresIn: '1h', }); res.json({ token }); }); // Protected route router.get('/protected', auth, (req, res) => { res.json({ message: Hello ${req.user.username}, you accessed a protected route! }); }); module.exports = router; //server.js const express = require('express'); const mongoose = require('mongoose'); const dotenv = require('dotenv'); const authRoutes = require('./routes/auth'); dotenv.config(); const app = express(); app.use(express.json()); // Connect to MongoDB mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => console.log('MongoDB Connected')) .catch(err => console.error('MongoDB Connection Error:', err)); // Routes app.use('/api', authRoutes); // Start server const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(Server running on port ${PORT}));
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter