Key Points
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. HttpOnly
and secure
flags, enabling Session Expiration and Token Refresh, encrypting sensitive data, using SameSite
attributes, and separating authentication and Application status. 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.
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.
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.
There are various types of cookies, each of which is perfect for its intended use case.
<code>名称:_ga 值:GA1.3.210706468.1583989741 域:.example.com 路径:/ 过期/最大年龄:2022-03-12T05:12:53.000Z</code>
// 示例:设置会话 Cookie document.cookie = "sessionID=abc123; path=/";
// 示例:设置具有过期日期的持久性 Cookie document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
document.cookie = "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; path=/";
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 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=/";
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.
As mentioned earlier, cookies are a basic component of web processes and React applications.
How to implement cookies in React include:
document.cookie
APIdocument.cookie
APIThe 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:
// 设置 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);
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");
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");
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.
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.
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 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:
// 示例:设置会话 Cookie document.cookie = "sessionID=abc123; path=/";
Now, configure Express:
// 示例:设置具有过期日期的持久性 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 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 中存储用户偏好设置 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.
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.
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: // 示例:设置会话 Cookie document.cookie = "sessionID=abc123; path=/";
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.
// 示例:设置具有过期日期的持久性 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.
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=/";
SameSite
Properties 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=/";
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, }));
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=/";
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);
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.
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.
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:
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!