DEV Community

Yaser
Yaser

Posted on

๐ŸŒŸ JWT auth made pretty pretty simple!

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 ๐Ÿš€

  1. Set up your Node.js project:
    Install Express, JWT, and dotenv:

    npm install express jsonwebtoken dotenv
    
  2. 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);
    
    
  3. 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' });
      }
    }
    
    
  4. 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! ๐Ÿ˜Š

Nodejs #JWT #Authentication #WebDevelopment #Backend #Security

Top comments (0)