Frontend Security Best Practices for CSRF Protection
To prevent CSRF attacks, the front-end requires cooperation with the back-end. The front-end can enhance protection by: 1. Set the SameSite Cookie attribute to Lax or Strict to limit the automatic sending of cookies in cross-site requests; 2. Avoid sensitive operations using GET requests, and use non-idempotent methods such as POST to prevent induce triggering; 3. When the page is loaded, the Anti-CSRF Token generated by the back-end is obtained and carried in the request header; 4. Use the dual submission cookie mode, the back-end writes the token to the HttpOnly cookie, and puts it in the request header after the front-end reads it, and the back-end verifies consistency. The above measures should be used in combination to improve overall safety.

Preventing CSRF (cross-site request forgery) attacks is a part of front-end security that cannot be ignored. Although the backend plays a core role in defending against such attacks, the frontend can also enhance its protection capabilities through some means. Here are a few practical front-end security practices that can effectively help you reduce CSRF risks.

Use SameSite Cookie Attribute
CSRF attacks usually rely on credentials automatically sent by the user's browser, such as session cookies. Setting SameSite property can limit the sending behavior of cookies in cross-site requests.
- SameSite=Strict : The cookie is not sent in any cross-site request, which is highly secure, but may affect the user experience.
- SameSite=Lax : Allows some secure cross-site requests (such as navigating to the target website), taking into account both security and experience.
- SameSite=None : Must be used with
Secureproperty, suitable for scenarios where cookies are required to be carried across domains, such as embedded iframes.
It is recommended to set authentication-related cookies to SameSite=Lax or Strict as much as possible to reduce the CSRF attack surface.

Avoid designing sensitive operations as GET requests
GET requests are easily triggered, such as clicking through <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/175286847314881.jpg" class="lazy" alt="Frontend Security Best Practices for CSRF Protection" > , <script></script> or links. However, POST, PUT, DELETE and other methods are relatively difficult to forge.
If you have an account deletion operation that is implemented through GET /api/delete-account , then the attacker only needs to induce the user to access an image link:

<img src="/static/imghw/default1.png" data-src="https://your-site.com/api/delete-account" class="lazy" / alt="Frontend Security Best Practices for CSRF Protection" >
You can complete a malicious request. Therefore, all operations involving state changes should be implemented using non-idempotent methods such as POST and avoid exposure to simple URLs.
Add Anti-CSRF Token (combined with backend)
Although the front-end itself cannot generate and verify anti-CSRF tokens separately, it can be fetched from the server when the page is loaded and actively bring it with you in each request.
Common practices include:
- Store the token in a hidden input element or in a JS variable.
- Add this token in the AJAX request header, such as
XSRF-TOKEN. - If you use a framework such as React Axios, you can use an interceptor to handle it uniformly.
Note: The token must be generated, verified by the backend, and cannot be stored in localStorage in case of XSS leak.
Use dual submission cookie mode (suitable for front-end and back-end separation architecture)
This is a solution commonly used in SPA applications, and the process is as follows:
- After the login is successful, the backend writes the CSRF token to an HttpOnly cookie.
- The front-end reads the cookie and places it in the request header (such as
X-CSRF-Token). - The backend simultaneously verifies whether the cookie and the token in the request header are consistent.
The advantage of this method is that it does not require the server to maintain the state of the token, and it can also prevent cross-domain requests.
Note: This method requires that both the front and back ends support CORS and are configured correctly, otherwise the token will not be able to read or send correctly due to cross-domain issues.
The above methods are not used in isolation, but should be combined and applied according to the actual situation of the project. Although Frontend can do CSRF defense, it can significantly improve overall security based on the backend. Basically all this is not complicated but easy to ignore.
The above is the detailed content of Frontend Security Best Practices for CSRF Protection. 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)
How to use del and ins tags in HTML
Aug 12, 2025 am 11:38 AM
Thetagisusedtomarkdeletedtext,optionallywithdatetimeandciteattributestospecifywhenandwhythedeletionoccurred.2.Thetagindicatesinsertedcontent,alsosupportingdatetimeandciteforcontextabouttheaddition.3.Thesetagscanbecombinedtoshowdocumentrevisionsclearl
How to use CSS gradients for backgrounds
Aug 17, 2025 am 08:39 AM
CSSgradientsprovidesmoothcolortransitionswithoutimages.1.Lineargradientstransitioncolorsalongastraightlineusingdirectionsliketobottomorangleslike45deg,andsupportmultiplecolorstopsforcomplexeffects.2.Radialgradientsradiatefromacentralpointusingcircleo
How to use CSS selectors effectively
Aug 11, 2025 am 11:12 AM
When using CSS selectors, low-specific selectors should be used first to avoid excessive limitations; 1. Understand the specificity level and use them reasonably in the order of type, class, and ID; 2. Use multi-purpose class names to improve reusability and maintainability; 3. Use attributes and pseudo-class selectors to avoid performance problems; 4. Keep the selector short and clear scope; 5. Use BEM and other naming specifications to improve structural clarity; 6. Avoid the abuse of tag selectors and:nth-child, and give priority to the use of tool classes or modular CSS to ensure that the style is controllable for a long time.
How can you make an HTML element editable by the user?
Aug 11, 2025 pm 05:23 PM
Yes, you can make HTML elements editable by using the contenteditable attribute. The specific method is to add contenteditable="true" to the target element. For example, you can edit this text, and the user can directly click and modify the content. This attribute is suitable for block-level and in-line elements such as div, p, span, h1 to h6. The default value is "true" to be editable, "false" to be non-editable, and "inherit" to inherit the parent element settings. In order to improve accessibility, it is recommended to add tabindex="0&quo
How to create a responsive testimonial slider with CSS
Aug 12, 2025 am 09:42 AM
It is feasible to create a responsive automatic carousel slider with pure CSS, just combine HTML structure, Flexbox layout, and CSS animation. 2. First build a semantic HTML container containing multiple recommendation terms, each .item contains reference content and author information. 3. Use the parent container to set display:flex, width:300% (three slides) and apply overflow:hidden to achieve horizontal arrangement. 4. Use @keyframes to define a translateX transformation from 0% to -100%, and combine animation: scroll15slinearinfinite to achieve seamless automatic scrolling. 5. Add media
How to use the address tag in HTML
Aug 15, 2025 am 06:24 AM
Thetagisusedtodefinecontactinformationfortheauthororownerofadocumentorsection;1.Useitforemail,physicaladdress,phonenumber,orwebsiteURLwithinanarticleorbody;2.Placeitinsideforauthorcontactorinfordocument-widecontact;3.StyleitwithCSSasneeded,notingdefa
How to create a select dropdown in HTML
Aug 16, 2025 am 05:32 AM
Use and create drop-down menus; 2. Add tags and names with the and name attributes; 3. Set default options with selected attributes; 4. Group options; 5. Add required attributes to achieve required verification; a complete HTML drop-down menu should contain tags, names, options grouping and verification to ensure complete and user-friendly functions.
How to create subscript and superscript in HTML
Aug 20, 2025 am 11:37 AM
TocreatesubscriptandsuperscripttextinHTML,usetheandtags.1.Usetoformatsubscripttext,suchasinchemicalformulaslikeH₂O.2.Usetoformatsuperscripttext,suchasinexponentslike10²orordinalslike1ˢᵗ.3.Combinebothtagswhenneeded,asinscientificnotationlike²³⁵₉₂U.The


