DEV Community

Cover image for JWT Authentication and Cookie Management in Web Applications
Abdullahi-abdiaziz
Abdullahi-abdiaziz

Posted on

JWT Authentication and Cookie Management in Web Applications

Understanding JWT Authentication and Cookie Management in Web Applications

When building modern web applications, especially those requiring user authentication, one of the most commonly used methods is JWT (JSON Web Token). In this article, we’ll dive into what JWT is, how it works, and explain a piece of code that generates and sets a JWT as a cookie. This will be especially useful for beginners who are learning how to manage user authentication in web development.

Let’s start by understanding the basics.

What is JWT?

JWT stands for JSON Web Token, which is a compact and secure way to represent information between two parties (the client and the server). In the context of a web application, it’s used to verify the identity of a user without needing to check their credentials (like a password) repeatedly.

Imagine a JWT as a ticket that a user receives after logging in. This ticket has some information about the user (like their ID), and it’s signed by the server. The user holds onto this ticket and presents it every time they request something from the server, so the server knows who they are.

Key Components of a JWT:

  • Header: This contains metadata about the token, like the type (JWT) and the algorithm used to sign it.
  • Payload: This contains the actual data, such as the user’s ID (userId), and can include other details.
  • Signature: This is a unique signature that is created using a secret key (known only to the server). It ensures that no one can tamper with the token.

JWTs are typically used for authentication in web applications. When a user logs in, the server generates a JWT and sends it to the client (usually in a cookie). The client then sends this token with every request, allowing the server to verify the user’s identity.

Code Breakdown: Generating a JWT and Setting it in a Cookie

Here’s a piece of code that illustrates how to generate a JWT and store it in a cookie:

import jwt from "jsonwebtoken";

export const generateTokenAndSetCookies = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "7d",
  });

  res.cookie("token", token, {
    httpOnly: true,
    sameSite: "strict",
    secure: process.env.NODE_ENV === "production",
    maxAge: 7 * 60 * 60 * 1000, // 7 days
  });
  return token;
};
Enter fullscreen mode Exit fullscreen mode

Let’s break it down and explain each part.

1. Creating the JWT (jwt.sign)

The first part of the function creates the JWT. Here's what happens:

const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "7d",
});
Enter fullscreen mode Exit fullscreen mode
  • jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: "7d" }): This generates a JWT with the userId as part of its payload. The process.env.JWT_SECRET is a secret key stored in the environment variables that’s used to sign the token, ensuring its security. The token is set to expire in 7 days (expiresIn: "7d"), meaning after that period, it will no longer be valid, and the user will need to log in again.

Why is this important?

  • This token is used to authenticate the user. When the user makes future requests, they’ll send this token back to the server, so the server can verify their identity.

If you skip this step:

  • Without generating a token, the server will have no way to know who the user is after they log in. This means they won’t be able to access pages or perform actions that require authentication, like viewing their profile or making a purchase.

2. Storing the Token in a Cookie (res.cookie)

After creating the token, we need to store it somewhere so that the browser can send it along with every request. We do this by saving it in a cookie.

res.cookie("token", token, {
    httpOnly: true,
    sameSite: "strict",
    secure: process.env.NODE_ENV === "production",
    maxAge: 7 * 60 * 60 * 1000, // 7 days
});
Enter fullscreen mode Exit fullscreen mode

Here’s what each part means:

  • res.cookie("token", token, {...}): This sets a cookie in the user’s browser. The cookie is named "token", and it stores the JWT (token).

  • httpOnly: true: This means that the cookie can’t be accessed by JavaScript running in the browser. It’s a security feature to prevent malicious scripts from stealing the token.

  • sameSite: "strict": This helps protect against CSRF (Cross-Site Request Forgery) attacks. It ensures that the cookie is only sent when the user is interacting directly with your site (not when they’re tricked into clicking a link from another site).

  • secure: process.env.NODE_ENV === "production": This ensures that the cookie is only sent over secure HTTPS connections in a production environment. In development, it can be sent over HTTP for testing purposes.

  • maxAge: 7 * 60 * 60 * 1000: This sets the expiration time for the cookie to 7 days, just like the token.

Why is this important?

  • The cookie is where we store the JWT so that the browser can automatically send it with every request. This way, the server always knows who the user is without them needing to log in again on each page load.

If you skip this step:

  • If you don’t set the cookie, the browser won’t store the token, and the user will need to log in again every time they refresh the page or visit a new page on your site. The user’s session won’t persist, and they’ll constantly be "logged out."

The Bigger Picture: Why Use JWT and Cookies for Authentication?

Using JWTs and cookies for authentication has several advantages:

  1. Stateless Authentication: JWTs allow the server to remain stateless. This means the server doesn’t need to store session data for each user. Instead, the JWT is sent with each request, and the server can verify it quickly.

  2. Security: By using a secret key to sign the JWT, the server ensures that the token hasn’t been tampered with. Storing the JWT in a httpOnly cookie adds an extra layer of security, preventing client-side scripts from accessing the token.

  3. Convenience for the User: Once the user is logged in, they don’t need to re-enter their credentials every time they load a new page or revisit the site within 7 days.

What Happens If You Skip JWT Authentication?

Let’s summarize what will happen if you skip generating the token or setting it in a cookie:

  1. No Token: If you don’t generate a JWT, the server won’t know who the user is after they log in. As a result, the user won’t be able to access parts of the site that require authentication (like viewing their profile or performing actions as a logged-in user).

  2. No Cookie: Even if the token is generated, if it’s not stored in a cookie, the browser won’t remember it. The user will lose their authentication state after refreshing the page or visiting a new page, and they’ll be treated as if they’re logged out.

Conclusion

In this post, we’ve explored the basics of JWTs and cookies for user authentication in web applications. The code we discussed helps you:

  • Generate a JWT that proves the user’s identity.
  • Store this token in a cookie so that the user’s browser automatically sends it with every request.

By using JWTs and cookies, you can efficiently and securely manage user sessions, allowing users to stay logged in and access protected areas of your site.

If you’re new to web development, understanding this process is crucial for building secure, scalable, and user-friendly applications. Let me know if you have any questions or if you need further clarification on any part!


Top comments (0)