How to create a JWT Authentication in Node.js

This example assumes you have a user model and a database to store user information.

First, install the jsonwebtoken library by running npm install jsonwebtoken in your project directory.

				
					// Require the necessary modules
const jwt = require('jsonwebtoken');

// Define your secret key for JWT
const secretKey = 'yourSecretKey';

// Generate a JWT token for a user
function generateToken(user) {
  const payload = {
    userId: user.id,
    username: user.username,
    // You can include additional data in the payload if needed
  };

  const options = {
    expiresIn: '1h', // Token expiration time
  };

  // Sign the token with the payload and secret key
  const token = jwt.sign(payload, secretKey, options);

  return token;
}

// Verify and decode a JWT token
function verifyToken(token) {
  try {
    const decoded = jwt.verify(token, secretKey);
    return decoded;
  } catch (err) {
    // Token verification failed
    return null;
  }
}

// Middleware to authenticate requests
function authenticate(req, res, next) {
  const token = req.headers.authorization;

  if (!token) {
    // Token is missing
    return res.status(401).json({ message: 'No token provided' });
  }

  // Verify the token
  const decoded = verifyToken(token);

  if (!decoded) {
    // Invalid token
    return res.status(401).json({ message: 'Invalid token' });
  }

  // Token is valid, attach the decoded payload to the request object
  req.user = decoded;
  next();
}

module.exports = {
  generateToken,
  verifyToken,
  authenticate,
};
				
			

To use this module, you can require it in your routes or controllers and utilize the functions as needed. Here’s an example of how you can use it:

				
					const express = require('express');
const auth = require('./auth'); // Assuming you've named the file 'auth.js'

const app = express();

// Example route that generates a JWT token upon successful login
app.post('/login', (req, res) => {
  // Authenticate the user and generate a token
  const user = {
    id: 1,
    username: 'exampleuser',
    // Other user properties...
  };

  const token = auth.generateToken(user);

  res.json({ token });
});

// Example protected route that requires authentication
app.get('/protected', auth.authenticate, (req, res) => {
  // Access the authenticated user's information from req.user
  res.json({ message: 'You are authenticated!', user: req.user });
});

// Start the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
				
			

Please note that this is a basic example to help you get started. In a production environment, you would likely want to enhance the error handling, add proper user validation, integrate with a database, and possibly include additional security measures.