Back to BlogGuides & Tutorials

How to Secure Your Web Application [2026]

Jay PipaliyaPublished July 2, 202620 min read✓ Last Updated: July 2, 2026

Key Takeaways

  • 1Key Takeaways
  • 2Step 1: Secure Authentication and Access Control
  • 3Step 2: Validate and Sanitise All Input
  • 4Step 3: Prevent Injection Attacks
  • 5Step 4: Secure Your APIs

Key Takeaways

  • Web application security follows 7 layers: authentication and access control → input validation and sanitisation → injection prevention → API security → HTTPS and headers → dependency management → monitoring and incident response
  • The OWASP Top 10 covers 90%+ of web application vulnerabilities — addressing these eliminates the vast majority of attack vectors
  • Security is not a feature you add at the end — it must be built into every layer from the start. Fixing a vulnerability in production costs 30x more than preventing it during development
  • The three most common vulnerabilities in Indian web applications: SQL injection (unsanitised database queries), XSS (unsanitised user output), and broken authentication (weak passwords, missing rate limiting)

Every web application is a potential target. In 2026, cyberattacks on Indian businesses increased 35% year-over-year, with web applications being the primary attack vector. Small and medium businesses are disproportionately targeted because they often lack dedicated security teams. The good news: 95% of web application vulnerabilities are preventable with standard security practices. This guide walks you through securing your web application step by step, covering the OWASP Top 10, practical implementation techniques, and a security checklist you can apply to any project — whether you are building with Next.js, Node.js, Python, or any other stack.

Step 1: Secure Authentication and Access Control

Authentication (proving who the user is) and authorisation (controlling what they can access) are the foundation of application security. A breach here compromises everything.

Authentication best practices:

  • Use established authentication libraries: Do not build authentication from scratch. Use NextAuth.js (Next.js), Passport.js (Node.js), Django's auth system (Python), or managed services like Clerk, Auth0, or Firebase Auth. These handle password hashing, session management, token rotation, and edge cases that custom implementations miss.
  • Password security: Hash passwords with bcrypt (cost factor 12+) or Argon2id. Never store plain text or MD5/SHA-256 hashed passwords. Enforce minimum 8-character passwords. Check against breached password databases (Have I Been Pwned API) to prevent users from choosing compromised passwords.
  • Multi-factor authentication (MFA): Implement MFA for admin accounts at minimum, and offer it for all users. TOTP (Google Authenticator, Authy) is the most common implementation. For Indian users, SMS OTP is widely understood and accepted — use it as a second factor despite being less secure than TOTP.
  • Rate limiting: Limit login attempts to 5-10 per minute per IP address and per username. After exceeding the limit, require a CAPTCHA or implement a progressive delay (exponential backoff). This prevents brute-force attacks. Use Redis to track attempt counts with expiring keys.
  • Session management: Use HttpOnly, Secure, SameSite=Lax cookies for session tokens. Set session expiry to 24-72 hours for regular users and 1-4 hours for admin accounts. Implement session revocation — when a user changes their password or reports a security concern, invalidate all existing sessions.
  • JWT best practices: If using JWTs, keep them short-lived (15-60 minutes) with a refresh token mechanism. Store refresh tokens in HttpOnly cookies, never in localStorage (vulnerable to XSS). Validate the JWT signature on every request. Include an audience (aud) and issuer (iss) claim.

Authorisation best practices:

  • Implement role-based access control (RBAC) or attribute-based access control (ABAC). Never rely solely on frontend checks — always enforce permissions on the server.
  • Check authorisation on every API endpoint. A common vulnerability: the frontend hides an "admin" button, but the API endpoint is accessible to anyone who knows the URL. This is Broken Access Control — the #1 vulnerability in OWASP Top 10.
  • Use the principle of least privilege — every user and service should have the minimum permissions needed to perform their function. An API endpoint for reading user profiles should not have write access to billing data.

Step 2: Validate and Sanitise All Input

Never trust any data that comes from outside your application — user input, URL parameters, HTTP headers, cookies, file uploads, and API responses from third-party services. Every piece of external data is a potential attack vector.

Input validation principles:

  • Validate on the server: Client-side validation (JavaScript form validation) improves UX but provides zero security. An attacker can bypass the frontend entirely and send requests directly to your API. Always validate on the server.
  • Whitelist, do not blacklist: Define what valid input looks like (a phone number is 10 digits, an email matches a specific pattern, a name contains only letters and spaces) rather than trying to block malicious patterns. Blacklists always miss edge cases.
  • Use schema validation libraries: Zod (TypeScript), Joi (Node.js), Pydantic (Python), or Yup (JavaScript) provide declarative input validation. Define a schema for every API endpoint's input. Example: z.object({ email: z.string().email(), age: z.number().min(18).max(120) }).
  • Sanitise for context: Sanitise data based on where it will be used. Data displayed in HTML needs HTML entity encoding. Data used in SQL queries needs parameterised queries. Data used in URLs needs URL encoding. There is no universal "sanitise" function — context matters.
  • File upload validation: Validate file type by checking the file's magic bytes (not just the extension — renaming malware.exe to malware.jpg bypasses extension checks). Limit file size. Store uploaded files outside the webroot (never in a publicly accessible directory). Use a dedicated file storage service (AWS S3, Cloudflare R2) with proper access controls. Scan uploaded files for malware if accepting documents.

Step 3: Prevent Injection Attacks

Injection attacks occur when untrusted data is sent to an interpreter as part of a command or query. SQL injection and Cross-Site Scripting (XSS) remain the most prevalent and dangerous web vulnerabilities.

SQL injection prevention:

  • Use parameterised queries (prepared statements): This is the single most important defence against SQL injection. Instead of building SQL strings with user input, use placeholders that the database driver fills safely. Every major database library supports this. ORMs like Prisma, Sequelize, TypeORM, and Django ORM use parameterised queries by default.
  • Use an ORM: ORMs (Prisma for Node.js, Django ORM for Python, ActiveRecord for Ruby) abstract SQL generation and use parameterised queries internally. They also provide input escaping and type checking. Use raw SQL queries only when the ORM cannot express the query — and even then, use the ORM's raw query method with parameter binding.
  • Least privilege database user: Your application's database user should only have the permissions it needs. A web application that reads and writes data should not have permission to DROP tables, CREATE users, or modify the schema. Create a dedicated database user with only SELECT, INSERT, UPDATE, and DELETE on specific tables.

XSS (Cross-Site Scripting) prevention:

  • Output encoding: Encode all user-supplied data before rendering it in HTML. React and Next.js encode output by default through JSX — this is one of React's biggest security advantages. If you use dangerouslySetInnerHTML, you are bypassing this protection and must sanitise manually.
  • Content Security Policy (CSP): Set a CSP header that restricts which scripts can execute on your page. A strict CSP prevents injected scripts from running even if an XSS vulnerability exists. Start with: Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' and refine from there.
  • Sanitise rich text input: If your application accepts rich text (HTML) from users (comments, blog posts, forum messages), sanitise it with a library like DOMPurify (client-side) or sanitize-html (server-side). These libraries strip dangerous elements (script, iframe, event handlers) while preserving safe formatting.
  • Avoid inline JavaScript: Do not use onclick, onload, or other inline event handlers in HTML. Do not generate JavaScript from user input. Use CSP nonces or hashes for any inline scripts that are necessary.

Step 4: Secure Your APIs

Modern web applications are API-driven. Your API endpoints are the primary attack surface — they handle authentication, process data, and interact with your database.

API security best practices:

  • Authentication on every endpoint: Every API endpoint that accesses user data or performs actions must verify the user's identity. Use middleware to enforce authentication globally, with explicit opt-out for public endpoints (login, registration, public content).
  • Rate limiting: Implement rate limits on all API endpoints. Common limits: 100 requests/minute for authenticated users, 20 requests/minute for unauthenticated users, 5 requests/minute for login/registration. Use Redis with a sliding window algorithm for accurate counting. Return 429 Too Many Requests with a Retry-After header.
  • Request size limits: Set maximum request body size (e.g., 1 MB for JSON, 10 MB for file uploads). Without limits, an attacker can send enormous payloads to exhaust server memory. Configure in your web server (Nginx) and application framework.
  • CORS (Cross-Origin Resource Sharing): Configure CORS to allow requests only from your known domains. Do not use Access-Control-Allow-Origin: * on authenticated endpoints. Whitelist specific origins: your web app domain, your mobile app's domain.
  • API versioning and deprecation: Version your API (v1, v2) so you can deprecate insecure endpoints without breaking clients. When a vulnerability is found in an API endpoint, you can fix it in a new version while communicating the deprecation timeline for the old one.
  • Request validation: Validate every field in every request against a schema. Reject requests with unexpected fields (prevent mass assignment attacks where an attacker adds an "isAdmin: true" field to a profile update request).

Step 5: Implement HTTPS and Security Headers

HTTPS encrypts all communication between the user's browser and your server. Security headers add additional protection layers.

HTTPS:

  • Use HTTPS everywhere — not just on login and payment pages. Let's Encrypt provides free SSL certificates with automatic renewal. Cloudflare provides free SSL with one click. There is no reason to serve any page over HTTP in 2026.
  • Configure HTTP Strict Transport Security (HSTS): Strict-Transport-Security: max-age=31536000; includeSubDomains. This tells browsers to always use HTTPS for your domain, preventing SSL stripping attacks.
  • Redirect all HTTP traffic to HTTPS with a 301 redirect.

Essential security headers:

HeaderValuePurpose
Content-Security-Policydefault-src 'self'; script-src 'self'Prevents XSS by controlling allowed script sources
X-Content-Type-OptionsnosniffPrevents MIME-type sniffing attacks
X-Frame-OptionsDENY or SAMEORIGINPrevents clickjacking (your site in an iframe)
Referrer-Policystrict-origin-when-cross-originControls what URL information is sent in Referer header
Permissions-Policycamera=(), microphone=(), geolocation=()Disables browser features you do not use
Strict-Transport-Securitymax-age=31536000; includeSubDomainsForces HTTPS for 1 year

In Next.js, set security headers in next.config.js using the headers() function. In Express/NestJS, use the helmet middleware which sets all recommended headers with a single line: app.use(helmet()).

Step 6: Manage Dependencies Securely

Modern web applications use hundreds of open-source dependencies. A vulnerability in any dependency is a vulnerability in your application. In 2026, supply chain attacks (compromised npm packages) are one of the fastest-growing attack vectors.

Dependency security practices:

  • Audit regularly: Run npm audit or yarn audit weekly. Fix critical and high-severity vulnerabilities immediately. Automate this in your CI/CD pipeline — fail builds on critical vulnerabilities.
  • Use Dependabot or Renovate: Enable GitHub Dependabot or Renovate Bot to automatically create pull requests when dependencies have security patches. Review and merge these promptly — the window between vulnerability disclosure and exploitation is often hours, not days.
  • Lock dependency versions: Use package-lock.json (npm) or yarn.lock to ensure consistent dependency versions across environments. Review lock file changes in pull requests — unexpected changes could indicate a compromised package.
  • Minimise dependencies: Every dependency is a potential attack surface. Before adding a package, check: is it actively maintained? Does it have known vulnerabilities? Can you implement the functionality in 20-50 lines of code instead? The left-pad incident taught us that even trivial packages can cause chaos.
  • Use Snyk or Socket: Beyond basic npm audit, tools like Snyk and Socket provide deeper analysis — detecting malicious packages, typosquatting (malicious packages with names similar to popular ones), and maintainer account compromises.

Step 7: Set Up Monitoring and Incident Response

No application is 100% secure. You need the ability to detect attacks in progress, respond quickly, and recover from breaches.

Security monitoring:

  • Application logging: Log authentication events (successful logins, failed logins, password resets, MFA changes), authorisation failures (403 responses), input validation failures, and unusual patterns (100 failed logins from one IP). Do not log sensitive data (passwords, tokens, credit card numbers) — log event types and metadata only.
  • Error tracking: Use Sentry or similar tools to capture and alert on application errors. A sudden spike in errors can indicate an attack in progress — SQL injection attempts often generate database errors before succeeding.
  • Web Application Firewall (WAF): Cloudflare WAF (included in paid plans, basic rules in free) blocks common attack patterns (SQL injection, XSS, directory traversal) at the edge before requests reach your application. AWS WAF provides similar protection for applications on AWS.
  • Uptime monitoring: Use Better Uptime, UptimeRobot, or Pingdom to monitor your application's availability. Unexpected downtime can indicate a DDoS attack or a successful breach.

Incident response plan:

  • Detection: How will you know an attack is happening? Automated alerts from monitoring tools, customer reports, or security researcher notifications.
  • Containment: Steps to limit damage — revoke compromised tokens, block attacking IPs, take affected services offline if necessary, rotate API keys and secrets.
  • Investigation: Review logs to understand what happened, what data was accessed, and how the attacker gained access.
  • Recovery: Fix the vulnerability, restore from clean backups if data was corrupted, and deploy patches.
  • Communication: If user data was compromised, notify affected users promptly. Indian IT Act and DPDPA (Digital Personal Data Protection Act) require notification of data breaches to the Data Protection Board.
  • Post-mortem: Document what happened, why, and what changes will prevent recurrence. Update security practices based on lessons learned.

Security Checklist

CategoryCheckPriority
AuthenticationPasswords hashed with bcrypt/Argon2idCritical
AuthenticationRate limiting on login endpointsCritical
AuthenticationMFA available for admin accountsHigh
InputServer-side validation on all inputsCritical
InputFile uploads validated by magic bytesHigh
InjectionParameterised queries (no string concatenation)Critical
InjectionOutput encoding for all user contentCritical
APIAuthentication on all non-public endpointsCritical
APICORS restricted to known domainsHigh
TransportHTTPS everywhere with HSTSCritical
HeadersCSP, X-Content-Type-Options, X-Frame-Options setHigh
Dependenciesnpm audit runs in CI/CDHigh
MonitoringAuthentication events loggedHigh
MonitoringError tracking (Sentry) activeHigh

Cost and Timeline Summary

Security MeasureImplementation TimeCost
HTTPS + security headers1-2 hours₹0 (Let's Encrypt + Cloudflare)
Authentication hardening2-3 days₹15,000-40,000 (developer time)
Input validation and injection prevention3-5 days₹20,000-60,000
API security (rate limiting, CORS)1-2 days₹10,000-25,000
Dependency scanning setup2-4 hours₹0 (npm audit + Dependabot free)
WAF setup (Cloudflare)1-2 hours₹0-₹1,500/month
Complete security audit and fixes1-3 weeks₹50,000-3 lakh

When to DIY vs Hire a Professional

Handle yourself:

  • HTTPS setup (Let's Encrypt, Cloudflare — straightforward)
  • Security headers (helmet middleware, next.config.js headers)
  • npm audit and Dependabot setup
  • Basic rate limiting with established libraries

Hire a security professional when:

  • Your application handles sensitive data (financial, healthcare, personal information)
  • You need a security audit before launch or for compliance (PCI-DSS, HIPAA, SOC 2)
  • You suspect your application has been breached or is being actively attacked
  • You are building authentication, payment processing, or file upload handling and want expert review
  • Your application serves 10,000+ users and a breach would have significant business impact

JK Tech Hub builds security into every application from Day 1. Our web application development process includes OWASP Top 10 compliance, input validation, parameterised queries, security headers, dependency scanning, and authentication best practices. We also offer standalone security audits for existing applications. Get a free security assessment.

Sources & References

Is your web application secure? Contact JK Tech Hub for a free security assessment. We build and audit secure web applications following OWASP standards — 150+ projects delivered, 4.9/5 client rating, based in Rajkot, Gujarat. Get an instant estimate.

Tags

web application securityweb security checklistOWASP top 10secure codingXSS preventionSQL injectionapplication securitysecurity best practices

Need Help with Guides & Tutorials?

Our team at JK Tech Hub is ready to help you build the right solution for your business. Let's discuss your project.

Contact Us