惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
T
Threatpost
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
O
OpenAI News
P
Palo Alto Networks Blog
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
TaoSecurity Blog
TaoSecurity Blog
量子位
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
Know Your Adversary
Know Your Adversary
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
宝玉的分享
宝玉的分享
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
S
Security @ Cisco Blogs
S
Schneier on Security
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
AWS News Blog
AWS News Blog
IT之家
IT之家
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
H
Heimdal Security Blog
I
Intezer
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
W
WeLiveSecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Frontend Security - What Your Browser Is Quietly Protecting You From
Yogesh Yadav · 2026-04-26 · via DEV Community

The browser is doing more security work than you realize. Here's what happens when you accidentally get in its way.

In this article we'll cover how XSS actually happens in real frontend codebases, how CSRF works and where the browser's default protections break down, how clickjacking works and how one header stops it, what Content Security Policy actually does and how to implement it without breaking your app, and the CORS misconfigurations that create vulnerabilities while feeling like security.


Frontend security has a reputation for being someone else's problem. The backend handles auth, the infrastructure team handles firewalls and the frontend just renders what it's given.

That mindset is expensive.

I've worked on platforms handling more than 10 million active users. At that scale, a single security misconfiguration isn't a bug report - it's an incident. And the uncomfortable truth is that most of the vulnerabilities I've seen on the frontend weren't sophisticated attacks. They were gaps left behind by developers who didn't know the browser was already protecting them and accidentally turned that protection off.

This article is about understanding what the browser does for you by default, so you never accidentally undo it.


XSS - The Attack That Lives in Your Own Code

Cross-Site Scripting is the most common frontend vulnerability. The idea is simple: an attacker finds a way to get malicious JavaScript to run in your page, in your users' browsers, with access to everything your page has access to - cookies, localStorage, DOM, API tokens.

The most important thing to understand about XSS is that it doesn't require a sophisticated attacker. It requires a place in your codebase where user-controlled content is rendered without sanitization.

// This is all it takes
document.getElementById('username').innerHTML = userInput

Enter fullscreen mode Exit fullscreen mode

If userInput contains <script>alert(document.cookie)</script> that script runs. Game over.

Modern frameworks help significantly here. React, Vue, and Angular all escape output by default. When you write {userInput} in JSX, React treats it as text, not HTML. That's the browser's XSS protection working through the framework.

The danger is when you deliberately bypass it:

// This bypasses React's built-in escaping
<div dangerouslySetInnerHTML={{ __html: userContent }} />

Enter fullscreen mode Exit fullscreen mode

dangerouslySetInnerHTML exists for legitimate reasons - rendering rich text, markdown output, CMS content. But every time you use it, you're taking on the responsibility of sanitizing that content yourself.

If you need to render HTML from an untrusted source, sanitize it first:

import DOMPurify from 'dompurify'

const clean = DOMPurify.sanitize(userContent)
// Now safe to render

Enter fullscreen mode Exit fullscreen mode

DOMPurify strips anything that could execute JavaScript while preserving legitimate HTML structure. At scale, this belongs in a shared utility, not copied across components.

The other XSS surface most teams miss: third-party scripts.

Every analytics library, chat widget, and ad script you load is running JavaScript in your page with the same privileges as your own code. If any of those scripts are compromised - through a supply chain attack on the npm package or a hijacked CDN - your users are exposed.

This is where Content Security Policy becomes critical, which we'll cover shortly.


CSRF - The Attack the Browser Already Mostly Fixed

Cross-Site Request Forgery works like this: a user is logged into your platform. They visit a malicious site. That site silently makes a request to your platform's API - a request that carries the user's cookies automatically, because that's how cookies work.

If your API trusts cookie-authenticated requests without verifying their origin, the attacker can perform actions on behalf of the user without them knowing.

The browser has quietly been fixing this for years through the SameSite cookie attribute.

Set-Cookie: session=abc123; SameSite=Lax; Secure; HttpOnly

Enter fullscreen mode Exit fullscreen mode

SameSite=Lax tells the browser: only send this cookie on requests that originate from the same site or on top-level navigation. Cross-site requests from a malicious page won't carry the cookie.

SameSite=Strict is even more restrictive - the cookie won't be sent on any cross-site request, including navigations. Good for sensitive session cookies.

Most modern browsers now default to SameSite=Lax even if you don't set it explicitly. That's the browser protecting you without you asking.

Where this breaks down:

If your frontend and API are on different domains - app.yourplatform.com and api.yourplatform.com - cookie handling gets more complex. Subdomains are generally considered same-site, but cross-domain setups are not.

If you're using token-based auth with the Authorization header instead of cookies, CSRF is largely not your problem. Browsers don't automatically attach Authorization headers to cross-site requests the way they do with cookies.

But if you're mixing both - cookies for session management and tokens for API calls - understand exactly what each request is sending and why.


Clickjacking - The Invisible Iframe Attack

Clickjacking is straightforward in concept. An attacker embeds your platform in an invisible iframe on their site, positioned perfectly over a button the attacker wants you to click. You think you're clicking something on the attacker's page. You're actually clicking something on yours.

On a platform with payment flows, subscription management or any destructive actions, this is a real risk.

One HTTP header stops it entirely:

X-Frame-Options: DENY

Enter fullscreen mode Exit fullscreen mode

Or the more modern equivalent via Content Security Policy:

Content-Security-Policy: frame-ancestors 'none'

Enter fullscreen mode Exit fullscreen mode

DENY means your page cannot be embedded in any iframe, on any site. If you need to allow embedding on specific trusted domains:

Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com

Enter fullscreen mode Exit fullscreen mode

This is one of those protections that takes 30 seconds to implement and eliminates an entire category of attack. There is almost no reason not to have it.


Content Security Policy - The Most Powerful Tool Nobody Uses

CSP is the most underutilized browser security feature in frontend development. It's also the most powerful.

A Content Security Policy is a HTTP header that tells the browser exactly what it's allowed to load and execute on your page. Scripts, styles, images, fonts, iframes - you define the allowlist. Anything not on the list gets blocked.

Content-Security-Policy: 
  default-src 'self';
  script-src 'self' https://cdn.trusted.com;
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self' https://fonts.gstatic.com;
  frame-ancestors 'none'

Enter fullscreen mode Exit fullscreen mode

What this does:

  • default-src 'self' - by default, only load resources from your own domain.
  • script-src 'self' https://cdn.trusted.com - scripts can only come from your domain or this specific CDN. An injected script from anywhere else is blocked by the browser before it executes.
  • frame-ancestors 'none' - replaces X-Frame-Options, prevents clickjacking.

This is your XSS backstop. Even if an attacker injects a script tag into your page, if the script source isn't on your allowlist, the browser won't run it.

Why most teams don't implement it:

CSP is hard to get right, especially on established codebases. Inline scripts, eval usage and dynamically injected styles all conflict with a strict policy. The error messages aren't always helpful.

The right approach is to start in report-only mode:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-violations

Enter fullscreen mode Exit fullscreen mode

This enforces nothing but logs every violation. You can see exactly what your existing codebase would break before you flip the switch. Run it for a few weeks, fix the violations, then move to enforcement.

At scale, CSP is not optional. It's the difference between a contained incident and a platform-wide compromise.


CORS - The Misconfigurations That Feel Like Security

CORS - Cross-Origin Resource Sharing - is widely misunderstood. Most developers encounter it as an error to fix, not a security mechanism to understand.

Here's the core idea: browsers block JavaScript from reading responses from a different origin unless that origin explicitly allows it. CORS headers on the server tell the browser what's permitted.

The misconfig that creates vulnerabilities:

Access-Control-Allow-Origin: *

Enter fullscreen mode Exit fullscreen mode

This tells the browser any site can read responses from your API. For truly public, unauthenticated APIs this is fine. For an API that returns user data or accepts authenticated requests, this is a problem.

An even worse pattern:

// On the server - don't do this
const origin = req.headers.origin
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')

Enter fullscreen mode Exit fullscreen mode

This dynamically reflects whatever origin made the request and allows credentials. Effectively any site can make credentialed requests to your API and read the responses. This defeats the entire purpose of CORS.

The correct approach is an explicit allowlist:

const allowedOrigins = [
  'https://yourplatform.com',
  'https://app.yourplatform.com'
]

const origin = req.headers.origin
if (allowedOrigins.includes(origin)) {
  res.setHeader('Access-Control-Allow-Origin', origin)
}

Enter fullscreen mode Exit fullscreen mode

CORS is not an authentication mechanism. It controls what the browser allows JavaScript to read. It does not stop direct requests made with curl, Postman or server-to-server calls. Your API still needs proper authentication and authorization regardless of CORS configuration.


What Developers Accidentally Break

The browser's security model is opt-out, not opt-in. Most of the protections are on by default. The problems happen when developers don't realize they're turning them off.

Using target="_blank" without rel="noopener"

Opening a link in a new tab with target="_blank" gives the new page a reference back to your page through window.opener. A malicious site opened this way can redirect your original tab.

<!-- Vulnerable -->
<a href="https://external.com" target="_blank">Link</a>

<!-- Safe -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">Link</a>

Enter fullscreen mode Exit fullscreen mode

Modern browsers now default to noopener behavior for target="_blank", but it's still worth being explicit.

Disabling certificate warnings in development

Running your local dev server with a self-signed cert and clicking through browser security warnings trains developers to ignore those warnings. More importantly, configurations that disable certificate validation sometimes make their way into staging or production environments.

Putting secrets in frontend code

API keys, client secrets, internal endpoint URLs - these don't belong in frontend code. They end up in your JavaScript bundle, which is downloaded by every user and readable by anyone who opens DevTools. If a key needs to be kept secret, it belongs on the server.

Using eval() or new Function()

Beyond being a performance issue, eval executes arbitrary strings as JavaScript. If any user-controlled content reaches an eval call, it's an XSS vulnerability. CSP's script-src directive blocks eval by default for exactly this reason.


Final Thoughts

The browser is not your enemy. It's doing a significant amount of security work on your behalf, quietly on every page load. SameSite cookies, CORS restrictions, XSS escaping in frameworks, referrer policies - most of this just works if you don't interfere with it.

The job of a security-conscious frontend engineer is not to implement security from scratch. It's to understand what the browser already does, build on top of it and avoid accidentally disabling it.

At scale, that understanding is the difference between a platform your users can trust and one that's one misconfiguration away from an incident.

Know what the browser does for you. Don't get in its way.


Have thoughts or questions on frontend security? Drop them in the comments, always happy to discuss.

This article is part of the Frontend at Scale series.