Frontend Security & Correctness 🔐
Secure-by-default habits prevent costly incidents. Treat every UI feature as an attack surface.
1) Preventing XSS 🛑
- Never inject untrusted HTML; prefer plain text rendering.
- If raw HTML is required, sanitize first and use
dangerouslySetInnerHTMLsparingly.
import DOMPurify from "dompurify";
function SafeMarkup({ html }) {
return <article dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />;
}- Escape user-generated content in meta tags, attributes, and URLs.
- Enable Content Security Policy (CSP) headers from the server.
2) CSRF Awareness 🧾
- CSRF targets state-changing requests. Mitigations:
- Use SameSite=Lax or Strict cookies for session tokens.
- Include CSRF tokens in forms or
fetchcalls; store token in meta tag and send via header. - Prefer double-submit or origin checks for critical endpoints.
fetch("/api/update", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify(payload)
});3) Secure Auth Handling 🔑
- Store access tokens in
httpOnlycookies when possible; avoid localStorage for long-lived secrets. - Use short-lived access tokens + refresh tokens; handle refresh in secure endpoints.
- When using OAuth/OpenID, validate issuer, audience, and expiration on the backend.
- Obfuscate sensitive routes until user auth state is confirmed (avoid exposing internal IDs in public bundles).
4) Secrets & Config 🧳
- Never hard-code API keys or credentials in frontend bundles; use environment variables injected at build time for non-secret config only.
- For server actions / RSC, keep secrets on the server layer; client should call through protected APIs.
- Audit
process.envusage to ensure only safe values leak to the browser.
5) Dependency Hygiene 🧼
- Lock dependencies with
package-lock.json/pnpm-lock.yamland review diffs in PRs. - Run
npm audit,yarn npm audit --recursive, or tooling like Snyk/GitHub Dependabot regularly. - Avoid unmaintained packages; pin versions for security-sensitive libs (auth, crypto).
6) Additional Hardening 🧱
- Rate limiting: coordinate with backend to throttle API abuse.
- Feature flags: hide unfinished features server-side so toggling doesn’t expose hidden endpoints.
- Monitoring: log suspicious activity (e.g., repeated 401 responses) via observability tools.
- Secure headers: ensure backend sets HSTS, X-Frame-Options, X-Content-Type-Options.
Key Takeaways ✅
- Sanitize any HTML and prefer text rendering to avoid XSS.
- Guard state-changing requests with CSRF tokens and safe cookies.
- Keep secrets server-side; manage tokens securely.
- Maintain dependency hygiene and monitor for vulnerabilities.
Recap 🔄
Frontend security is layered: treat user content carefully, harden auth flows, keep secrets off the client, and audit dependencies. Combine these with server-side headers and monitoring to deliver trustworthy React apps.
Last updated on