Home > Web Front-end > JS Tutorial > Understanding Cookies and Sessions in React

Understanding Cookies and Sessions in React

William Shakespeare
Release: 2025-02-08 10:46:10
Original
267 people have browsed it

Understanding Cookies and Sessions in React

Key Points

  • Cookies and Sessions are critical components in web development and are used to manage user data, authentication, and status. Cookies are small amounts of data chunks stored by a web browser on a user’s device, and Session refers to the time a user browses a website.
  • In React, you can use the document.cookie API, create custom hooks, or use third-party libraries to implement cookies. Session in React can be implemented through server-side session or token-based authentication.
  • Best practices for managing Session and Cookies in React include: Protecting Cookies with HttpOnly and secure flags, enabling Session Expiration and Token Refresh, encrypting sensitive data, using SameSite attributes, and separating authentication and Application status.
  • Third-party libraries such as js-cookies can simplify cookie management in React applications. It is recommended to update dependencies regularly to benefit from security patches and improvements.
  • Regular security audits and testing are essential to ensure application security. Tools and practices such as Content Security Policy (CSP) can be used to reduce security risks.

This article will explore technologies and best practices for implementing cookies and sessions in React.

Cookies and Session are indispensable components of web development. They are the medium for managing user data, authentication, and status.

Cookies are small amounts of data (up to 4096 bytes) stored in the web browser on the user's device. A typical cookie looks like this (this is a Google Analytics — _ga — Cookie):

<code>名称:_ga
值:GA1.3.210706468.1583989741
域:.example.com
路径:/
过期/最大年龄:2022-03-12T05:12:53.000Z</code>
Copy after login
Copy after login
Copy after login
Copy after login

Cookie is just a string with key-value pairs.

"Session" refers to the time the user browses the website. They represent the user's continuous activity over a period of time.

In React, cookies and sessions help us create robust and secure applications.

In-depth basics of cookies and sessions

Understanding the basics of cookies and sessions is the foundation for developing dynamic and user-centric web applications.

This section will explore the concepts of cookies and sessions in a more in-depth way, exploring their types, life cycles, and typical use cases.

Cookie

Cookies mainly maintain state data between the client and the server in multiple requests. Cookies allow you to store and retrieve data from users’ machines, providing a more personalized/seamless browsing experience.

Cookie Type

There are various types of cookies, each of which is perfect for its intended use case.

  1. Session Cookies are temporary and only exist during user sessions. They store brief information, such as items in a shopping cart:
    <code>名称:_ga
    值:GA1.3.210706468.1583989741
    域:.example.com
    路径:/
    过期/最大年龄:2022-03-12T05:12:53.000Z</code>
    Copy after login
    Copy after login
    Copy after login
    Copy after login
  2. Permanence Cookie has an expiration date and will remain on the user's machine for a longer period of time. They are suitable for features like the Remember Me feature:
    // 示例:设置会话 Cookie
    document.cookie = "sessionID=abc123; path=/";
    Copy after login
    Copy after login
    Copy after login

Usercases of cookies in React

  • User authentication. When a user logs in successfully, a session token or JWT (JSON Web Token) is usually stored in a cookie:
    // 示例:设置具有过期日期的持久性 Cookie
    document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
    Copy after login
    Copy after login
    Copy after login
  • User preferences. Cookies usually store user preferences, such as theme selection or language settings, for a better personalized experience.
    document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
    Copy after login
    Copy after login
    Copy after login

Session

Definition and Use

Session represents a logical server-side entity that stores user-specific data during access. Session is closely related to cookies, but is stored in different ways; session identifiers usually store cookies on the client side. (Cookie data is stored on the server.)

Server side and client Session

  • Server-side Session involves storing Session data on the server. Frameworks like Express.js use server-side Session to manage user status:

    // 示例:在 Cookie 中存储用户偏好设置
    document.cookie = "theme=dark; path=/";
    Copy after login
    Copy after login
    Copy after login
  • Client Session. When using client sessions, there is no need to replicate, verify the session, or query the data store between nodes. Although "client Session" may refer to the Session storage information on the client, it usually involves the use of cookies to store Session identifiers:

    // 使用 express-session 中间件
    const express = require('express');
    const session = require('express-session');
    const app = express();
    
    app.use(session({
      secret: 'your-secret-key',
      resave: false,
      saveUninitialized: true,
    }));
    Copy after login
    Copy after login
    Copy after login

Understanding the subtleties of cookies and sessions helps build dynamic and interactive web applications.

The next section will explore the actual implementation of cookies and sessions in React applications.

Implementation Cookies

As mentioned earlier, cookies are a basic component of web processes and React applications.

How to implement cookies in React include:

  • Using document.cookie API
  • Create custom Hook
  • Using third-party libraries

Using document.cookie API

The most basic way to use cookies in React is through the document.cookie API. It provides a simple interface to set, get and delete cookies.

  1. Set Cookies:

    // 示例:在客户端的 Cookie 中存储 Session ID
    document.cookie = "sessionID=abc123; path=/";
    Copy after login
    Copy after login
    Copy after login
  2. Get Cookies:

    // 设置 Cookie 的函数
    const setCookie = (name, value, days) => {
      const expirationDate = new Date();
      expirationDate.setDate(expirationDate.getDate() + days);
    
      document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`;
    };
    
    // 示例:设置一个在 7 天后过期的用户名 Cookie
    setCookie("username", "john_doe", 7);
    Copy after login
    Copy after login
  3. Delete Cookie:

    // 按名称获取 Cookie 值的函数
    const getCookie = (name) => {
      const cookies = document.cookie
        .split("; ")
        .find((row) => row.startsWith(`${name}=`));
    
      return cookies ? cookies.split("=")[1] : null;
    };
    
    // 示例:获取“username” Cookie 的值
    const username = getCookie("username");
    Copy after login

Use custom hooks to handle cookies

Create a custom React Hook to encapsulate cookie-related features so that it can be reused between components:

// 按名称删除 Cookie 的函数
const deleteCookie = (name) => {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
};

// 示例:删除“username” Cookie
deleteCookie("username");
Copy after login

This custom Hook useCookie Returns the current value of the cookie, the function that sets the new value, and the function that deletes the cookie.

Using third-party libraries

Third-party libraries such as js-cookies simplify cookie management in React applications.

  1. Installation library:

    // useCookie.js
    import { useState, useEffect } from "react";
    
    const useCookie = (cookieName) => {
      const [cookieValue, setCookieValue] = useState("");
    
      useEffect(() => {
        const cookie = document.cookie
          .split("; ")
          .find((row) => row.startsWith(`${cookieName}=`));
    
        setCookieValue(cookie ? cookie.split("=")[1] : "");
      }, [cookieName]);
    
      const setCookie = (value, expirationDate) => {
        document.cookie = `${cookieName}=${value}; expires=${expirationDate.toUTCString()}; path=/`;
      };
    
      const deleteCookie = () => {
        document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
      };
    
      return [cookieValue, setCookie, deleteCookie];
    };
    
    // 在 React 组件中的用法
    const [username, setUsername, deleteUsername] = useCookie("username");
    Copy after login
  2. Usage in React components:

    <code>名称:_ga
    值:GA1.3.210706468.1583989741
    域:.example.com
    路径:/
    过期/最大年龄:2022-03-12T05:12:53.000Z</code>
    Copy after login
    Copy after login
    Copy after login
    Copy after login

Using third-party libraries such as js-cookies provides a simple and convenient API for cookie management in React components.

Understanding these different approaches helps us choose the one that best suits the needs and complexity of our React applications.

Implement Session

In React applications, Session works on the server side, while Session identifiers use cookies to work on the client side.

The methods to implement Session include:

  • Server side Session
  • Token-based authentication

Server side Session

Server-side Session involves storing Session data on the server. In React, this means using server-side frameworks like Express.js and Session management middleware.

  1. Set Express.js using express-session: First, install the required package:

    // 示例:设置会话 Cookie
    document.cookie = "sessionID=abc123; path=/";
    Copy after login
    Copy after login
    Copy after login

    Now, configure Express:

    // 示例:设置具有过期日期的持久性 Cookie
    document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
    Copy after login
    Copy after login
    Copy after login

    secret Used to sign Session ID cookies, adding an additional layer of security.

  2. Use Session in routing: After configuring the Session, we can use them in the route:

    document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
    Copy after login
    Copy after login
    Copy after login

    After successfully logging in, user information will be stored in the Session. This information can be accessed by subsequent requests for the /profile route.

Token-based authentication

Token-based authentication is a way to manage sessions in modern React applications. It involves generating a token after successful authentication on the server, sending it to the client, and including it in the header of subsequent requests.

  1. Generate and send tokens: On the server side:

    // 示例:在 Cookie 中存储用户偏好设置
    document.cookie = "theme=dark; path=/";
    Copy after login
    Copy after login
    Copy after login

    The server generates a JWT (JSON Web Token) and sends it to the client.

  2. Include token in the request: On the client (React):

    // 使用 express-session 中间件
    const express = require('express');
    const session = require('express-session');
    const app = express();
    
    app.use(session({
      secret: 'your-secret-key',
      resave: false,
      saveUninitialized: true,
    }));
    Copy after login
    Copy after login
    Copy after login

    The above uses React Context to manage authentication status. The login function updates the status using the received token.

  3. Use tokens in request: With the token, include it in the request's header:

    // 示例:在客户端的 Cookie 中存储 Session ID
    document.cookie = "sessionID=abc123; path=/";
    Copy after login
    Copy after login
    Copy after login

    When requesting with Axios, the token is automatically added to the header.

Both methods help us manage our Session effectively, providing a safe and seamless experience.

Best Practices for Managing Sessions and Cookies in React

Handling Sessions and Cookies in React applications is essential for building secure, user-friendly, and high-performance web applications.

To ensure our React application works correctly, please do the following.

Use HttpOnly and secure Logo protection cookies

Always include the HttpOnly and secure logos where applicable.

  • HttpOnly. This flag prevents attacks on cookies through JavaScript or any other malicious code, reducing the risk of cross-site scripting (XSS) attacks. It ensures that cookies are accessible only by the server:
    <code>名称:_ga
    值:GA1.3.210706468.1583989741
    域:.example.com
    路径:/
    过期/最大年龄:2022-03-12T05:12:53.000Z</code>
    Copy after login
    Copy after login
    Copy after login
    Copy after login
  • secure. This flag ensures that cookies are sent only over Secure Encrypted Connections (HTTPS). It can mitigate the risk of malicious user interception:
    // 示例:设置会话 Cookie
    document.cookie = "sessionID=abc123; path=/";
    Copy after login
    Copy after login
    Copy after login

Implement Session Expiration and Token Refresh

For enhanced security, implement Session Expiration and Token Refresh properties. Refreshing the token regularly or setting the Session expiration time can help mitigate the risk of unauthorized access.

  • Token refresh. Refresh the authentication token to ensure that the user remains authenticated. This is related to applications with longer user sessions.
  • Session Expired. Set a reasonable Session expiration time to limit the duration of the user Session. This helps prevent Session hijacking.
// 示例:设置具有过期日期的持久性 Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
Copy after login
Copy after login
Copy after login

/login The endpoint returns the initial JWT token after successful authentication. /refresh-token The endpoint uses the refresh token to generate a new access token.

Encrypt sensitive data

Avoid storing sensitive information directly in cookies or sessions. To retain sensitive data in inevitable circumstances, encrypt it before storing it. Encryption adds an additional layer of security, making it harder to access sensitive information even if malicious users intercept data:

document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
Copy after login
Copy after login
Copy after login

Using SameSite Properties

The

SameSite attribute helps prevent cross-site request forgery (CSRF) attacks by specifying when cookies are sent together with cross-site requests.

  • Strict. Cookies are sent only in a first-party context, preventing third-party websites from making requests on behalf of users.
    // 示例:在 Cookie 中存储用户偏好设置
    document.cookie = "theme=dark; path=/";
    Copy after login
    Copy after login
    Copy after login
  • Lax. Allow us to send cookies using top-level navigation (such as when clicking a link), but not cross-site POST requests initiated by third-party websites:
    // 使用 express-session 中间件
    const express = require('express');
    const session = require('express-session');
    const app = express();
    
    app.use(session({
      secret: 'your-secret-key',
      resave: false,
      saveUninitialized: true,
    }));
    Copy after login
    Copy after login
    Copy after login

Separate authentication and application status

Avoid storing the entire application state in a cookie or session. Separate authentication data from other application-related states to maintain clarity and minimize the risk of exposure to sensitive information:

// 示例:在客户端的 Cookie 中存储 Session ID
document.cookie = "sessionID=abc123; path=/";
Copy after login
Copy after login
Copy after login

Use third-party libraries for cookie management

Consider using a mature third-party library for cookie management. Library like js-cookie provides a simple and convenient API that abstracts the complexity of the native document.cookie API:

// 设置 Cookie 的函数
const setCookie = (name, value, days) => {
  const expirationDate = new Date();
  expirationDate.setDate(expirationDate.getDate() + days);

  document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`;
};

// 示例:设置一个在 7 天后过期的用户名 Cookie
setCookie("username", "john_doe", 7);
Copy after login
Copy after login

Related updates to dependencies

Keep third-party libraries and frameworks up-to-date to benefit from security patches and improvements. Regular updates to dependencies ensure that our applications are not susceptible to known vulnerabilities.

Test safety measures

Discuss your application regularly for security audits and testing. This includes testing common vulnerabilities such as XSS and CSRF. Consider using security tools and practices such as Content Security Policy (CSP) to reduce security risks.

Summary

Cookies and Session are useful tools for building safe and efficient React applications. They are used to manage user authentication, preserve user preferences, or enable stateful interactions.

By following best practices and using proven libraries, we can create robust and reliable applications that provide a seamless user experience while prioritizing security.

If you like this article, please check out other exciting resources from SitePoint:

  • React performance optimization
  • Best React Chart Library of 2024
  • 6 techniques for conditional rendering in React, with examples

The above is the detailed content of Understanding Cookies and Sessions in React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template