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)