Tutorial
Auth Routes 4

MIDDLEWARE Auth.js

Routes With Files

server
├── middleware
│   ├── auth.js
import jwt from "jsonwebtoken";
 
export const verifyToken = async (req, res, next) => {
  try {
    let token = req.header("Authorization");
 
    if (!token) {
      return res.status(403).send("Access Denied");
    }
 
    if (token.startsWith("Bearer ")) {
      token = token.slice(7, token.length).trimLeft();
    }
 
    const verified = jwt.verify(token, process.env.JWT_SECRET);
    req.user = verified;
    next();
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
 

Introduction

The auth.js file is used to provide authorization functionality to our application. This means that it allows logged-in users to perform certain actions that non-logged-in users cannot. In this file, we will be using JSON Web Tokens (JWT) to authenticate users.

Importing Dependencies

The first thing we do in this file is import the jsonwebtoken module using the import statement. This module will allow us to work with JWTs in our application.

import jwt from "jsonwebtoken";

Exporting a Middleware Function

Next, we export a middleware function called verifyToken. Middleware functions are functions that get executed in the middle of the request-response cycle. In this case, our verifyToken function will be executed before any protected routes are accessed.

export const verifyToken = async (req, res, next) => {
  // Function body here
};

The verifyToken function takes in three parameters: req, res, and next. req and res are objects that represent the incoming request and the outgoing response, respectively. next is a function that we call when we are ready to move on to the next middleware function in the stack.

Parsing the JWT

Inside the verifyToken function, we first try to retrieve the JWT from the incoming request headers. We expect the JWT to be passed in the Authorization header.

let token = req.header("Authorization");

If there is no JWT present in the request headers, we return a 403 status code and the message "Access Denied".

if (!token) {
  return res.status(403).send("Access Denied");
}

If a JWT is present, we check if it starts with the string "Bearer ". If it does, we strip that string from the JWT.

if (token.startsWith("Bearer ")) {
  token = token.slice(7, token.length).trimLeft();
}

Verifying the JWT

Next, we use the jwt.verify() function to verify the JWT. We pass in the JWT and a secret string that we defined elsewhere in our application as parameters to this function.

const verified = jwt.verify(token, process.env.JWT_SECRET);

If the JWT is valid, we set the user property on the req object to the decoded JWT.

req.user = verified;

Finally, we call the next function to move on to the next middleware function in the stack.

next();

Handling Errors

If an error occurs during any of the above steps, we catch it using a try-catch block. We then return a 500 status code and a JSON object containing the error message.

try {
  // JWT verification code here
  next();
} catch (err) {
  res.status(500).json({ error: err.message });
}
 

Conclusion

In conclusion, the auth.js file provides authorization functionality to our application using JSON Web Tokens. The verifyToken middleware function retrieves the JWT from the request headers, verifies it, and sets the user property on the req object. If any errors occur, they are caught and a 500 status code is returned.

// This function takes in a request object, a response object, and a next function as arguments
export const verifyToken = async (req, res, next) => {
  try {
    // Get the token from the Authorization header of the request
    let token = req.header("Authorization");
 
    // If there is no token, return a 403 (Forbidden) status code and "Access Denied" message
    if (!token) {
      return res.status(403).send("Access Denied");
    }
 
    // If the token starts with "Bearer ", remove it from the token string
    if (token.startsWith("Bearer ")) {
      token = token.slice(7, token.length).trimLeft();
    }
 
    // Verify the token using the JWT_SECRET environment variable
    const verified = jwt.verify(token, process.env.JWT_SECRET);
    // Set the user property of the request object to the verified token
    req.user = verified;
    // Call the next function to move on to the next middleware function
    next();
  } catch (err) {
    // If there is an error, return a 500 (Internal Server Error) status code and the error message
    res.status(500).json({ error: err.message });
  }
};