Web Security Basics Every Frontend Developer Should Know
Security often feels like someone else's job, handled by a dedicated team or a backend engineer. In reality, many of the most common web vulnerabilities live in the frontend or sit right at the boundary between browser and server. If you build interfaces, you make security decisions every day, whether you realize it or not.
This post covers the core threats and the habits that defend against them, with examples relevant to React and Next.js applications.
The mindset: never trust the client
The single most important principle is that anything running in the browser can be inspected and modified by the user. Hidden buttons, disabled fields, and client-side validation are conveniences, not protections.
That means:
Authorization must be enforced on the server. Hiding an admin link does not stop someone from calling the admin endpoint directly.
Validation must be repeated on the server. Client checks improve the experience, but the server decides what is acceptable.
Secrets cannot live in client code. Anything shipped to the browser is public.
Keep this in mind and many vulnerabilities become easier to spot.
Cross-Site Scripting (XSS)
XSS happens when an attacker gets their JavaScript to run in your page, typically through user-generated content that you render without proper handling. Once it runs, it can read data, perform actions as the user, and steal session information.
React helps by escaping values rendered in JSX by default. The danger appears when you bypass that protection.
// Dangerous: renders raw HTML from an untrusted source
<div dangerouslySetInnerHTML={{ __html: comment.body }} />If you need to render rich content, such as a blog post from an editor, follow these practices:
Sanitize the HTML with a well-maintained library like DOMPurify before rendering, and prefer sanitizing on the server when you store it.
Never build HTML strings from user input and insert them with
innerHTML.Validate URLs. A link with a
javascript:scheme can execute code. Allow onlyhttp,https, andmailto.Use a Content Security Policy. A CSP tells the browser which scripts may run, limiting the damage if something slips through.
Cross-Site Request Forgery (CSRF)
CSRF tricks a logged-in user's browser into sending an unwanted request to your site. Because browsers attach cookies automatically, the server may believe the request is legitimate.
Defenses include:
SameSite cookies. Setting
SameSite=LaxorStrictprevents cookies from being sent on most cross-site requests, and is now the default in many browsers.CSRF tokens. Include a unpredictable token in forms and state-changing requests, and verify it on the server.
Check the origin. Verify the
OriginorRefererheader for sensitive actions.Never change state with GET requests. Reserve GET for reading data.
If you use server actions or form handlers in a framework, learn what protections are built in and what remains your responsibility.
Handling authentication and sessions
Where you store a session token matters.
Prefer HttpOnly cookies. JavaScript cannot read them, so an XSS bug cannot trivially steal the token.
Add the Secure flag so cookies travel only over HTTPS.
Avoid storing tokens in localStorage. Any script on the page can read it.
Expire sessions sensibly and invalidate them on logout and password change.
cookies().set("session", token, {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 7,
});For login itself, do not invent your own scheme. Use a proven library or provider, enforce rate limiting on login attempts, and hash passwords with a slow algorithm such as bcrypt or Argon2 on the server.
Injection and unsafe input
Injection attacks occur when untrusted input is interpreted as code or commands. SQL injection is the classic example, but the pattern appears everywhere.
Use parameterized queries or an ORM instead of concatenating strings into SQL.
Validate input with a schema. Libraries like Zod let you define exactly what shape and type you expect, and reject everything else.
Be careful with file uploads. Check type and size, rename files, and never serve uploads from a location where they could execute.
Avoid passing user input to shell commands or
eval.
const Input = z.object({
email: z.string().email(),
age: z.number().int().min(13).max(120),
});
const data = Input.parse(await request.json());Validate on the way in, and encode on the way out. Both matter.
Protect your secrets
A surprising number of breaches start with an API key committed to a public repository or bundled into frontend code.
Keep secrets on the server. In Next.js, only variables prefixed with
NEXT_PUBLIC_are exposed to the browser, so never put a private key under that prefix.Use environment variables, and keep
.envfiles out of version control.Rotate keys if they may have been exposed, and give each key the minimum permissions it needs.
Scan your repository with a secret-detection tool in CI.
If something sensitive was ever pushed, assume it is compromised. Deleting the commit is not enough.
Secure your dependencies
Modern apps include hundreds of packages, and each is part of your attack surface.
Run
npm auditor an equivalent regularly, and act on serious findings.Pin versions with a lockfile and review updates before merging.
Remove dependencies you no longer use.
Be cautious with obscure packages. Check maintenance activity and download history before installing.
Automated tools that open pull requests for updates make this routine rather than a heroic effort.
Useful security headers
A few HTTP headers add inexpensive protection:
Content-Security-Policy restricts where scripts, styles, and other resources can load from.
Strict-Transport-Security forces HTTPS.
X-Content-Type-Options: nosniff stops browsers from guessing file types.
Referrer-Policy limits how much URL information is shared with other sites.
frame-ancestors in your CSP, or
X-Frame-Options, prevents clickjacking by controlling who can embed your pages.
You can add these in your framework configuration or at the proxy layer, then test the result with an online header scanner.
Make security part of the routine
Security works best as a habit rather than a project. A few lightweight practices go a long way:
Add a short security checklist to your pull request template.
Run dependency and secret scanning automatically in CI.
Review any code that handles authentication, payments, or user-generated content more carefully.
Log security-relevant events, and make sure errors do not leak internal details to users.
Apply the principle of least privilege everywhere: to users, services, and API keys.
Final thoughts
You do not need to be a security specialist to prevent the majority of common attacks. Treat the browser as untrusted, enforce rules on the server, escape and sanitize what you render, keep secrets out of client code, and keep your dependencies current. These habits are small, and they protect your users, who are trusting you with their data every time they sign in.