Security: XSS, CSRF, CORS
The same-origin policy and the 4 attacks every frontend developer must know.
Updated
Why a frontend developer needs to know this
Most web attacks exploit the browser and frontend code. You don't have to be a security expert, but you do need to know the 4 big problems and how to defend against them.
Same-origin policy
The browser's core rule: a script from one origin cannot read responses from another origin. Without it, any site you open could read your email from another tab.
The 4 attacks to know
| Attack | What happens | Protection |
|---|---|---|
| XSS | the attacker manages to run JS on your page (through unfiltered input) | escaping on output, no innerHTML with user data, CSP, HttpOnly cookies |
| CSRF | another site sends a request on your behalf, using your cookies | SameSite=Lax, CSRF tokens, checking Origin (Next does this for Server Actions) |
| Clickjacking | your site is put in an invisible iframe and the user clicks without knowing | X-Frame-Options: DENY / CSP frame-ancestors |
| Exposed secrets | API keys end up in the JS bundle | variables without NEXT_PUBLIC_, server-only |
XSS in detail
el.innerHTML = `Hello, ${name}` // ✗ if name = '<img src=x onerror=alert(1)>' → code runs
el.textContent = `Hello, ${name}` // ✓ treated as textReact escapes everything you put in {} automatically. The only open door is dangerouslySetInnerHTML — use it only with trusted HTML (like these lessons' markdown, written by us) or sanitized HTML (DOMPurify).
CORS
CORS (Cross-Origin Resource Sharing) is how a server explicitly allows other origins to read its responses:
Access-Control-Allow-Origin: https://app.com
Important to understand:
- CORS doesn't protect you — it protects the user. The request is sent anyway; the browser just refuses to hand you the response.
- A CORS error is fixed on the server (or with a proxy / Route Handler on the same origin), not in the frontend.
Access-Control-Allow-Origin: *doesn't work together with cookies.
HTTPS
Encrypts the conversation — nobody on the network can read or modify the data. It's automatic on Vercel. Without HTTPS, Secure cookies and many modern APIs (geolocation, service workers) don't work.
Checklist for any project
- Don't use
innerHTML/dangerouslySetInnerHTMLwith user input. - Validate data on the server, not just in the form.
- Check authentication in every Server Action and Route Handler.
- Session cookies:
HttpOnly; Secure; SameSite=Lax. - No secrets in
NEXT_PUBLIC_variables.
Summary
- The same-origin policy isolates sites from each other.
- XSS = foreign code running on your page; CSRF = a request made on your behalf.
- CORS is decided by the server and protects the user.