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.
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.
SQL Injection
AI often generates SQL queries using string concatenation instead of parameterized queries, allowing attackers to inject malicious SQL.
XSS (Cross-Site Scripting)
Rendering user input as raw HTML without sanitization. AI may use dangerouslySetInnerHTML or equivalent without warning.
Hardcoded Secrets
AI frequently places API keys, passwords, and tokens directly in source code instead of using environment variables.
Missing Input Validation
AI generates code that trusts user input — no length checks, no type validation, no sanitization.
Broken Authentication
Weak token generation, missing expiration, no rate limiting on login endpoints, plain-text password storage.
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.
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.
// 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.
- Phantom packages — AI suggests
npm install family-scheduler-utilsfor a package that doesn't exist. You run the install, it fails, and you've wasted time. - Invented API methods — AI uses
array.filterByKey()orreact.useAsync()— methods that look plausible but don't exist in any library. - Outdated patterns — AI generates class components in React, uses deprecated lifecycle methods, or references old API endpoints.
- Wrong function signatures — AI calls a real function but with the wrong arguments or in the wrong order.
- Confident misinformation — AI explains its hallucinated code with complete confidence, making it harder to spot.
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.
- Real API keys, passwords, or tokens — Keep them out of prompts and source code; use placeholders such as
YOUR_API_KEY_HERE - Customer personal data — Use synthetic data unless an approved design and service agreement explicitly permit the real data flow
- Proprietary business logic — Check the organization's disclosure, retention, and AI-tool policy before sharing it
- Database connection strings — These contain credentials. Redact before sharing.
- Internal infrastructure details — Server addresses, network topology, internal URLs
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.
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
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:
- OWASP Top 10:2025 — current web-application risk categories, including broken access control and software supply-chain failures
- OWASP Password Storage Cheat Sheet — Argon2id guidance and bcrypt's legacy role
- OWASP REST Security Cheat Sheet — token, transport, validation, and CORS guidance
Take a piece of AI-generated backend code — either from this tutorial or from your own projects. Run the full security audit:
- Step 1: Read the code yourself. Can you spot any security issues?
- Step 2: Ask AI to review the code using the security review prompt template.
- Step 3: Compare your findings with AI's findings. What did each catch that the other missed?
- Step 4: Fix all identified issues. Ask AI to verify the fixes are correct.
- Step 5: Run the security checklist on the fixed code. Are all items satisfied?
Key Takeaways
- AI generates plausible code, not provably secure code — security review is mandatory, not optional
- Example risks to check include injection, cross-site scripting, hardcoded secrets, broken access control, insecure design, and missing server-side validation
- Always use parameterized queries — never string-interpolate user input into SQL
- AI hallucinations create reliability risks: phantom packages, invented APIs, outdated patterns
- Do not send secrets, credentials, or customer data to an AI service unless an approved design explicitly permits and protects that data flow
- Include security requirements in your initial prompts — build secure from the start, don't patch after
- Use the security checklist on every project that handles user data or authentication
- The biggest risk is over-reliance — you own the code AI generates, including its security flaws
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.