CSRF Protection & Security Headers: The Missing Layer in AI-Built Apps

Quick answer: Security headers like CSP, HSTS, and X-Frame-Options are the missing defense layer in AI-built apps. While tools like Cursor and Lovable generate functional code, they rarely configure the HTTP headers needed to block XSS and clickjacking. Learn how to implement these headers and CSRF protection to secure your vibe-coded projects.

By Daniel A · Kraftwire Software

· 11 min read

To protect AI-built apps from Cross-Site Request Forgery (CSRF) and browser-level exploits, you must manually implement six core security headers: Content-Security-Policy, Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy. While AI tools like Cursor, Lovable, and Windsurf excel at generating functional UI and logic, they almost never configure the underlying HTTP response headers or CSRF middleware required to secure a production environment.

Many of these vulnerabilities stem from the "missing layer" · the infrastructure-level security that AI agents assume the developer will handle. Because AI models are trained on code snippets rather than full server configurations, they prioritize "making it work" over "making it secure." This leads to a common scenario where a vibe-coded app is visually perfect but architecturally transparent to attackers.

What Are Security Headers?

Security headers are HTTP response headers that instruct the browser on how to handle your site's content. They act as a declarative security policy, enabling the browser to block entire classes of attacks · such as clickjacking, MIME-sniffing, and Cross-Site Scripting (XSS) · without requiring changes to your application's business logic.

When you use "vibe coding" tools to ship an app in minutes, the focus is on the App.tsx or the database schema. However, security is a shared responsibility. Research into thousands of publicly deployed vibe-coded apps has shown that a staggering number of these projects hit a wall because they lack basic architectural protections. According to research by Escape.tech, which scanned 5,600 publicly deployed vibe-coded apps, critical architectural failures are rampant in the wild. These failures often include missing headers that would otherwise mitigate common web vulnerabilities.

Why AI-Built Apps Are Vulnerable

AI coding assistants typically generate code that works in a local development environment. In development, security headers are often absent to make debugging easier. When that code is pushed to Vercel, Netlify, or a VPS, those "missing" headers remain missing. The AI doesn't "know" your deployment environment unless you specifically prompt it to configure vercel.json or next.config.js.

A recent industry audit of AI-generated codebases found that zero percent of the sampled apps had CSRF protection, and none set CSP or HSTS headers. This creates a dangerous gap: you have a modern, functional app that is effectively defenseless against browser-side manipulation. Furthermore, only one app in the sample attempted rate limiting, and even that was bypassable with a single HTTP header. This highlights the "vibe coding" trap: the app feels secure because it's new and uses modern frameworks, but the foundation is missing the standard industry hardening.

The Essential Security Header Checklist

1. Content-Security-Policy (CSP)

CSP is your primary defense against XSS. It defines which scripts, styles, and images are allowed to load. Without a CSP, a browser will execute any script it finds on your page, whether it’s your code or a malicious script injected via a comment form or a compromised third-party library.

Why it matters: If an attacker finds a way to inject a script into your Lovable or Bolt.new app, CSP prevents that script from executing unless it comes from a trusted source. For AI apps using Supabase or Firebase, you must include their API domains in the connect-src directive. A strict CSP can also prevent data exfiltration by blocking unauthorized fetch or XMLHttpRequest calls to unknown domains.

2. Strict-Transport-Security (HSTS)

HSTS ensures the browser only communicates with your server over HTTPS. It tells the browser that for a specified period (usually one year), it should never attempt to connect via insecure HTTP.

Why it matters: It prevents SSL stripping attacks where an attacker intercepts a request and downgrades it to HTTP. By adding the preload flag and submitting your site to the HSTS preload list, you ensure that even the very first connection a user makes is encrypted. This is critical for apps built with Replit or Base44 that might handle user credentials or sensitive session tokens.

3. X-Frame-Options

This header prevents your application from being rendered inside an <iframe> on a different domain.

Why it matters: It stops "clickjacking." Without this, an attacker could overlay your app's "Delete Account" button with a fake "Click here for a prize" button on their own site. While modern browsers also support the frame-ancestors directive in CSP, X-Frame-Options remains a vital fallback for older browser compatibility.

4. X-Content-Type-Options

This prevents the browser from "sniffing" the MIME type of a file.

Why it matters: It forces the browser to respect the Content-Type header sent by the server. This prevents an attacker from uploading a malicious script disguised as an image file and having the browser execute it. This is a simple but effective defense against drive-by downloads and certain types of XSS.

5. Referrer-Policy

Controls how much information is shared in the Referer header when a user clicks a link to an external site.

Why it matters: AI apps often use complex URL structures or query parameters that might contain sensitive IDs or even session fragments. This policy ensures that external sites only see your domain name, not the full URL path, when a user navigates away from your app.

6. Permissions-Policy

Restricts the use of browser features like the camera, microphone, or geolocation.

Why it matters: It reduces the attack surface. If your app doesn't need the camera, disabling it at the header level ensures that even a successful XSS attack cannot turn on the user's webcam. This follows the principle of least privilege at the browser level.

Understanding and Fixing CSRF

Cross-Site Request Forgery (CSRF) is an attack that tricks a logged-in user into submitting a malicious request to your app. Because the browser automatically attaches cookies to requests, the server thinks the user intended to perform the action. If your app has a "Change Password" or "Delete Project" endpoint that doesn't check for CSRF, an attacker can host a malicious page that sends a POST request to your API when a victim visits it.

CSRF is a frequent contributor to high-severity security ratings because it can lead to unauthorized data changes or account takeovers. In the world of vibe coding, where rapid deployment is the goal, CSRF protection is often the first thing forgotten.

How to Implement CSRF Protection

  • SameSite Cookie Attribute: This is the most effective modern defense. Set your session cookies to SameSite=Lax or SameSite=Strict. This tells the browser not to send the cookie during cross-site POST requests. Most modern frameworks like Next.js or Remix set this by default, but it’s worth verifying in your session configuration.
  • Anti-CSRF Tokens: For sensitive actions, generate a unique, cryptographically strong token for the session and require it to be sent in a hidden form field or a custom header (like X-CSRF-Token). The server then validates that the token in the request matches the token stored in the user's session.
  • Custom Headers: If your app is a Single Page Application (SPA) built with Windsurf or Cursor, requiring a custom header for all API calls (e.g., X-Requested-With) provides a strong layer of defense. Cross-origin requests cannot set custom headers without a preflight CORS check, which the attacker's site will fail unless you have explicitly whitelisted them.

How to Add Headers to Your Stack

Vercel (vercel.json)

If you are deploying a Lovable or v0 app to Vercel, use this configuration in your root directory:

Next.js (next.config.js)

For apps built with Cursor, add this to your config to ensure every page load includes the necessary protections:

The Ultimate Vibe Coding Security Checklist

Shipping fast doesn't have to mean shipping "naked" apps. Follow this application security checklist to ensure your AI-built project is production-ready:

  • Audit Headers: Use the Security Headers Checker to verify your deployment. A quick check can reveal if your vercel.json or next.config.js is actually being applied.
  • Enable RLS: If using Supabase, ensure Row Level Security is active. See our RLS guide. Without RLS, your security headers are just a thin shell over an unprotected database.
  • Check for Leaks: Ensure .env files are not exposed. Use the Secret Scanner to check for leaked OpenAI or Anthropic keys.
  • Monitor Uptime: Set up uptime monitoring to catch configuration errors that might break your headers or your entire site during a deployment.
  • Run a Full Scan: Use SimplyScan to check 8 dimensions including security, speed, and GDPR signals in 30 seconds. It detects exposed API keys, missing/weak Supabase RLS, broken auth, XSS, CSRF, and missing security headers.

Speed, SEO, and AEO

Security headers don't just protect users; they impact your site's reputation with search and answer engines. While security headers add a few bytes to the response, the trust they build with browsers and search crawlers is essential for Answer Engine Optimization (AEO). Search engines like Google prioritize sites that follow security best practices, and missing headers like HSTS can lead to lower rankings.

If your app is slow or insecure, AI engines like Perplexity or ChatGPT may flag your site as "unreliable" or "potentially harmful," hurting your visibility. A secure, fast app is the foundation of modern AI visibility. SimplyScan's 8-dimension scan helps you balance these needs by grading speed and SEO alongside security.

Deep Dive: The Impact of Missing Headers

When an app lacks X-Frame-Options, it is vulnerable to UI redressing. An attacker can create a transparent iframe of your site over a malicious one. When a user thinks they are clicking a link on the attacker's site, they are actually clicking a button on your site. If the user is logged in, this can lead to catastrophic results.

Similarly, the absence of X-Content-Type-Options allows for "MIME sniffing." If your AI-generated app allows users to upload files (like profile pictures), an attacker could upload a .jpg file that contains JavaScript. If the browser "sniffs" the content and decides it's actually a script, it will execute it in the context of your domain. This bypasses many traditional frontend security checks.

By implementing these headers, you are not just checking a box for compliance; you are building a multi-layered defense. This is especially important for Bolt.new or v0 users who are often building and deploying in a single session. The "vibe" might be fast, but the security must be firm.

Conclusion

AI tools have revolutionized how we build, but they haven't changed the fundamental rules of web security. CSRF protection and security headers are the "missing layer" that separates a weekend project from a professional SaaS. As we move further into the era of AI-generated software, the responsibility of the developer shifts from writing every line of code to auditing the architecture that the AI provides.

Don't guess if your app is secure. Run a free scan on SimplyScan today to detect exposed API keys, missing headers, and architecture security risks. It takes 30 seconds, requires no signup, and provides a comprehensive grade across security, speed, SEO, and accessibility.

---

Related Guides

Related Free Tools

Frequently asked questions

What are security headers and why does my AI app need them?

Security headers are HTTP response headers that tell the browser how to handle your site's content. They prevent attacks like XSS, clickjacking, and MIME-sniffing at the browser level. AI tools often omit them because they are infrastructure-level settings, not application logic. You can add them via vercel.json, next.config.js, or server middleware like Helmet.

How do I stop CSRF in a vibe-coded application?

CSRF (Cross-Site Request Forgery) tricks a user's browser into performing actions on your site without their consent. Most AI-generated code lacks CSRF middleware. To fix this, use SameSite=Lax or Strict for cookies, implement anti-CSRF tokens for state-changing requests, or require custom headers (like X-Requested-With) for your API calls to block cross-origin forgery.

What is CSP and how does it prevent XSS?

Content-Security-Policy (CSP) is a header that restricts where scripts, styles, and images can be loaded from. It is the most effective defense against Cross-Site Scripting (XSS). For AI apps, you must carefully whitelist your own domain and any third-party services like Supabase, Firebase, or Clerk in the CSP to ensure functionality isn't blocked.

What is HSTS preload do for my app's security?

HSTS (Strict-Transport-Security) forces browsers to use HTTPS for all communication with your domain. The 'preload' directive takes this further by adding your domain to a hardcoded list in browsers, ensuring that even the very first visit to your site is encrypted. This prevents SSL stripping and man-in-the-middle attacks on public Wi-Fi.

What is clickjacking and how do I prevent it?

Clickjacking is an attack where your site is hidden in an invisible iframe on a malicious page, tricking users into clicking buttons they can't see. The X-Frame-Options header (set to DENY or SAMEORIGIN) or the CSP frame-ancestors directive tells the browser whether your site is allowed to be embedded, effectively neutralizing this entire class of attack.

How can I verify if my security headers are working?

You can check your headers using browser DevTools (Network tab -> Response Headers) or free online tools. SimplyScan offers a free Security Headers Checker that grades your site from A to F. Additionally, SimplyScan's full site audit checks for CSRF vulnerabilities, permissive CORS, and missing headers as part of its 8-dimension health scan.

Related guides

  • Content Security Policy for Vibe-Coded Apps: A Practical CSP Guide · Content Security Policy (CSP) is a browser-enforced allowlist that blocks unauthorized scripts, providing the strongest defense against XSS. Most vibe-coded apps ship with no CSP or use 'unsafe-inline', which negates protection. This guide explains how to implement strict policies using nonces, hashes, and report-only mode to secure AI-built applications.
  • Firebase Rules for AI Apps: A Security Guide for LLM Architectures · Firebase rules for AI apps must prioritize data ownership and input validation to prevent prompt injection and unauthorized access. Use strict UID checks, limit string lengths for AI-generated content, and enforce immutability for chat histories. Always move beyond default 'Test Mode' rules to protect sensitive LLM context and user data.
  • FlutterFlow Security Guide: Firebase Rules, Auth, and Data Protection · FlutterFlow apps are secure only if you manually configure Firebase Security Rules, restrict API keys, and enable App Check. By default, these apps often ship with permissive rules that expose your entire database. You must replace 'allow-all' logic with ownership checks and move sensitive API logic to Cloud Functions to prevent data breaches.
  • React Security Best Practices for AI-Built Apps: Fixing Common Vibe-Coding Vulnerabilities · React security best practices in 2026 focus on preventing API key exposure and XSS in AI-generated code. Never store secret keys in client-side environment variables. Instead, use Next.js Server Components or proxy routes. Always enable Row Level Security (RLS) and sanitize dynamic HTML to protect against common vibe-coding vulnerabilities.

All security guides · Free security tools · Platform scanners · Security checklist