Building Secure ReactJS Apps: Mastering Advanced Security Techniques • Jim Manico • GOTO 2024

A deep dive into ReactJS security, this presentation reframes the discussion around leveraging AI for secure code generation. It argues that by creating detailed, specific security prompts, developers can train AI to be an expert security coder, transforming it from a flawed tool into a powerful ally for building robust and secure applications.

6 min read
Building Secure ReactJS Apps: Mastering Advanced Security Techniques • Jim Manico • GOTO 2024
source: https://www.youtube.com/watch?v=BKaxtBSgueQ

The Shift to AI-Powered Secure Development

The era of AI-driven code generation is fundamentally changing software engineering. Raw, untrained prompts often lead to insecure code, but when AI is treated like a junior developer—trained with specific, expert-level security rules—it becomes an incredibly powerful tool. By capturing the knowledge of security architects into detailed, reusable AI prompts, teams can ensure that security best practices are consistently applied, preserving expertise and dramatically increasing development efficiency.

The proposed lifecycle for building secure code with AI is:

  1. Capture Expertise: Define clear, explicit security rules based on expert knowledge.
  2. Create Prompts: Translate these rules into detailed prompts that AI can understand and execute.
  3. Generate & Review: Use the prompts to generate code and review the output.
  4. Iterate & Refine: Continuously improve the prompts based on the AI’s performance to achieve the desired security outcomes.

Beyond security, foundational software design principles should also be enforced via prompts to ensure maintainability:

  • Low Cyclomatic Complexity: For more readable and maintainable code.
  • Low Cognitive Complexity: Avoid “clever” code that is difficult to maintain. As the speaker notes, “clever coders and teams are destructive to the future of your software.”
  • High Cohesion: Ensure modules have well-related responsibilities, making them easier to maintain and less error-prone.

Top 10 React Security Risks & AI-Powered Defenses

The primary security risks in client-side React are exposing sensitive information in the source code (e.g., hardcoded secrets, access control logic) and content injection, commonly known as Cross-Site Scripting (XSS). Here are ten key security domains and the corresponding AI prompts to mitigate them.

1. Cross-Site Scripting (XSS)

React’s JSX automatically escapes content placed within curly braces {} to prevent XSS. However, this protection doesn’t apply to all parts of a component. While children are escaped, component types and props are not, creating potential vulnerabilities.

AI Prompt: “Generate React code that displays user input securely. Ensure the user input is placed inside JSX using curly braces so React automatically escapes the content to stop XSS. Avoid using any other method that bypasses React’s escaping mechanism. The goal is to show exactly what the user typed without allowing any injected scripts or HTML.”

2. Dangerous URLs

A primary way to bypass React’s XSS protection is by injecting javascript: URLs into attributes like href, src, or action. A user-provided URL rendered in an anchor tag can execute malicious code. Client-side validation is crucial, as data from APIs should not be implicitly trusted.

AI Prompt: “Ensure that user-provided URLs are strictly validated for correct syntax and allowed only if they use secure protocols like https. If the URL is not valid or does not use a secure protocol, reject it or replace it with a safe default value. Additionally, sanitize URLs to prevent injection attacks or unsafe characters, especially in attributes like href, src, action, or any other URL-related field.”

3. Rendering Untrusted HTML

To render HTML from a user (e.g., from a WYSIWYG editor), developers must use dangerouslySetInnerHTML. Using this function with raw, unsanitized user input is extremely risky. The correct approach is to sanitize the HTML on the client side before rendering.

AI Prompt: “Avoid using dangerouslySetInnerHTML whenever possible. If its use is absolutely necessary, such as when rendering dynamic HTML, ensure the content is first sanitized using a trusted library like DOMPurify to remove any potentially harmful scripts, unsafe elements, or malicious attributes. Always ensure that only sanitized, safe content is rendered.”

4. Insecure JSON Serialization

Embedding initial state as a JSON object in the HTML (e.g., window.preloadedState) can improve performance but introduces a vulnerability if JSON.stringify is used. An attacker can craft a JSON string that breaks out of the script context. The solution is to use a library that properly serializes JSON for embedding in HTML, such as serialize-javascript.

AI Prompt: “When embedding preloaded JSON into the DOM (e.g., via window.initialState) to save a round trip, do not use JSON.stringify. Instead, ensure the JSON is safely encoded or serialized using a library like serialize-javascript before being embedded in the page.”

5. Dangerous Styles (CSS Injection)

Injecting user-controlled data into styled-components can lead to CSS Injection, a vulnerability that can be used to leak data from the page. Any dynamic value from a user that is used in a style must be escaped.

AI Prompt: “When using dynamic values in React styled-components, ensure that any user-generated or untrusted input is properly escaped using a function like CSS.escape() before it is included in the CSS.”

6. Insecure Native DOM Access with ref

Directly manipulating the DOM using refs (e.g., createRef) bypasses React’s virtual DOM and its built-in security mechanisms. This is considered a “React sin.” While refs are acceptable for reading from the DOM or managing focus, they should not be used to inject content. If you must, only use safe properties like textContent or use a sanitizer.

AI Prompt: “Restrict ref usage to safe operations. Avoid using refs to directly edit the DOM, as this bypasses the virtual DOM and can lead to security risks. If refs are used, they should be for reading from the DOM or for specific use cases like programmatic focus, scrolling, or integrating with third-party libraries that require direct DOM access. Any data written to the DOM via a ref must be sanitized.”

7. Flawed Access Control

Zero access control logic should exist in client-side React. Any UI-hiding logic is easily bypassed by viewing the source or using browser developer tools. All authorization decisions must be enforced on the server. Architecturally, administrative functionality should be in a completely separate application or loaded lazily only after a successful server-side authorization check.

AI Prompt: “Do not rely on client-side code for access control in React. All critical security and access control decisions must be enforced on the server-side, where permissions and roles can be securely validated before returning any sensitive data or UI components to the client.”

8. Vulnerable & Outdated Dependencies

The JavaScript ecosystem is vast, and third-party libraries do not come with a security guarantee. It’s crucial to vet dependencies for known vulnerabilities and unsafe coding patterns (like innerHTML or unvalidated URLs). Use tools like npm audit and retire.js to scan for issues.

AI Prompt: “Ensure that AI-generated React components and any of their dependencies are based on the latest stable versions. When integrating third-party libraries, avoid those that rely on unsafe practices like dangerouslySetInnerHTML, direct DOM manipulation, or handling of unvalidated URLs.”

9. Open Redirects

An open redirect vulnerability occurs when an application redirects to a URL specified by a user. Attackers can use this to create convincing phishing attacks. Instead of trying to validate redirect URLs with complex logic, use a strict allow-list of known, safe destinations.

AI Prompt: “When handling redirects, do not trust user-provided values for the destination. Always validate the destination URL against a strict allow-list of trusted domains or paths within your application before performing the redirect.”

10. Insecure Server-Side Rendering (SSR)

When using SSR, developers might be tempted to construct React templates by concatenating strings with user data, which can lead to template injection vulnerabilities. All data rendered on the server must go through React’s standard, safe rendering mechanisms.

AI Prompt: “When using Server-Side Rendering (SSR) in React, ensure all template construction is secure by strictly validating and sanitizing any data rendered on the server. Avoid dynamically constructing React templates with untrusted data, as this can lead to template injection vulnerabilities.”

Share post

Stay In The Loop! Subscribe to Our Newsletter.

Get updates straight to your inbox. No spam, just useful content.

Recommended for You

Leah Belsky on how AI is transforming education — the OpenAI Podcast Ep. 4

Leah Belsky on how AI is transforming education — the OpenAI Podcast Ep. 4

OpenAI's Head of Education, Leah Belsky, and students Yabsera and Alaap discuss how AI, particularly ChatGPT and its new Study Mode, is transforming education. They cover global adoption, the shift from policing AI to integrating it, its role as a personal tutor for building confidence and skills, and the evolving nature of learning, work, and critical thinking in the age of AI.

Balaji Srinivasan: How AI Will Change Politics, War, and Money

Balaji Srinivasan: How AI Will Change Politics, War, and Money

Technologist Balaji Srinivasan joins a16z's Erik Torenberg and Martin Casado to discuss the limitations and societal impact of AI, framing the conversation around the concept of "Polytheistic AGI"—multiple, culturally-specific AIs—versus a singular, god-like intelligence. They explore the practical system-level constraints on AI, its surprising evolution, the critical role of cryptography in grounding AI in reality, and the future of work and security in an AI-driven world.