Skip to main content

Implementing JWT Authentication

JSON Web Tokens (JWT) are a small and secure way to share information between two parties.

In Node.js, JWTs are commonly used for authentication and information exchange. Here’s a simple guide on how to use JWT for authentication in Node.js.

Authentication is the process of verifying the identity of a user. It often involves validating credentials like usernames and passwords. If the credentials match the stored data, the system confirms the identity and grants access.

Installation

First, install the jsonwebtoken package using npm:

npm install jsonwebtoken

Creating a Token

we can build a createJWT function to create a new JWT token.

It takes a user ID as an argument and signs a new token with the user ID as the payload.

export function createJWT(id) {
return JWT.sign({ userId: id }, process.env.JWT_SECRET_KEY, {
expiresIn: "1d"
});
}

The token expires in 1 day (expiresIn: "1d"), after which the user would need to authenticate again.

Verifying a Token

The userAuth function is a middleware that verifies the JWT token from the Authorization header of the incoming request.

const userAuth = async(req, res, next) => {
// Extract the Authorization header from the request
const authHeader = req?.headers?.authorization

// Check if Authorization header is missing or doesn't start with "Bearer"
if(!authHeader || !authHeader?.startsWith("Bearer")){
next("Authentication == failed")
}

// Extract the JWT token from the Authorization header
const token = authHeader?.split(" ")[1]

try{
const userToken = JWT.verify(token, process.env.JWT_SECRET_KEY)

req.body.user = {
userId: userToken.userId
}

next()
} catch (error) {
console.log('error', error)
next("Authentication failed")
}
}

export default userAuth

If the token is valid, it adds the user’s ID to the request body and calls the next() function to proceed to the next middleware or route handler.

If the token is invalid, it logs the error and ends the request-response cycle with an “Authentication failed” message.