Skip to main content
Saved
Guide implementation Intermediate 5 min read

Securing Frontend Data Flows

A defense-in-depth checklist for reducing the risk of client-side injection and protecting your users' data.

The browser is a hostile environment by default. The code on a page comes from many sources, users paste untrusted data into forms, and browser extensions can even change the page after it loads. You don’t control any of this, but it’s still your job to protect your users.

Attacks usually come in through the data your app handles, such as user input, API responses, third-party scripts, and whatever you eventually render to the DOM. This guide shows how to layer your defenses so that when one layer fails, another one can still stop the attack. Each layer has its own pattern in the security patterns collection, so you can add them one at a time.

Map Where Data Enters

Every place where data enters your application is a possible way in for an attacker. You can’t protect data flows you haven’t found yet, so it’s worth mapping them first.

  • List every data entry point: Form inputs, URL parameters, CMS content, and third-party scripts are all potential attack vectors. Anything that a user controls or an external service provides should be checked carefully, and routes that handle money or administrative access need even closer attention.
  • Track where session data is stored: Tokens and user IDs might be in cookies, localStorage, or sessionStorage. Each of these has different security properties, so it’s worth documenting where each piece of sensitive data is stored. Secure Token Storage and SameSite Cookie cover the trade-offs.
  • Document your rendering approach: Server rendering and client-side rendering come with different risks. Any component that writes raw HTML through innerHTML or dangerouslySetInnerHTML needs a careful code review, and Trusted Types can enforce safe rendering across the whole application.

Build Your Defense Layers

Security rarely comes down to a single fix, and it works best as several layers of protection that back each other up.

Layer 1: Content Security Policy (CSP)

Content Security Policy (CSP) is a strong first line of defense. It tells the browser where scripts, styles, and other resources are allowed to load from. A sensible default is default-src 'self', which you can then loosen only where you need to. With violation reporting enabled, the browser sends you a report each time it blocks something that breaks the policy. CSP won’t stop every attack, but it does block many kinds of injection attack before the injected code can run.

If you load scripts from a CDN, you can add Subresource Integrity alongside CSP, so the browser rejects any third-party file that has been tampered with.

Layer 2: Sanitize Inputs, Encode Outputs

Checking data on the way in and again on the way out gives you two chances to stop an attack.

  • On arrival: Input Sanitization strips dangerous HTML tags and attributes as data enters your application, and it’s safest to treat any input that users supply as untrusted by default.
  • On display: Output Encoding escapes special characters before the data is rendered, so <script> becomes &lt;script&gt;, and the browser shows it as text instead of running it. Encoding is the last check before the data goes into the DOM.

Layer 3: Enforce Trusted Types

Trusted Types is a browser feature that blocks dangerous DOM operations unless you explicitly mark data as safe, and it works a lot like a type system. Once you enable it, the browser blocks writes to risky DOM sinks by default. If you create one Trusted Types policy that converts sanitized data into TrustedHTML, the rest of your team has one safe way to write HTML to the page, and developers can’t get around the protection by accident.

Layer 4: Prevent Cross-Site Request Forgery (CSRF)

CSRF Protection stops attackers from tricking authenticated users into making requests they didn’t mean to make. CSRF tokens work alongside SameSite cookies. In a single-page app, each API call that changes state should include a token that expires with the session. You can check the protection by submitting a form without a valid token, and if the request still succeeds, the protection isn’t working.

Protect Data at Rest and in Transit

Securing the way data flows through your app also involves protecting the data you keep.

  • Store tokens deliberately: Secure Token Storage can help you choose between cookies and web storage based on your threat model. Cookies marked HttpOnly and Secure keep tokens where JavaScript can’t read them, so an injected script can do less damage.
  • Minimize what you expose: PII Redaction removes personal data before it’s sent to logs or error trackers.

Make Security Automatic

If a security step depends on someone remembering to do it, it tends to get skipped when the team is under pressure, so it helps to automate as much as you can.

  • Scan dependencies in CI: Your CI pipeline can run npm audit and dependency scanners on every build, and fail the build when a package has a known vulnerability, so you don’t have to rely on someone spotting it later.
  • Add security checks to CI/CD: A linter can flag risky patterns such as dangerouslySetInnerHTML or eval, and tests can check that your sanitizers strip what they’re meant to. The same pipeline can also check that your CSP headers are present. It takes far less effort to catch these issues before the code review than to fix them after a deploy.
  • Track CSP violations and unsafe APIs: Your team can keep a record of which routes produce CSP violations and which components use unsafe APIs. If you watch those counts over time, you can tell whether your fixes are lasting.

Monitor and Improve

Keeping an app secure is ongoing work, because browsers, dependencies, and attacks keep changing.

  • Review security logs regularly: Your CSP violation reports are a good place to start. A sudden spike might mean that a new feature broke something legitimate, or that someone is probing your defenses, and both are worth investigating.
  • Fix vulnerabilities thoroughly: Once you find a security bug, you should look for other variations of it and fix those too. It helps to update sanitizers, encoders, CSP policies, and Trusted Types together, because the same root cause often appears in more than one place.
  • Schedule periodic reviews: Browsers keep adding security features, and new attack vectors keep appearing, so it’s worth revisiting your setup regularly to adopt new protections and check that your existing ones still work.

Defense-in-Depth Checklist

LayerPatternAttacks it stops
Restrict script sourcesContent Security Policy, Subresource IntegrityInjected and tampered scripts
Clean and escape dataInput Sanitization, Output EncodingStored and reflected XSS
Enforce safe DOM sinksTrusted TypesAccidental unsafe rendering
Validate requestsCSRF Protection, SameSite CookieForged state-changing requests
Protect stored dataSecure Token Storage, PII RedactionToken theft and data leakage

Each layer stops a different kind of attack, so if one of them is missing or misconfigured, the others can still protect your users.

Next Guide · 4 min read

Testing Confidence Ladder

Building the test suite for a modern frontend in layers, using unit, integration, visual, and accessibility tests.

Read the next guide →

Keep Exploring

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.