JavaScript and React course ยท Module 10: React Ecosystem and Future
Comprehensive Security Practices in React
In this lesson6
A single unchecked comment field is enough for a foreign signal to take over the helm: the attacker pastes HTML with a script, and every passenger's browser runs that script. React application security is several layers of shields, from escaping in JSX, through tokens and dependencies, to the OWASP Top 10 rules.
1. Cross-Site Scripting (XSS)
XSS means injecting a script that runs in the victim's browser. By default React escapes every value in JSX curly braces, turning special HTML characters into safe entities:
// React automatically escapes these values
function UserProfile({ userData }) {
return (
<div>
{/* Safe - React escapes content */}
<h1>{userData.name}</h1>
<p>{userData.description}</p>
{/* DANGEROUS - bypasses escaping */}
<div dangerouslySetInnerHTML={{ __html: userData.bio }} />
</div>
);
}{userData.name} will be displayed as text, even if someone types a <script> tag there. The exception is dangerouslySetInnerHTML, which inserts raw HTML and bypasses this protection.
Sanitization with DOMPurify
When you have to show HTML from an untrusted source, for example content from a text editor, run it through DOMPurify first:
// Safe components with validation
function SafeHTMLRenderer({ content, allowedTags = [] }) {
// DOMPurify library for HTML sanitization
const cleanHTML = DOMPurify.sanitize(content, {
ALLOWED_TAGS: allowedTags,
ALLOWED_ATTR: ['href', 'title', 'alt', 'src'],
ALLOW_DATA_ATTR: false
});
return (
<div dangerouslySetInnerHTML={{ __html: cleanHTML }} />
);
}
// URL validation
function SafeLink({ href, children, ...props }) {
const isValidURL = (url) => {
try {
const urlObj = new URL(url);
// Allow only safe protocols
return ['http:', 'https:', 'mailto:'].includes(urlObj.protocol);
} catch {
return false;
}
};
if (!isValidURL(href)) {
console.warn('Unsafe URL blocked:', href);
return <span>{children}</span>;
}
return (
<a
href={href}
{...props}
rel="noopener noreferrer" // Protection against tabnabbing
>
{children}
</a>
);
}
// Safe image rendering
function SafeImage({ src, alt, ...props }) {
const [imageSrc, setImageSrc] = useState(null);
const [error, setError] = useState(false);
useEffect(() => {
// Validate image source
if (src && typeof src === 'string') {
try {
const url = new URL(src);
if (['http:', 'https:', 'data:'].includes(url.protocol)) {
setImageSrc(src);
} else {
setError(true);
}
} catch {
setError(true);
}
}
}, [src]);
if (error) {
return <div className="image-error">Invalid image source</div>;
}
return imageSrc ? (
<img
src={imageSrc}
alt={alt}
{...props}
onError={() => setError(true)}
/>
) : null;
}The rule is: dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHtml) }}, never raw HTML. You do not need to sanitize plain text from form fields, because React escapes it anyway. SafeLink lets through only the http:, https: and mailto: protocols, and SafeImage checks the image source.
Content Security Policy
The second shield works in the browser: the Content Security Policy header says where scripts, styles and images may be loaded from:
// CSP Header configuration
const cspConfig = {
'default-src': ["'self'"],
'script-src': [
"'self'",
"'unsafe-inline'", // Only in development
'https://apis.google.com',
'https://cdn.jsdelivr.net'
],
'style-src': [
"'self'",
"'unsafe-inline'", // For CSS-in-JS
'https://fonts.googleapis.com'
],
'img-src': [
"'self'",
'data:',
'https:',
'blob:'
],
'font-src': [
"'self'",
'https://fonts.gstatic.com'
],
'connect-src': [
"'self'",
'https://api.example.com',
'wss://socket.example.com'
],
'frame-ancestors': ["'none'"],
'form-action': ["'self'"],
'upgrade-insecure-requests': []
};
// Next.js CSP configuration
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: Object.entries(cspConfig)
.map(([directive, sources]) =>
`${directive} ${sources.join(' ')}`
)
.join('; ')
},
{
key: 'X-Frame-Options',
value: 'DENY'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin'
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()'
}
];
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: securityHeaders
}
];
}
};cspConfig becomes a single header, and headers() in next.config.js adds it to every response. 'unsafe-inline' in script-src disables a large part of the protection, so keep it only in the development environment.
2. JWT Security
A JWT token is a boarding pass, so stealing it means taking over the account. SecureTokenManager shows two ways of storing it, and useAuth checks the token's validity every 5 minutes:
// Secure JWT storage and handling
class SecureTokenManager {
constructor() {
this.tokenKey = 'auth_token';
this.refreshTokenKey = 'refresh_token';
}
// Storage in httpOnly cookies (best approach)
setTokens(accessToken, refreshToken) {
// Send to backend to set httpOnly cookies
fetch('/api/auth/set-tokens', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken, refreshToken })
});
}
// Alternatively - sessionStorage (less secure)
setTokensInStorage(accessToken, refreshToken) {
// NEVER use localStorage for tokens!
sessionStorage.setItem(this.tokenKey, accessToken);
if (refreshToken) {
// Refresh token in a secure location
this.storeRefreshTokenSecurely(refreshToken);
}
}
getToken() {
return sessionStorage.getItem(this.tokenKey);
}
removeTokens() {
sessionStorage.removeItem(this.tokenKey);
sessionStorage.removeItem(this.refreshTokenKey);
// Also logout from cookies
fetch('/api/auth/logout', { method: 'POST' });
}
// Token validation
isTokenValid(token) {
if (!token) return false;
try {
// JWT encodes the payload in base64url, while atob() expects plain base64
const base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(atob(base64));
const now = Date.now() / 1000;
// Check if token has expired
return payload.exp > now;
} catch {
return false;
}
}
// Automatic token refresh
async refreshTokenIfNeeded() {
const token = this.getToken();
if (!token || !this.isTokenValid(token)) {
return await this.refreshToken();
}
return token;
}
async refreshToken() {
try {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
credentials: 'include' // For httpOnly cookies
});
if (response.ok) {
const { accessToken } = await response.json();
sessionStorage.setItem(this.tokenKey, accessToken);
return accessToken;
}
} catch (error) {
console.error('Token refresh failed:', error);
this.removeTokens();
}
return null;
}
}
// Hook for authorization
function useAuth() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const tokenManager = useRef(new SecureTokenManager());
const login = async (credentials) => {
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
});
if (response.ok) {
const { user, accessToken, refreshToken } = await response.json();
// Secure token storage
tokenManager.current.setTokens(accessToken, refreshToken);
setUser(user);
return { success: true };
}
} catch (error) {
return { success: false, error: error.message };
}
};
const logout = () => {
tokenManager.current.removeTokens();
setUser(null);
};
// Automatic token refresh
useEffect(() => {
const interval = setInterval(async () => {
await tokenManager.current.refreshTokenIfNeeded();
}, 5 * 60 * 1000); // Every 5 minutes
return () => clearInterval(interval);
}, []);
return { user, login, logout, loading };
}The safest option is an httpOnly cookie, which JavaScript cannot read, ideally set by the server right at login. sessionStorage disappears when the tab is closed, but it protects against XSS as poorly as localStorage, because any script from that domain can read both. isTokenValid checks only the expiration date, and only the server verifies the signature.
Axios Interceptors
Interceptors add headers to every request and retry it after refreshing the token:
// Secure Axios configuration
const createSecureAxiosInstance = () => {
const tokenManager = new SecureTokenManager();
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
timeout: 10000,
withCredentials: true // For httpOnly cookies
});
// Request interceptor
axiosInstance.interceptors.request.use(
async (config) => {
const token = await tokenManager.refreshTokenIfNeeded();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Add CSRF token if available
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
if (csrfToken) {
config.headers['X-CSRF-Token'] = csrfToken;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor
axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const newToken = await tokenManager.refreshToken();
if (newToken) {
originalRequest.headers.Authorization = `Bearer ${newToken}`;
return axiosInstance(originalRequest);
} else {
// Redirect to login
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);
return axiosInstance;
};On a 401 status the interceptor refreshes the token and repeats the request only once, which the _retry flag guards. The X-CSRF-Token header defends against CSRF, an attack in which a foreign site sends a request with the victim's cookies. Such a token must come from a cryptographically secure generator, like crypto.getRandomValues(), never from Math.random(), and the server compares it with the value stored in the session.
3. Environment Variables
The .env.example file shows the team which variables the project needs, without real values:
# .env.example - a template for the team, without real values
# Secrets such as API_SECRET_KEY or DATABASE_URL never go into this file
# or into REACT_APP_ variables, because the browser will see those
REACT_APP_API_URL=https://api.example.com
REACT_APP_ENVIRONMENT=development
REACT_APP_SENTRY_DSN=your_sentry_dsn_hereEverything with the REACT_APP_ prefix ends up in the JavaScript bundle, so every user can read it, and secrets stay on the server. The prefix comes from Create React App, which the React team deprecated in 2025. In Vite the equivalent is VITE_, in Next.js NEXT_PUBLIC_, and the rule stays the same.
EnvironmentValidator checks at startup whether the required variables exist and aborts the launch when something is missing:
// Environment variable validation
class EnvironmentValidator {
static requiredVars = [
'REACT_APP_API_URL',
'REACT_APP_ENVIRONMENT'
];
static validate() {
const missing = this.requiredVars.filter(
varName => !process.env[varName]
);
if (missing.length > 0) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}`
);
}
}
static get(key, defaultValue = null) {
const value = process.env[key];
if (!value && defaultValue === null) {
console.warn(`Environment variable ${key} is not set`);
}
return value || defaultValue;
}
static getSecure(key) {
const value = process.env[key];
if (!value) {
throw new Error(`Secure environment variable ${key} is required`);
}
return value;
}
}
// Application configuration
const appConfig = {
apiUrl: EnvironmentValidator.getSecure('REACT_APP_API_URL'),
environment: EnvironmentValidator.get('REACT_APP_ENVIRONMENT', 'development'),
isDevelopment: process.env.NODE_ENV === 'development',
isProduction: process.env.NODE_ENV === 'production',
// Helper functions
get isSecure() {
return this.apiUrl.startsWith('https://');
},
get shouldEnableDevTools() {
return this.isDevelopment && !this.isProduction;
}
};
// Validation at application startup
EnvironmentValidator.validate();An error at startup is better than an application that silently sends requests to undefined. getSecure throws an exception, while get only warns and returns a default value.
ConfigProvider splits settings by environment: debugging, log level and mocks:
// ConfigProvider.jsx
const ConfigContext = createContext();
export function ConfigProvider({ children }) {
const config = useMemo(() => {
const baseConfig = {
apiUrl: process.env.REACT_APP_API_URL,
environment: process.env.REACT_APP_ENVIRONMENT,
version: process.env.REACT_APP_VERSION || '1.0.0'
};
// Environment-specific configuration
const environmentConfigs = {
development: {
debug: true,
logLevel: 'debug',
enableMocks: true
},
staging: {
debug: true,
logLevel: 'info',
enableMocks: false
},
production: {
debug: false,
logLevel: 'error',
enableMocks: false
}
};
return {
...baseConfig,
...environmentConfigs[baseConfig.environment] || environmentConfigs.production
};
}, []);
return (
<ConfigContext.Provider value={config}>
{children}
</ConfigContext.Provider>
);
}
export const useConfig = () => {
const context = useContext(ConfigContext);
if (!context) {
throw new Error('useConfig must be used within ConfigProvider');
}
return context;
};An unknown environment gets the production configuration, which is the safest one: no debugging and no mocks.
4. Dependency Scanning
The weakest link is often someone else's code. The scripts in package.json run a vulnerability audit and a license check:
// package.json scripts for security
{
"scripts": {
"audit": "npm audit",
"audit:fix": "npm audit fix",
"audit:force": "npm audit fix --force",
"security:check": "npm audit && npm run license:check",
"license:check": "license-checker --summary",
"deps:update": "npm-check-updates -u",
"deps:check": "npm outdated"
},
"devDependencies": {
"license-checker": "^25.0.1",
"npm-check-updates": "^23.1.0",
"audit-ci": "^7.1.0"
}
}npm audit compares your dependencies against a database of known vulnerabilities. Be careful with npm audit fix --force, because it can bump major versions and break the application.
It is worth running the same checks automatically on every push and pull request:
# .github/workflows/security.yml
name: Security Checks
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write # CodeQL uploads results to the Security tab
steps:
- uses: actions/checkout@v7
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: javascript-typescript
- name: Setup Node.js
uses: actions/setup-node@v7
with:
node-version: 'lts/*'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run npm audit
run: npm audit --audit-level high
- name: Check for known vulnerabilities
run: npx audit-ci --high
- name: License compliance check
run: npm run license:check
- name: SAST with CodeQL
uses: github/codeql-action/analyze@v4
- name: Dependency Review
uses: actions/dependency-review-action@v5
if: github.event_name == 'pull_request'The pipeline will stop on a high-level vulnerability, and dependency-review-action will check new dependencies in the pull request. CodeQL works in two steps: init prepares the analysis, and analyze scans the code and uploads the results, for which the job needs the security-events: write permission. node-version: 'lts/*' picks the current LTS version of Node.js, and Dependabot can bump the action versions (package-ecosystem: github-actions).
SecurityMonitor listens in the browser for securitypolicyviolation events, meaning CSP violations, and reports them to the server:
// SecurityMonitor.jsx
class SecurityMonitor {
constructor() {
this.violations = [];
this.init();
}
init() {
// Monitor CSP violations
document.addEventListener('securitypolicyviolation', (e) => {
this.reportViolation({
type: 'CSP_VIOLATION',
directive: e.violatedDirective,
blockedURI: e.blockedURI,
documentURI: e.documentURI,
timestamp: new Date().toISOString()
});
});
// Monitor console.error for potential security issues
const originalError = console.error;
console.error = (...args) => {
const message = args.join(' ');
if (this.isSecurityRelated(message)) {
this.reportViolation({
type: 'SECURITY_ERROR',
message,
timestamp: new Date().toISOString()
});
}
originalError.apply(console, args);
};
}
isSecurityRelated(message) {
const securityKeywords = [
'unsafe-inline',
'unsafe-eval',
'xss',
'csrf',
'cors',
'unauthorized',
'forbidden'
];
return securityKeywords.some(keyword =>
message.toLowerCase().includes(keyword)
);
}
reportViolation(violation) {
this.violations.push(violation);
// Send to monitoring system
if (process.env.NODE_ENV === 'production') {
fetch('/api/security/violations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(violation)
}).catch(error => {
console.error('Failed to report security violation:', error);
});
}
}
getViolations() {
return [...this.violations];
}
}
// Hook for security monitoring
export function useSecurityMonitor() {
const monitor = useRef(new SecurityMonitor());
const reportCustomViolation = useCallback((violation) => {
monitor.current.reportViolation({
type: 'CUSTOM_VIOLATION',
...violation,
timestamp: new Date().toISOString()
});
}, []);
return {
reportViolation: reportCustomViolation,
getViolations: () => monitor.current.getViolations()
};
}You will learn about a blocked script before a user reports it. Overriding console.error is a global intervention, though, so use it carefully.
5. Data Validation and Sanitization
InputValidator checks required fields, length and patterns, and SecureForm validates fields as they are typed and cleans the values before sending:
// InputValidator.js
class InputValidator {
static patterns = {
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
phone: /^\+?[\d\s\-\(\)]+$/,
url: /^https?:\/\/.+/,
alphanumeric: /^[a-zA-Z0-9]+$/,
noSpecialChars: /^[a-zA-Z0-9\s\-_]+$/
};
static validate(value, rules) {
const errors = [];
// Required validation
if (rules.required && (!value || value.trim() === '')) {
errors.push('This field is required');
}
if (!value) return errors;
// Length validation
if (rules.minLength && value.length < rules.minLength) {
errors.push(`Minimum length is ${rules.minLength} characters`);
}
if (rules.maxLength && value.length > rules.maxLength) {
errors.push(`Maximum length is ${rules.maxLength} characters`);
}
// Pattern validation
if (rules.pattern && !this.patterns[rules.pattern]?.test(value)) {
errors.push(`Invalid ${rules.pattern} format`);
}
// Custom validation
if (rules.custom) {
const customError = rules.custom(value);
if (customError) errors.push(customError);
}
// XSS prevention
if (rules.preventXSS && this.containsPotentialXSS(value)) {
errors.push('Input contains potentially dangerous content');
}
return errors;
}
static containsPotentialXSS(value) {
const xssPatterns = [
/<script[^>]*>.*?<\/script>/gi,
/javascript:/gi,
/on\w+\s*=/gi,
/<iframe[^>]*>/gi,
/<object[^>]*>/gi,
/<embed[^>]*>/gi,
/eval\s*\(/gi,
/expression\s*\(/gi
];
return xssPatterns.some(pattern => pattern.test(value));
}
static sanitize(value, options = {}) {
if (!value) return value;
let sanitized = value;
// Remove HTML tags
if (options.stripHTML) {
sanitized = sanitized.replace(/<[^>]*>/g, '');
}
// Escape HTML entities
if (options.escapeHTML) {
sanitized = sanitized
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Remove null bytes
sanitized = sanitized.replace(/\0/g, '');
// Trim whitespace
if (options.trim !== false) {
sanitized = sanitized.trim();
}
return sanitized;
}
}
// SecureForm component
function SecureForm({ onSubmit, children }) {
const [formData, setFormData] = useState({});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const validateField = useCallback((name, value, rules) => {
const fieldErrors = InputValidator.validate(value, rules);
setErrors(prev => ({
...prev,
[name]: fieldErrors.length > 0 ? fieldErrors : undefined
}));
return fieldErrors.length === 0;
}, []);
const handleInputChange = useCallback((name, value, rules) => {
// Keep the raw text: React escapes it when rendering
setFormData(prev => ({
...prev,
[name]: value
}));
// Validate on change
validateField(name, value, rules);
}, [validateField]);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
// Validate all fields with the rules stored in the children
let isValid = true;
const newErrors = {};
React.Children.forEach(children, child => {
if (!React.isValidElement(child) || !child.props.name) return;
const fieldName = child.props.name;
const fieldErrors = InputValidator.validate(formData[fieldName], child.props.validationRules || {});
if (fieldErrors.length > 0) {
newErrors[fieldName] = fieldErrors;
isValid = false;
}
});
setErrors(newErrors);
if (isValid) {
// Trim values and remove null bytes only before sending
const cleanData = Object.fromEntries(
Object.entries(formData).map(([key, value]) => [key, InputValidator.sanitize(value)])
);
try {
await onSubmit(cleanData);
} catch (error) {
console.error('Form submission failed:', error);
}
}
setIsSubmitting(false);
};
return (
<form onSubmit={handleSubmit}>
{React.Children.map(children, child => {
if (React.isValidElement(child) && child.props.name) {
return React.cloneElement(child, {
value: formData[child.props.name] || '',
onChange: (e) => handleInputChange(
child.props.name,
e.target.value,
child.props.validationRules
),
error: errors[child.props.name],
disabled: isSubmitting
});
}
return child;
})}
</form>
);
}SecureForm keeps the raw text in state, because React escapes it when rendering, and escaping entities on every keystroke would corrupt the typed text: & would turn into &, and after the next character into &amp;. sanitize trims the values only before sending, and escapeHTML is useful only when the text goes into HTML outside React. Validation in the browser improves convenience but does not secure anything, because an attacker will send the request bypassing the form. The server must check the data again, and treat the expressions from containsPotentialXSS as a signal, not a shield.
6. OWASP Top 10
Finally, a checklist based on the OWASP Top 10:2025, the most popular ranking of web application risks. The code shows selected categories in ranking order:
// OWASP Top 10:2025 checklist (selected categories)
// A01:2025 Broken Access Control - the UI hides views, but the server checks permissions
function ProtectedRoute({ children, requiredRole, requiredPermissions }) {
const { user, hasRole, hasPermissions } = useAuth();
if (!user) {
return <Navigate to="/login" replace />;
}
if (requiredRole && !hasRole(requiredRole)) {
return <div>Access Denied: Insufficient role</div>;
}
if (requiredPermissions && !hasPermissions(requiredPermissions)) {
return <div>Access Denied: Insufficient permissions</div>;
}
return children;
}
// A02:2025 Security Misconfiguration - headers, CORS and the XML parser (XXE)
const SecurityConfig = {
securityHeaders: {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '0',
'Referrer-Policy': 'strict-origin-when-cross-origin'
},
corsConfig: {
origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
credentials: true,
optionsSuccessStatus: 200
},
// The browser's DOMParser does not fetch external XML entities
parseXMLSafely: (xmlString) => {
const doc = new DOMParser().parseFromString(xmlString, 'text/xml');
if (doc.querySelector('parsererror')) {
throw new Error('Invalid XML format');
}
return doc;
}
};
// A03:2025 Software Supply Chain Failures - npm ci, npm audit and dependency review from section 4
// A04:2025 Cryptographic Failures - randomness from Web Crypto, data encryption on the server
const CryptoPractices = {
// Token from a cryptographically secure generator, never from Math.random()
randomToken: (bytes = 32) => {
const values = crypto.getRandomValues(new Uint8Array(bytes));
return Array.from(values, (b) => b.toString(16).padStart(2, '0')).join('');
}
};
// A05:2025 Injection - data kept apart from the query, never concatenated into SQL text
const InjectionPrevention = {
// Always use prepared statements (backend code)
safeQuery: (query, params) => {
return db.prepare(query).run(params);
},
// Parameter validation
validateParams: (params, schema) => {
return schema.validate(params);
}
};
// A07:2025 Authentication Failures - password rules according to NIST SP 800-63B
const AuthenticationSecurity = {
passwordPolicy: {
minLength: 15, // 8 if the account has MFA
maxLength: 64, // allow long passphrases
checkBreachedPasswords: true, // reject breached and most common passwords
requireCharacterMix: false, // no forced uppercase letters or special characters
forcePeriodicChange: false // change the password only after a suspected breach
},
// Limit failed login attempts
loginAttempts: {
maxAttempts: 5,
lockoutDuration: 15 * 60 * 1000 // 15 minutes
},
// Session in a cookie
sessionConfig: {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 30 * 60 * 1000 // 30 minutes
}
};The full OWASP Top 10:2025 list is A01 Broken Access Control, A02 Security Misconfiguration, A03 Software Supply Chain Failures, A04 Cryptographic Failures, A05 Injection, A06 Insecure Design, A07 Authentication Failures, A08 Software or Data Integrity Failures, A09 Security Logging and Alerting Failures and A10 Mishandling of Exceptional Conditions. XSS from the first section belongs to A05, and SecurityMonitor from the dependencies section is an example of A09. We set X-XSS-Protection to 0, because the outdated browser filter could create new vulnerabilities, and MDN recommends CSP instead. An encryption key in frontend code is not a secret, so encrypting sensitive data belongs on the server, and the browser takes random values from the Web Crypto API. The password rules follow NIST SP 800-63B (revision 4 from 2025), which OWASP refers to: length and rejecting breached passwords are what counts, and NIST forbids forcing special characters and periodic password changes.
Security covers all layers, from the client to the server, and requires regular audits and up-to-date dependencies. I recommend starting with three steps: DOMPurify for every piece of raw HTML, httpOnly cookies and an automatic audit in CI. They will all return in the Security Operations Center exercise.
Remember: each layer is a separate shield of the ship - React escapes, CSP filters, and the server checks everything once more.
Code for this lesson: App.jsx
import React, { useState, useRef } from 'react';
// Demonstration of security practices in React
// XSS protection, HTML sanitization and input validation
function XSSDemo() {
const [userInput, setUserInput] = useState('');
const [messages, setMessages] = useState([
{ id: 1, text: 'Welcome aboard the station!', author: 'Captain' },
{ id: 2, text: 'Defense systems active.', author: 'Officer' },
]);
const nextId = useRef(3);
// React automatically escapes JSX content - protection against XSS
const maliciousInput = '<script>alert("hack!")<\/script><img src=x onerror=alert(1)>';
const addMessage = () => {
if (userInput.trim()) {
setMessages(prev => [...prev, {
id: nextId.current++,
text: userInput, // React safely escapes this data
author: 'User',
}]);
setUserInput('');
}
};
return (
<div style={styles.panel}>
<h2 style={styles.heading}>1. XSS Protection</h2>
<div style={{ marginBottom: '16px' }}>
<h4 style={styles.subheading}>Malicious input (automatically escaped):</h4>
<div style={{ background: '#0d1b2a', padding: '12px', borderRadius: '8px', color: '#ff6b6b', fontFamily: 'monospace', fontSize: '13px', wordBreak: 'break-all' }}>
{maliciousInput}
</div>
<p style={{ color: '#00ff88', fontSize: '13px' }}>
React renders this as text, not as HTML - the script will not run!
</p>
</div>
<div>
<h4 style={styles.subheading}>Safe space station chat:</h4>
<div style={{ background: '#0d1b2a', padding: '12px', borderRadius: '8px', maxHeight: '150px', overflowY: 'auto', marginBottom: '8px' }}>
{messages.map(msg => (
<div key={msg.id} style={{ marginBottom: '8px' }}>
<span style={{ color: '#00d4ff', fontWeight: 'bold' }}>{msg.author}: </span>
<span style={{ color: '#e0e1dd' }}>{msg.text}</span>
</div>
))}
</div>
<div style={{ display: 'flex', gap: '8px' }}>
<input
value={userInput}
onChange={e => setUserInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && addMessage()}
placeholder="Type a message (try HTML/script)..."
aria-label="Type a message (try HTML/script)..."
style={{ flex: 1, minWidth: 0, padding: '8px 12px', borderRadius: '8px', border: '1px solid #415a77', background: '#0d1b2a', color: '#e0e1dd' }}
/>
<button onClick={addMessage} style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', background: '#00d4ff', color: '#0d1b2a', fontWeight: 'bold', cursor: 'pointer' }}>
Send
</button>
</div>
</div>
</div>
);
}
function DangerousHTMLDemo() {
const [showComparison, setShowComparison] = useState(false);
const safeHTML = '<strong>Important message</strong> from the <em>space</em> station';
const unsafeHTML = '<img src=x onerror="alert(1)"><b>Dangerous HTML</b>';
// Simplified filter: keeps a few tags without any attributes (including onerror, onclick)
// and removes the rest. For demonstration only - in an app use DOMPurify.sanitize()
const sanitize = (html) => {
const allowedTags = ['b', 'i', 'em', 'strong', 'p', 'br', 'span'];
return html.replace(/<(\/?)([a-zA-Z]+)[^>]*>/g, (match, slash, tag) =>
allowedTags.includes(tag.toLowerCase()) ? `<${slash}${tag.toLowerCase()}>` : ''
);
};
return (
<div style={{ ...styles.panel, marginTop: '16px' }}>
<h2 style={styles.heading}>2. dangerouslySetInnerHTML</h2>
<div style={{ display: 'grid', gap: '12px' }}>
<div style={styles.box}>
<h4 style={{ color: '#ff6b6b', margin: '0 0 8px' }}>Dangerous usage:</h4>
<code style={{ color: '#778da9', fontSize: '13px' }}>
{'dangerouslySetInnerHTML={{ __html: userInput }}'}
</code>
<p style={{ color: '#ff6b6b', fontSize: '13px', margin: '8px 0 0' }}>
Never use it with untrusted data!
</p>
</div>
<div style={styles.box}>
<h4 style={{ color: '#00ff88', margin: '0 0 8px' }}>Safe - after sanitization:</h4>
<div style={{ color: '#e0e1dd', marginBottom: '8px' }} dangerouslySetInnerHTML={{ __html: sanitize(safeHTML) }} />
<code style={{ color: '#778da9', fontSize: '12px', display: 'block' }}>
{'dangerouslySetInnerHTML={{ __html: sanitize(html) }}'}
</code>
<p style={{ color: '#ffd166', fontSize: '12px', margin: '8px 0 0' }}>
The sanitize function in this example is a simplification. In a real app use DOMPurify.sanitize(), which knows the pitfalls of the HTML parser.
</p>
</div>
</div>
<button
onClick={() => setShowComparison(visible => !visible)}
style={{ marginTop: '12px', padding: '8px 16px', borderRadius: '8px', border: '1px solid #415a77', background: 'transparent', color: '#778da9', cursor: 'pointer' }}
>
{showComparison ? 'Hide the sanitization comparison' : 'Show the sanitization comparison'}
</button>
{showComparison && (
<div style={{ ...styles.box, marginTop: '12px' }}>
<p style={{ color: '#778da9', margin: '0 0 4px', fontSize: '13px', wordBreak: 'break-all' }}>Before: {unsafeHTML}</p>
<p style={{ color: '#00ff88', margin: 0, fontSize: '13px', wordBreak: 'break-all' }}>After sanitization: {sanitize(unsafeHTML)}</p>
</div>
)}
</div>
);
}
// Password strength according to NIST SP 800-63B: length and rejecting common passwords matter, not forced special characters
const COMMON_PASSWORDS = ['123456', 'password', 'qwerty', 'letmein', 'admin123'];
function passwordStrength(password) {
if (COMMON_PASSWORDS.includes(password.toLowerCase())) return 0;
if (password.length >= 20) return 4;
if (password.length >= 15) return 3;
if (password.length >= 12) return 2;
if (password.length >= 8) return 1;
return 0;
}
function InputValidationDemo() {
const [email, setEmail] = useState('');
const [emailValid, setEmailValid] = useState(null);
const [password, setPassword] = useState('');
const validateEmail = (value) => {
setEmail(value);
if (!value) { setEmailValid(null); return; }
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
setEmailValid(regex.test(value));
};
const strength = passwordStrength(password);
const isCommon = COMMON_PASSWORDS.includes(password.toLowerCase());
const strengthLabels = ['Very weak', 'Weak', 'Fair', 'Good', 'Strong'];
const strengthColors = ['#ff6b6b', '#ff6b6b', '#ffaa00', '#00d4ff', '#00ff88'];
return (
<div style={{ ...styles.panel, marginTop: '16px' }}>
<h2 style={styles.heading}>3. Input Validation</h2>
<div style={{ marginBottom: '16px' }}>
<label htmlFor="crew-email" style={styles.label}>Crew email:</label>
<input
id="crew-email"
value={email}
onChange={e => validateEmail(e.target.value)}
placeholder="pilot@station.space"
style={{ ...styles.input, borderColor: emailValid === null ? '#415a77' : emailValid ? '#00ff88' : '#ff6b6b' }}
/>
{emailValid !== null && (
<p style={{ color: emailValid ? '#00ff88' : '#ff6b6b', fontSize: '13px', margin: '4px 0 0' }}>
{emailValid ? 'Valid email format' : 'Invalid email format'}
</p>
)}
</div>
<div>
<label htmlFor="crew-password" style={styles.label}>Access password:</label>
<input
id="crew-password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="At least 15 characters, ideally a few words"
style={styles.input}
/>
{password && (
<div style={{ marginTop: '8px' }}>
<div style={{ display: 'flex', gap: '4px', marginBottom: '4px' }}>
{[1, 2, 3, 4].map(level => (
<div key={level} style={{ flex: 1, height: '4px', borderRadius: '2px', background: level <= strength ? strengthColors[strength] : '#415a77' }} />
))}
</div>
<p style={{ color: strengthColors[strength], fontSize: '13px', margin: 0 }}>
{isCommon ? 'This password is on the list of the most common ones - choose another' : `Password strength: ${strengthLabels[strength]} (length: ${password.length})`}
</p>
</div>
)}
<p style={{ color: '#778da9', fontSize: '12px', margin: '8px 0 0' }}>A long phrase of a few words is stronger than a short password with special characters.</p>
</div>
</div>
);
}
const styles = {
panel: { background: '#1b2838', padding: '20px', borderRadius: '12px', border: '1px solid #415a77' },
heading: { color: '#00d4ff', marginTop: 0 },
subheading: { color: '#778da9' },
box: { background: '#0d1b2a', padding: '12px', borderRadius: '8px' },
label: { color: '#778da9', display: 'block', marginBottom: '4px' },
input: { width: '100%', padding: '8px 12px', borderRadius: '8px', border: '1px solid #415a77', background: '#0d1b2a', color: '#e0e1dd', boxSizing: 'border-box' },
};
export default function App() {
return (
<div style={{ background: '#0d1b2a', minHeight: '100vh', padding: '24px 16px', color: '#e0e1dd', fontFamily: 'monospace' }}>
<div style={{ maxWidth: '650px', margin: '0 auto' }}>
<h1 style={{ color: '#00d4ff', textAlign: 'center' }}>Security in React</h1>
<p style={{ color: '#778da9', textAlign: 'center', marginBottom: '24px' }}>
Space station defense systems - security practices
</p>
<XSSDemo />
<DangerousHTMLDemo />
<InputValidationDemo />
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How does React protect against XSS (Cross-Site Scripting) attacks by default?
2. When in React do you NEED to sanitize user input using a library like DOMPurify?
Hands-on tasks in the game
- Horizontal ordering
Arrange the syntax for using DOMPurify to safely render HTML in React:
- Code editor
Secure the panel that shows transmissions from unknown ships. React escapes the message text by itself, because it goes into JSX inside braces. ___BLANK1___: isSafeUrl returns true only for the http:, https: and mailto: protocols (false for javascript:, data: and any other). ___BLANK2___: fill the bytes array with random bytes from the cryptographically secure crypto.getRandomValues (never Math.random), so that a 32-character CSRF token is created. ___BLANK3___: a link that opens in a new tab gets rel with the values noopener and noreferrer. In the preview the link from the unknown ship must be blocked and its text shown as plain text.