node express mongo boilerplate with jwt
- Install Node.js and npm:
sudo apt update
sudo apt install nodejs
sudo apt install npm
- Create a new Node.js project:
mkdir your_project_name
cd your_project_name
npm init -y
- Install necessary packages:
npm install express mongoose jsonwebtoken body-parser
- Set up Express server in
app.js
:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Configure MongoDB connection in
app.js
:
mongoose.connect('mongodb://localhost/your_database_name', {
useNewUrlParser: true,
useUnifiedTopology: true
});
- Create a model for user in
models/User.js
:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
password: String
});
module.exports = mongoose.model('User', userSchema);
- Create routes for authentication in
routes/auth.js
:
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
router.post('/login', async (req, res) => {
// Authentication logic here
});
router.post('/register', async (req, res) => {
// Registration logic here
});
module.exports = router;
- Implement JWT token generation and verification in
routes/auth.js
:
const generateToken = (user) => {
return jwt.sign({ _id: user._id }, 'your_secret_key', { expiresIn: '1h' });
};
const verifyToken = (req, res, next) => {
// Token verification logic here
};
// Use generateToken and verifyToken in the login and register routes
- Integrate the authentication routes in
app.js
:
const authRoutes = require('./routes/auth');
app.use('/auth', authRoutes);
- Update the login and register routes with JWT token:
// Inside routes/auth.js
router.post('/login', async (req, res) => {
// Authenticate user and generate JWT token
const token = generateToken(user);
res.json({ token });
});
router.post('/register', async (req, res) => {
// Create user and generate JWT token
const token = generateToken(newUser);
res.json({ token });
});
Now, you have a basic Node.js, Express, and MongoDB boilerplate with JWT authentication. Customize the authentication logic as needed for your application.