Security

Website Security: A Practical Guide for Developers (2026)

MZ Maciej Zmitrukiewicz 9 min read

Website security is a core part of development, not a final project task. In 2026, one vulnerability can expose user data, damage search rankings and trust, and create legal liability under GDPR and similar regulations.


Why Website Security Matters More Than Ever

Automated bots scan the internet for known vulnerabilities. A misconfigured server or unpatched dependency can be exploited within minutes of a site going public. The effects of a breach extend beyond the technical damage:

  • SEO impact – Google flags hacked sites with “This site may be hacked” warnings, causing immediate ranking drops and click-through rate collapse
  • User trust – 85% of users abandon a site after a security warning from their browser
  • Legal liability – GDPR, CCPA, and similar regulations impose significant fines for data breaches caused by negligence
  • Business continuity – DDoS attacks, ransomware, and data theft can take a business offline entirely

Security and performance are closely linked: a fast, well-architected site is structurally harder to exploit than a slow, bloated one.


HTTPS – The Non-Negotiable Baseline

HTTPS (HyperText Transfer Protocol Secure) encrypts communication between a visitor’s browser and your server using TLS (Transport Layer Security). Treat it as a baseline for every site.

Without HTTPS, visitors may see browser warnings and data is sent without encryption:

  • Browsers display a “Not Secure” warning in the address bar
  • Google applies a direct ranking penalty
  • Any data transmitted (passwords, form inputs, payment details) is sent in plain text and can be intercepted

Getting HTTPS Right

  • Use a valid SSL/TLS certificate — free certificates are available via Let’s Encrypt
  • Enforce TLS 1.2 as a minimum; prefer TLS 1.3 for all connections
  • Set up automatic certificate renewal to avoid expiry (a leading cause of security warnings)
  • Implement HSTS (HTTP Strict Transport Security) to force all connections over HTTPS:
textStrict-Transport-Security: max-age=31536000; includeSubDomains; preload
  • Redirect all HTTP traffic to HTTPS with a 301 redirect
  • Ensure all resources (images, scripts, fonts) load over HTTPS — mixed content breaks the secure connection

HTTP Security Headers

Security headers tell browsers how to handle a site’s content. They are among the more direct security improvements to implement, yet many production sites still lack them.

Content Security Policy (CSP)

Content Security Policy (CSP) restricts the sources from which a browser can load scripts, styles, images, and other resources. A strict policy can prevent many cross-site scripting (XSS) attacks:

textContent-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;

A strict CSP takes careful review of every resource source, but it can substantially reduce the risk of script injection.

X-Frame-Options

X-Frame-Options controls whether another domain can embed your site in an <iframe>, helping block clickjacking attacks:

textX-Frame-Options: DENY

X-Content-Type-Options

X-Content-Type-Options prevents browsers from guessing a different response type, which can block some injection attacks:

textX-Content-Type-Options: nosniff

Referrer-Policy

Referrer-Policy controls how much referrer information a browser includes in requests, reducing unnecessary data exposure:

textReferrer-Policy: strict-origin-when-cross-origin

Permissions-Policy

Permissions-Policy limits which browser APIs a page can use, including the camera, microphone, and geolocation:

textPermissions-Policy: camera=(), microphone=(), geolocation=()

The OWASP Top 10 – Most Critical Web Vulnerabilities

The OWASP Top 10 lists widely recognized web application security risks. Developers should know the vulnerabilities most relevant to their applications.

RankVulnerabilityWhat It Means
1Broken Access ControlUsers can access data or functions they shouldn’t
2Cryptographic FailuresSensitive data exposed due to weak or missing encryption
3Injection (SQLi, XSS)Malicious code injected into queries or output
4Insecure DesignSecurity flaws baked into the architecture
5Security MisconfigurationDefault credentials, open ports, verbose error messages
6Vulnerable ComponentsOutdated libraries or frameworks with known CVEs
7Authentication FailuresWeak passwords, missing MFA, broken session management
8Software Integrity FailuresUnverified code updates or dependencies
9Logging & Monitoring FailuresBreaches go undetected due to missing logs
10SSRFServer-side requests forged to access internal systems

SQL Injection (SQLi)

SQL injection occurs when an application inserts user input directly into a query. An attacker can then alter the query and manipulate the database.

sql-- Vulnerable query
SELECT * FROM users WHERE username = '$input';

-- Attacker input: ' OR '1'='1
-- Resulting query bypasses authentication entirely:
SELECT * FROM users WHERE username = '' OR '1'='1';

How to Prevent SQL Injection

  • Always use parameterized queries / prepared statements — never concatenate user input into SQL
  • Use an ORM (Object-Relational Mapper) that handles query building safely
  • Apply principle of least privilege — database users should only have the permissions they need
  • Validate and sanitize all user input on the server side (never trust client-side validation alone)

Cross-Site Scripting (XSS)

In an XSS attack, a malicious script is injected into a page and runs in other users’ browsers. It can steal session cookies, redirect people to phishing pages, or act on a user’s behalf.

XSS attacks are commonly grouped into three types:

  • Stored XSS – malicious script saved in the database and served to all visitors
  • Reflected XSS – script injected via URL parameters and reflected back in the response
  • DOM-based XSS – script executed via client-side JavaScript DOM manipulation

How to Prevent XSS

  • Escape all output — encode user-supplied data before rendering it in HTML
  • Implement a strict Content Security Policy to block inline script execution
  • Use modern frameworks (React, Svelte, Vue) that escape output by default — but be aware of dangerouslySetInnerHTML and similar escape hatches
  • Set the HttpOnly flag on session cookies to prevent JavaScript access:
textSet-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict

Cross-Site Request Forgery (CSRF)

CSRF uses an authenticated browser to send an unwanted request—for example, to change an email address or make a purchase—without the user’s knowledge.

How to Prevent CSRF

  • Implement CSRF tokens — unique, secret, session-specific tokens included in every state-changing form submission and verified server-side
  • Set the SameSite cookie attribute to Strict or Lax — modern browsers will block cross-origin cookie sending:
textSet-Cookie: sessionId=abc123; SameSite=Strict; Secure; HttpOnly
  • Validate the Origin and Referer headers on sensitive endpoints

Authentication and Session Security

Broken authentication remains a frequently exploited vulnerability category. Secure authentication involves more than choosing a strong password.

Password Security

  • Never store passwords in plain text — always use a strong hashing algorithm (bcrypt, Argon2, scrypt)
  • Enforce minimum password strength requirements
  • Check passwords against known breach databases (Have I Been Pwned API)
  • Implement account lockout after repeated failed login attempts

Multi-Factor Authentication (MFA)

Multi-factor authentication (MFA) is an effective defense against attacks that rely on stolen credentials. Even if a password is compromised, MFA can prevent unauthorized access. Offer:

  • TOTP apps (Google Authenticator, Authy) as the primary MFA method
  • Passkeys / WebAuthn for passwordless authentication — the direction the industry is heading in 2026

Session Management

  • Generate session IDs using a cryptographically secure random number generator
  • Invalidate sessions on logout, password change, and after a period of inactivity
  • Use short session lifetimes for sensitive applications
  • Regenerate session IDs after login to prevent session fixation attacks

Dependency Security

Web applications often depend on hundreds of npm or Composer packages. Each dependency adds code to maintain, and a vulnerable package can expose the application.

Keeping Dependencies Secure

  • Run npm audit or composer audit regularly and fix high/critical vulnerabilities immediately
  • Use Dependabot (GitHub) or Renovate to automate dependency updates
  • Avoid packages with no maintenance activity or a single maintainer with no community oversight
  • Use Subresource Integrity (SRI) for externally hosted scripts and stylesheets:
xml<script src="https://cdn.example.com/library.js"
  integrity="sha384-abc123..."
  crossorigin="anonymous"></script>
  • Pin dependency versions in production and review changes in lockfiles carefully

Security Misconfiguration

The OWASP Top 10 ranks security misconfiguration as the #5 vulnerability category. It can be easy to exploit because attackers often look for defaults that were never changed.

Review common misconfigurations such as:

  • Default credentials – change all default admin usernames and passwords immediately
  • Directory listing – disable it; never expose raw file system structure to the public
  • Verbose error messages – show generic errors to users; log detailed errors server-side only
  • Unnecessary services – disable or block any ports and services not actively needed
  • Development tools in production – never expose phpMyAdmin, debug panels, or .env files publicly
  • Open cloud storage – S3 buckets, Azure blobs, and GCP storage must never be publicly writable

Security Monitoring and Incident Response

Security requires ongoing monitoring. Without visibility into site activity, a breach can remain undetected for months.

What to Monitor

  • Failed login attempts and unusual authentication patterns
  • Unexpected file changes on the server (a core indicator of compromise)
  • Outbound traffic anomalies — a compromised server often calls home
  • Error rates — sudden spikes in 500 errors can indicate an active attack

Tools for Monitoring

  • Google Search Console – alerts you if Google detects hacked content
  • Cloudflare – DDoS protection, WAF (Web Application Firewall), bot management
  • Fail2ban – automatically blocks IPs with repeated failed login attempts
  • OWASP ZAP / Burp Suite – active vulnerability scanning for your own site

Incident Response Plan

Document an incident response plan for any site that handles user data. It should define:

  • Who is notified first in the event of a breach
  • How user data exposure is assessed
  • GDPR-mandated 72-hour notification timeline for reportable breaches
  • Steps to contain, eradicate, and recover from an attack

Website Security Checklist

HTTPS & Transport

  •  Valid SSL/TLS certificate installed and auto-renewing
  •  TLS 1.2+ enforced; TLS 1.3 preferred
  •  HSTS header configured with includeSubDomains
  •  All HTTP traffic redirected to HTTPS with 301
  •  No mixed content warnings

Security Headers

  •  Content Security Policy (CSP) implemented
  •  X-Frame-Options: DENY set
  •  X-Content-Type-Options: nosniff set
  •  Referrer-Policy configured
  •  Permissions-Policy configured

Application Security

  •  All user input validated and sanitized server-side
  •  Parameterized queries used for all database access
  •  Output escaped before rendering in HTML
  •  CSRF tokens on all state-changing forms
  •  Session cookies set with HttpOnly, Secure, SameSite=Strict

Authentication

  •  Passwords hashed with bcrypt or Argon2
  •  MFA available and encouraged
  •  Account lockout after failed login attempts
  •  Sessions invalidated on logout and password change

Dependencies & Configuration

  •  npm audit / composer audit passing with no critical issues
  •  Dependabot or Renovate configured for automated updates
  •  No default credentials in use anywhere
  •  Directory listing disabled
  •  Verbose error messages disabled in production
  •  No .env or config files publicly accessible

Monitoring

  •  Failed login attempts logged and alerted
  •  Web Application Firewall (WAF) in place
  •  Google Search Console monitoring active
  •  Incident response plan documented

Before launch, check the site with Mozilla Observatory and SecurityHeaders.com. Both are free, take about 10 seconds, and return a security grade with specific recommendations. Aim for A+ on both.