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
andsecure
flags, enabling Session Expiration and Token Refresh, encrypting sensitive data, usingSameSite
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>
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.
-
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>
-
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:
// 示例:設(shè)置會話 Cookie document.cookie = "sessionID=abc123; path=/";
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:
// 示例:設(shè)置具有過期日期的持久性 Cookie document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
- User preferences. Cookies usually store user preferences, such as theme selection or language settings, for a better personalized experience.
document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
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 中存儲用戶偏好設(shè)置 document.cookie = "theme=dark; path=/";
-
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, }));
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.
-
Set Cookies:
// 示例:在客戶端的 Cookie 中存儲 Session ID document.cookie = "sessionID=abc123; path=/";
-
Get Cookies:
// 設(shè)置 Cookie 的函數(shù) const setCookie = (name, value, days) => { const expirationDate = new Date(); expirationDate.setDate(expirationDate.getDate() + days); document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`; }; // 示例:設(shè)置一個在 7 天后過期的用戶名 Cookie setCookie("username", "john_doe", 7);
-
Delete Cookie:
// 按名稱獲取 Cookie 值的函數(shù) 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");
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 的函數(shù) const deleteCookie = (name) => { document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`; }; // 示例:刪除“username” Cookie deleteCookie("username");
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.
-
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");
-
Usage in React components:
<code>名稱:_ga 值:GA1.3.210706468.1583989741 域:.example.com 路徑:/ 過期/最大年齡:2022-03-12T05:12:53.000Z</code>
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.
-
Set Express.js using express-session: First, install the required package:
// 示例:設(shè)置會話 Cookie document.cookie = "sessionID=abc123; path=/";
Now, configure Express:
// 示例:設(shè)置具有過期日期的持久性 Cookie document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
secret
Used to sign Session ID cookies, adding an additional layer of security. -
Use Session in routing: After configuring the Session, we can use them in the route:
document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
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.
-
Generate and send tokens: On the server side:
// 示例:在 Cookie 中存儲用戶偏好設(shè)置 document.cookie = "theme=dark; path=/";
The server generates a JWT (JSON Web Token) and sends it to the client.
-
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, }));
The above uses React Context to manage authentication status. The
login
function updates the status using the received token. -
Use tokens in request: With the token, include it in the request's header:
// 示例:在客戶端的 Cookie 中存儲 Session ID document.cookie = "sessionID=abc123; path=/";
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>
secure
. This flag ensures that cookies are sent only over Secure Encrypted Connections (HTTPS). It can mitigate the risk of malicious user interception:// 示例:設(shè)置會話 Cookie document.cookie = "sessionID=abc123; path=/";
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.
// 示例:設(shè)置具有過期日期的持久性 Cookie document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
/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=/";
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 中存儲用戶偏好設(shè)置 document.cookie = "theme=dark; path=/";
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, }));
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=/";
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:
// 設(shè)置 Cookie 的函數(shù) const setCookie = (name, value, days) => { const expirationDate = new Date(); expirationDate.setDate(expirationDate.getDate() + days); document.cookie = `${name}=${value}; expires=${expirationDate.toUTCString()}; path=/`; }; // 示例:設(shè)置一個在 7 天后過期的用戶名 Cookie setCookie("username", "john_doe", 7);
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
