If you're working with Node.js and need to implement user authentication, JWT is one of the most efficient ways to do it! Here's a super simple guide to get you started.
What is JWT? ๐ค
JWT is a way to securely transmit information between the client and server as a token. It's commonly used for authentication, and the best part is, once a token is generated, you donโt need to store user data on the server โ everything is inside the token itself.
How to Implement JWT in Node.js ๐
-
Set up your Node.js project:
Install Express, JWT, and dotenv:
npm install express jsonwebtoken dotenv
-
Create a registration and login system:
- When a user registers or logs in, you generate a JWT token.
Example of generating a JWT:
const jwt = require('jsonwebtoken'); // Here we generate the jwt token --> jwt.sign(payload, secretKey, modreOptions) const token = jwt.sign({ username: 'user1' }, process.env.JWT_SECRET, { expiresIn: '1h' }); console.log(token);
-
Protect your routes with JWT:
Create a middleware to check if the JWT is valid before giving access to protected routes.Example middleware:
// /middleware/auth.js const jwt = require('jsonwebtoken'); function authMiddleware(req, res, next) { const token = req.header('Authorization'); if (!token) return res.status(401).json({ message: 'Access denied' }); try { // Verify the token --> jwt.verify(tokenValue, secretKey) const verified = jwt.verify(token, process.env.JWT_SECRET); req.user = verified; next(); } catch (err) { res.status(400).json({ message: 'Invalid token' }); } }
-
Add the middleware function to your protected routes:
// Just pass the middleware (autMiddleware) as an argument app.get('/profile', authMiddleware, (req, res) => { res.json({ message: `Welcome ${req.user.username}!` }); });
And thatโs it! ๐ With these few lines of code, you have JWT-based authentication set up in Node.js! ๐
๐ก Bonus tip: Always store your JWT secret in environment variables (.env
) to keep it safe, and set reasonable expiration times for tokens.
Feel free to share this or try it yourself! ๐
Top comments (0)