Chapter 11

Security and Risks with AI-Generated Code

AI-generated code can contain security vulnerabilities just as easily as it can contain working logic. Understanding these risks is not optional — it's essential for every developer using AI as a coding tool.

Last reviewed: Aug 28 2026


The Security Problem

AI-generated code can reproduce insecure patterns, omit controls, misunderstand a framework, or use outdated APIs. A polished response is not evidence that the implementation is secure.

Core Principle

AI generates plausible code, not provably secure code. Every piece of AI-generated code that handles user input, authentication, data storage, or network communication must be reviewed for security — by you, by AI in reviewer mode, or ideally both.


Common Vulnerabilities in AI Code

These are common web-application risks worth checking in AI-generated code. The relevant risks depend on the system, data, trust boundaries, and deployment environment.

Critical

SQL Injection

AI often generates SQL queries using string concatenation instead of parameterized queries, allowing attackers to inject malicious SQL.

Critical

XSS (Cross-Site Scripting)

Rendering user input as raw HTML without sanitization. AI may use dangerouslySetInnerHTML or equivalent without warning.

High

Hardcoded Secrets

AI frequently places API keys, passwords, and tokens directly in source code instead of using environment variables.

High

Missing Input Validation

AI generates code that trusts user input — no length checks, no type validation, no sanitization.

High

Broken Authentication

Weak token generation, missing expiration, no rate limiting on login endpoints, plain-text password storage.

Medium

Insecure Dependencies

AI may suggest outdated or vulnerable packages without checking for known CVEs.


SQL Injection: A Real Example

SQL injection is a critical risk when untrusted input is combined with a query string, and the vulnerable code can look superficially reasonable.

🚨
Vulnerable Code — SQL Injection

AI often generates database queries like this:

// DANGEROUS — AI-generated, vulnerable to SQL injection

app.get('/api/activities', (req, res) => {

  const member = req.query.member;

  const query = `SELECT * FROM activities WHERE member = '${member}'`;

  db.query(query, (err, results) => {

    res.json(results);

  });

});

This looks clean and functional, but crafted input can change the meaning of the query. The exact impact depends on the driver configuration and database permissions; it can include unauthorized reads or writes.

Secure Version — Parameterized Query
// SAFER FOR VALUE INPUT — uses parameter binding
app.get('/api/activities', (req, res) => {

  const member = req.query.member;

  const query = 'SELECT * FROM activities WHERE member = ?';

  db.query(query, [member], (err, results) => {

    res.json(results);

  });

});

Use the parameter-binding mechanism documented by your database driver and apply least-privilege permissions. In this example, ? is a value placeholder for drivers that support that syntax; identifiers and dynamic query structure require separate allow-listing or safe query-building APIs.


AI Hallucinations

Beyond security vulnerabilities, AI has a broader reliability problem: hallucinations. AI can generate code that references packages that don't exist, uses API methods that were never implemented, or follows patterns from outdated documentation.

Common Hallucination Patterns

Pro Tip: Verify Before You Trust

When AI suggests a package or API method you are unfamiliar with, verify it before using it. Check the official registry, project documentation, release status, maintenance history, and the package identity before installation. A confident tone is not evidence of correctness.


The Security Review Prompt

AI can supplement a security review by suggesting issues to investigate. It does not replace threat modeling, tested controls, dependency analysis, security tooling, or review by someone with the required expertise.

Review this code for security vulnerabilities.



[paste your code]



Check specifically for:

- SQL injection (string interpolation in queries)

- XSS (unescaped user input in HTML)

- Hardcoded secrets (API keys, passwords, tokens)

- Missing input validation and sanitization

- Authentication/authorization bypasses

- Insecure data storage (plain-text passwords)

- Missing CORS configuration

- Missing rate limiting on sensitive endpoints

- Insecure HTTP headers



For each issue found:

- Describe the vulnerability

- Explain how it could be exploited

- Show the fix

Use a prompt like this as one review input for code that crosses trust boundaries. Verify every finding and every claimed absence with tests, tools, official guidance, and system context.


Data Privacy Risks

When you paste code into AI for review or generation, you're sharing that code with a third-party service. This creates data privacy considerations that every developer needs to understand.

What NOT to Share with AI

Scan code, diffs, logs, and stack traces before sending them to an AI service. Remove secrets and minimize personal, customer, and internal infrastructure data. Store real secrets through the application's approved secret-management path, not as values to paste back into source code.


The Security Checklist

Use this checklist on every project that handles user data, authentication, or external APIs. Ask AI to verify each item — and verify AI's answers yourself for critical systems.

Input & Data
All user inputs validated — Type checked, length limited, format verified
SQL queries parameterized — No string interpolation in database queries
HTML output escaped — User content rendered safely, no raw HTML injection
Authentication
Passwords hashed — Prefer Argon2id with parameters appropriate to your environment; use bcrypt mainly for legacy compatibility, and never store plaintext passwords
Sessions designed explicitly — Expiration, rotation, revocation, cookie attributes, CSRF exposure, and token storage match the threat model
Login abuse controls — Rate limits and related controls are tuned and tested against automated guessing without creating an easy denial of service
Configuration
No hardcoded secrets — Keys, passwords, and tokens use the deployment's approved secret-management mechanism
CORS scoped — Browser cross-origin access is limited to the origins and methods the application needs; authorization is enforced separately on every protected endpoint
HTTPS enforced — All traffic encrypted in transit
Supply chain monitored — Track direct and transitive versions, lock dependencies, scan regularly, review advisories, and respond to supported-tooling alerts; a clean scan is not proof of safety
Error Handling
No stack traces exposed — Production errors show generic messages, not internals
Error logging configured — Errors logged server-side for debugging, not sent to client

Building Secure Code with AI

Include security requirements in the initial task, then verify the implementation with threat modeling, tests, supported tooling, and review. Prompt constraints are one input, not a security control by themselves.

The values below are example constraints, not universal defaults. Replace them with the application's threat model, authentication policy, framework guidance, and measured limits.

Build an Express.js login endpoint.


Security requirements:

- Hash passwords with Argon2id using parameters selected from current OWASP guidance
- Use the application's established session design; document expiration, rotation, revocation, storage, and CSRF controls
- Apply the project's tested login-abuse controls; state the thresholds and denial-of-service trade-offs
- Enforce the current authentication policy for identifiers and password length
- Return generic error messages (don't reveal if email exists)

- Log failed attempts server-side

- Set secure HTTP headers (helmet)



Do NOT:

- Store passwords in plain text

- Include secrets in the code (use process.env)

- Return stack traces on error

Explicit requirements make omissions easier to notice, but the model can still violate or misunderstand them. Treat every generated control as untrusted until it has been checked in the actual framework and deployment context.


Over-Reliance: The Biggest Risk

The security threats above are technical. But the most dangerous risk of AI-generated code is human, not technical: over-reliance.

When code appears instantly and looks correct, there's a strong psychological tendency to trust it without verification. This is especially dangerous because AI-generated code looks professional — it's well-formatted, uses proper naming conventions, and includes comments. All of this creates a false sense of security.

Over-Reliance Pattern

  • AI generates code → immediately ship it
  • "It looks right" = "it is right"
  • No testing, no review
  • Don't understand how the code works
  • Can't debug it when it breaks

Healthy Pattern

  • AI generates code → read it → test it → review it
  • Understand every line before committing
  • Run AI security review on all critical code
  • Can explain what the code does and why
  • Can debug and modify independently
The Responsibility Rule

You remain accountable for code you ship. Generated output must pass the same ownership, review, testing, security, and change-control requirements as human-written code.


Current Security References

Security guidance changes. For high-consequence decisions, start with current primary guidance and the documentation for the exact framework, runtime, and database version you use. This chapter was checked on Aug 28 2026 against:

🧪 Practical Exercise

Take a piece of AI-generated backend code — either from this tutorial or from your own projects. Run the full security audit:


Key Takeaways

Related Guides

AI-Assisted Code Review

Use security-focused review prompts where risk is highest.

When AI Gets It Wrong

Detect failure modes before risky output reaches users.

Previous Chapter AI-First Development Methodology
Next Chapter Advanced Strategies