Web Security Best Practices 2025: Protecting Your Applications

Most website compromises don't involve brilliant attackers. They come from missing headers, outdated plugins, weak admin passwords, leaked API keys, or forms that trust whatever they receive. The fundamentals have been stable for years, and the tooling keeps improving. This guide walks through the practices we consider the baseline for any modern site or web application in 2025 and beyond, from HTTPS and Content Security Policy to authentication, the OWASP Top 10, supply-chain security, and recovery planning.
Start With HTTPS and HSTS
HTTPS is not optional. Browsers flag HTTP pages as "Not Secure," many modern APIs (service workers, WebAuthn, geolocation) require secure contexts, and without TLS anyone on the network path can read or modify traffic.
Getting a certificate is free and automatic through Let's Encrypt or your host's built-in TLS. The remaining work is making sure HTTPS is always used:
- Redirect all HTTP traffic to HTTPS with a permanent (301) redirect.
- Enable HTTP Strict Transport Security (HSTS) so browsers refuse to connect over HTTP after the first visit.
- Support only TLS 1.2 and 1.3.
- Fix mixed content. Every script, stylesheet, image, and font should load over HTTPS.
On Apache (common on shared hosting), a typical setup in .htaccess looks like this:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</IfModule>
Roll HSTS out carefully. Start with a short max-age (for example, one day), confirm every subdomain works over HTTPS, then raise it. Only add preload and submit to the HSTS preload list once you're sure, because removal from the list is slow.
Set the Essential Security Headers
A handful of response headers block whole classes of attacks for very little effort:
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
Header always set X-Frame-Options "SAMEORIGIN"
</IfModule>
- X-Content-Type-Options: nosniff stops browsers from guessing content types, which prevents some file-upload attacks.
- Referrer-Policy limits how much of your URLs leak to other sites.
- Permissions-Policy disables browser features you don't use.
- X-Frame-Options prevents clickjacking. The modern replacement is the CSP
frame-ancestorsdirective; sending both is fine.
The old X-XSS-Protection header is deprecated and can introduce problems in older browsers. Leave it out or set it to 0.
Content Security Policy Without Breaking Your Site
A Content Security Policy (CSP) tells the browser which sources of scripts, styles, images, frames, and network connections are allowed. If an attacker manages to inject a <script> tag, a good CSP stops it from running. CSP is defense in depth: it doesn't replace output encoding, but it dramatically limits the damage of a mistake.
Allow-listing third parties
Most sites load analytics, reCAPTCHA, fonts, or payment widgets from elsewhere, and each needs an explicit entry. A starting policy for a site using Google Analytics 4 and reCAPTCHA might look like this (shown on several lines for readability; send it as a single header value):
default-src 'self';
script-src 'self' https://www.googletagmanager.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/;
connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com;
img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com;
frame-src https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/;
style-src 'self' https://fonts.googleapis.com;
font-src 'self' https://fonts.gstatic.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self';
upgrade-insecure-requests
Vendors change domains over time, so check each provider's current CSP documentation.
Roll out in report-only mode first
Never ship a strict CSP straight to production. Send it as Content-Security-Policy-Report-Only first. The browser enforces nothing but logs (and optionally reports) every violation, so you can see what would break:
Header always set Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' https://www.googletagmanager.com; report-uri /csp-report"
Watch the console and your report endpoint for a week or two, adjust, then switch to the enforcing Content-Security-Policy header. The newer report-to directive uses the Reporting API; sending both report-uri and report-to gives broader browser coverage.
Nonces, hashes, and strict-dynamic
Domain allow-lists can be bypassed if an allowed domain hosts attacker-controllable scripts. A stronger approach is a "strict" CSP based on nonces or hashes:
- Nonces: the server generates a random value per response, adds it to the header (
script-src 'nonce-R4nd0m'), and puts the same value on each legitimate<script nonce="R4nd0m">tag. Injected scripts don't know the nonce, so they don't run. Nonces require server-side rendering of each response; never reuse a nonce or bake it into a static file. - Hashes: for static sites, list the SHA-256 hash of each inline script (
'sha256-...'). Most build tools can generate these. - 'strict-dynamic': lets a trusted (nonced or hashed) script load further scripts, which makes tag managers and bundlers practical under a strict policy.
Avoid 'unsafe-inline' and 'unsafe-eval' in script-src wherever you can. Also note that a CSP delivered through a <meta> tag can't use frame-ancestors or reporting directives, so prefer the HTTP header.
Authentication Done Right
Passkeys and WebAuthn
Passkeys, built on the WebAuthn standard, are now supported by all major browsers and operating systems. They use public-key cryptography tied to your domain, so they can't be phished, reused, or leaked from your database in a useful form. For new applications, offering passkeys as a sign-in option (alongside a fallback) is the strongest improvement you can make. Well-maintained libraries such as SimpleWebAuthn handle the ceremony details on Node.js; don't implement the protocol from scratch.
Multi-factor authentication
Where passwords remain, offer MFA and require it for administrators. Authenticator apps (TOTP) and security keys are preferable to SMS codes, which are vulnerable to SIM swapping. Provide recovery codes and treat account recovery with the same seriousness as login, since it's a common bypass.
Password storage
Never store passwords in plain text or with fast hashes like MD5 or SHA-256. Use a slow, salted password hashing algorithm:
- Argon2id is the current first choice. OWASP's Password Storage Cheat Sheet lists a minimum configuration of 19 MiB of memory, 2 iterations, and 1 degree of parallelism.
- bcrypt remains acceptable for existing systems, with a work factor of 10 or higher. Be aware that bcrypt only uses the first 72 bytes of input.
import argon2 from "argon2";
export async function hashPassword(plain) {
return argon2.hash(plain, {
type: argon2.argon2id,
memoryCost: 19456, // KiB (19 MiB)
timeCost: 2,
parallelism: 1,
});
}
export async function verifyPassword(hash, plain) {
return argon2.verify(hash, plain);
}
Follow current NIST guidance (SP 800-63B): favor length over composition rules, allow long passphrases and password managers, check new passwords against lists of known-breached passwords, and don't force periodic rotation without cause.
Session cookies
Session cookies should be set with these attributes:
Set-Cookie: __Host-session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=86400
- HttpOnly keeps JavaScript (including injected scripts) from reading the cookie.
- Secure sends it only over HTTPS.
- SameSite=Lax (or
Strict) stops the cookie from being sent on most cross-site requests, a strong CSRF mitigation. - The
__Host-prefix forcesSecure,Path=/, and noDomainattribute, preventing subdomains from overwriting it.
Regenerate the session ID after login, expire sessions on the server side, and invalidate them on logout and password change. Storing long-lived tokens in localStorage is riskier than an HttpOnly cookie, because any XSS can read them.
The OWASP Top 10
The OWASP Top 10 is the most widely used reference for web application risks. The 2021 edition, still the basis of many checklists and audits, lists:
- A01 Broken Access Control
- A02 Cryptographic Failures
- A03 Injection (now including XSS)
- A04 Insecure Design
- A05 Security Misconfiguration
- A06 Vulnerable and Outdated Components
- A07 Identification and Authentication Failures
- A08 Software and Data Integrity Failures
- A09 Security Logging and Monitoring Failures
- A10 Server-Side Request Forgery (SSRF)
OWASP released an updated edition, the Top 10:2025, which reorganizes several categories and gives software supply-chain risks more prominence. Check the official OWASP site for the current wording. The underlying advice hasn't changed much: broken access control remains the category to worry about most. Every request that reads or changes data must check, on the server, that the current user is allowed to touch that specific record. Hiding a button in the UI is not access control.
Cross-site scripting (XSS)
XSS happens when untrusted data ends up in a page as executable code. Defenses:
- Let your framework escape output. React escapes text content by default; the danger zones are
dangerouslySetInnerHTML,hrefvalues built from user input (watch forjavascript:URLs), and direct DOM manipulation. - If you must render user-supplied HTML (rich text, CMS content), sanitize it with a maintained library such as DOMPurify.
- Back it all up with a CSP.
Injection
SQL, NoSQL, and command injection all come from mixing data with code. Use parameterized queries or a query builder/ORM, never string concatenation:
// Vulnerable: user input becomes part of the SQL
// db.query("SELECT * FROM users WHERE email = '" + email + "'");
// Safe: the driver sends the value separately
const result = await db.query("SELECT * FROM users WHERE email = $1", [email]);
Validate input against an expected shape (type, length, format) at the boundary, and avoid passing user input to shell commands at all. For more on query safety and schema design, see our guide to database design and optimization.
Cross-site request forgery (CSRF)
CSRF tricks a logged-in user's browser into sending a request they didn't intend. SameSite cookies stop most of it, but don't rely on them alone. Also:
- Use anti-CSRF tokens for cookie-authenticated, state-changing forms (most frameworks provide them).
- Check the
Originheader, or theSec-Fetch-Siteheader, on state-changing requests and reject cross-site ones. - Never change state on
GETrequests.
Server-side request forgery (SSRF)
SSRF occurs when your server fetches a URL supplied by a user (link previews, webhooks, image imports) and the attacker points it at internal services, such as a cloud metadata endpoint at 169.254.169.254. Mitigations:
- Allow-list the domains you actually need to fetch from.
- Resolve the hostname and reject private, loopback, and link-local IP ranges; re-check after redirects, or disable redirects.
- Run outbound fetchers with minimal network access, and use your cloud provider's hardened metadata options (such as AWS IMDSv2).
Dependency and Supply-Chain Security
Modern applications ship far more third-party code than first-party code, and attackers know it. Compromised npm packages and malicious look-alike packages have been a recurring problem in recent years.
- Commit your lockfile (
package-lock.json,pnpm-lock.yaml, oryarn.lock) and install withnpm ciin CI so builds use exactly the versions you reviewed. - Run
npm auditregularly and in CI.npm audit signaturesverifies registry signatures and provenance attestations where available. - Enable Dependabot (or Renovate) for automated update pull requests and security alerts, and actually review and merge them.
- Be skeptical of new dependencies. Check maintenance activity and watch for typo-squatted names.
- Limit install scripts. Consider
npm install --ignore-scriptswhere feasible, since lifecycle scripts are a common malware vector. - Pin third-party scripts loaded from CDNs with Subresource Integrity (
integrity="sha384-...") when the file is versioned and static.
On WordPress, the same applies to plugins and themes: remove what you don't use and update the rest.
Secrets Management
- Never commit API keys, database passwords, or private keys to Git. Keep
.envfiles in.gitignore, and enable secret scanning (GitHub offers secret scanning and push protection). - Store production secrets in your host's or CI provider's secret store (for example, GitHub Actions encrypted secrets) or a dedicated secrets manager.
- Remember that anything bundled into front-end JavaScript is public. A variable like
VITE_API_KEYends up in the browser. Only publishable keys (such as a reCAPTCHA site key) belong there; secret keys stay on the server. - If a secret leaks, rotate it immediately. Deleting the commit isn't enough, because it may already have been copied.
Rate Limiting and Abuse Protection
Login forms, password reset, contact forms, and APIs all need limits on how often they can be called. Rate limiting slows credential stuffing and brute-force attacks, and protects you from spam and runaway costs.
- Limit by IP and, for login, by account as well.
- Return
429 Too Many Requestswith aRetry-Afterheader. - Add a CAPTCHA after repeated failures, and consider a CDN or WAF for larger-scale abuse.
Our Node.js and Express API guide shows a concrete rate-limiting setup with express-rate-limit.
Logging, Monitoring, and Backups
You can't respond to what you can't see.
- Log security-relevant events: logins (successful and failed), password and MFA changes, permission changes, and admin actions, with timestamps, user IDs, and IP addresses.
- Never log secrets: strip passwords, tokens, session IDs, and full payment details from logs.
- Alert on anomalies such as spikes in failed logins or errors.
- Back up regularly and automatically, keep copies off the server (ideally one that is offline or immutable), and encrypt them.
- Test restores. A backup you've never restored is a hope, not a plan.
- Write a short incident plan covering who to call, how to rotate credentials, and how to notify users.
What Isn't Security
Some common "protections" give a false sense of safety:
- Disabling right-click, text selection, or keyboard shortcuts doesn't protect anything. Your HTML, CSS, and JavaScript are delivered to the browser and can be read with view-source, curl, or a proxy.
- Detecting or blocking DevTools is trivially bypassed and mostly annoys legitimate users.
- Obfuscating JavaScript doesn't hide API keys or business logic.
- Client-side validation alone is a usability feature, not a security control. Every check that matters must be repeated on the server.
Assume anything sent to the browser is public, and anything received from it is untrusted.
Conclusion
Web security isn't a single feature you add at the end; it's a set of habits built into how a site is designed, developed, and maintained. Start with the basics that block the most common attacks (HTTPS, headers, solid authentication, updated dependencies), then layer on CSP, monitoring, and a recovery plan. Security also overlaps with performance work, since trimming third-party scripts helps both; our Core Web Vitals guide covers that side.
If you'd like a second pair of eyes on your site's security setup, or you're planning a new application and want these practices built in from day one, get in touch with our team.
DLN Web Studio
Author


