Is AI-Generated Code Secure? Risks to Check
Yes, AI-generated code can contain security vulnerabilities. It often runs perfectly and looks tidy while still leaving a hole, so review it the way you would review code from a fast but inexperienced developer before it goes live.
This post is for owners and small teams who use tools like ChatGPT, Claude, Copilot, Cursor or other AI builders to write website code. You will learn the flaws that show up most often, how to spot each one, and a short checklist to run before you deploy. No security background needed.
Why AI-written code can be insecure
An AI model writes code that looks like the code it learned from. It learned from a huge amount of public code, and public code includes plenty of insecure examples. It also does not know your users, your data, or what an attacker would try.
There is a second problem: prompts. If you ask for "a login page that works," you get one that works. Security is rarely in the request, so it is often missing from the answer.
The flaws are not new. They match the well-known categories in the OWASP Top 10, the standard list of web application risks. AI just produces them quickly and at volume.
The common flaws at a glance
| Flaw | What it looks like | Quick check |
|---|---|---|
| Missing input validation | Form or URL data goes straight into a database query or a web page | Search for string-built queries and unescaped output |
| Hardcoded secrets | API keys or passwords typed into the code | Search the code and git history for keys |
| Outdated or invented packages | Old library versions, or a package name that does not exist | Run an audit and check each new package by hand |
| Weak authentication | Weak password storage, no rate limits, loose sessions | Read the login and session code |
| Missing access checks | Any logged-in user can open another user's data | Change an ID in a URL and see what happens |
| Open defaults | Wide-open CORS, a database with Row Level Security off, debug mode left on | Check settings and response headers |
1. Missing input validation
Input validation means checking that data from a visitor is the shape you expect before you use it. When it is missing, attackers can send code instead of data. This is called injection, and it covers SQL injection (tricking your database) and cross-site scripting, or XSS (running a script in another visitor's browser).
A typical AI-written query builds the SQL as a string:
// Risky: user input is pasted into the query
db.query("SELECT * FROM users WHERE email = '" + email + "'");
The safe version uses a parameterized query, where the database treats the input as data only:
// Safer: placeholder, input passed separately
db.query('SELECT * FROM users WHERE email = $1', [email]);
For pages, avoid inserting user text with innerHTML or dangerouslySetInnerHTML. Use plain text output, which most frameworks escape for you. OWASP's Input Validation Cheat Sheet and SQL Injection Prevention Cheat Sheet explain both in detail.
Also validate on the server. A check that only exists in the browser form can be skipped by anyone.
2. Hardcoded secrets
A secret is anything that proves your app's identity: API keys, database passwords, payment keys, tokens. AI examples often paste a placeholder key straight into the code, and people replace it with the real one and move on.
That is dangerous because code gets committed to Git, shared, and sometimes made public. Even a deleted key stays in the Git history.
Two checks take a minute:
git grep -nIiE "api[_-]?key|secret|password|token|sk_live|AKIA"
git log --all -p | grep -iE "api[_-]?key|secret|sk_live"
The first searches the tracked files in your project. The second searches past changes. Expect some harmless matches, so read the results.
The fix is to store secrets in environment variables or your host's secrets setting, and keep .env in .gitignore. If a real key was ever committed, rotate it (create a new one and disable the old one). Deleting the line is not enough. See OWASP's Secrets Management Cheat Sheet.
Watch for a front-end trap too. In frameworks like Next.js, variables starting with NEXT_PUBLIC_ are shipped to every visitor's browser. In Vite, the same is true for VITE_. Never put a private key behind those prefixes.
3. Outdated or invented packages
AI tools learned from older code, so they may suggest old library versions that have known security fixes available. Check them with the audit tool for your language:
npm audit # JavaScript (see docs.npmjs.com/cli/commands/npm-audit)
pip install pip-audit && pip-audit # Python
The stranger issue is the invented package. Models sometimes recommend a package name that does not exist. Attackers can register that name and fill it with malicious code, hoping someone installs it. This is sometimes called slopsquatting, and it is a variation on the older typosquatting trick.
Before installing anything an AI suggests, look it up:
npm view some-package time.created maintainers repository.url
Be suspicious if the package was created very recently, has no real repository, or has a name that is only close to a famous library. When in doubt, use the well-known package, or write the small piece yourself.
4. Weak authentication and missing access checks
Authentication is proving who someone is. Authorization is deciding what they may do. AI code often gets the first one roughly right and forgets the second.
Look for these in the login and session code:
- Passwords stored weakly. Plain text, MD5 or SHA-1 are not acceptable. Use bcrypt, scrypt or Argon2 through a trusted library.
- Guessable secrets. A token-signing key (JWT secret) set to something like
secretorchangeme. - No login rate limit. Nothing slows down someone trying thousands of passwords.
- Loose session cookies. Cookies should carry
HttpOnly; Secure; SameSite=Laxat minimum. - No ownership check. The route
/api/orders/1042returns the order to anyone logged in, not just its owner.
That last one is easy to test. Log in as user A, open a page that shows an ID in the URL, change the number, and see whether you can read user B's data. If you can, that is broken access control, which sits at the top of the OWASP Top 10. If you want a broader view of this kind of testing, read our guide to whether your website is hackable.
If you use a backend service like Supabase, also confirm that Row Level Security is switched on for every table that holds user data. See the Supabase documentation. A table with Row Level Security switched off can be read, and often changed, by anyone who has your public (anon) key. Turning RLS on with no policies blocks that access until you add policies that allow only what each user needs.
5. Risky defaults and leftovers
AI code often ships with settings that are convenient for testing:
Access-Control-Allow-Origin: *, or an API that echoes back any origin while allowing credentials, on an endpoint that serves private data.- Debug mode or detailed error pages left on in production.
- Test accounts, admin routes, or sample data that were never removed.
- Missing security headers. You can check yours with our free security headers tool.
Two headers are a sensible starting set. X-Content-Type-Options: nosniff tells browsers not to guess file types. Strict-Transport-Security (HSTS) forces HTTPS. Start with Strict-Transport-Security: max-age=300 and raise it gradually to 31536000 once everything works. Add includeSubDomains only after you confirm every subdomain works over HTTPS, because it can break a staging, mail or legacy host that only uses HTTP. Only add HSTS once your whole site works over HTTPS.
A pre-deploy review checklist
Run this every time AI-written code is about to go live. The time depends on how much code changed. A small site is quicker than a large one.
- Read it. If nobody on your team can explain what a block of code does, do not ship it.
- Search for secrets with the
git grepandgit logcommands above. Rotate anything real you find. - Run your audit tool (
npm auditorpip-audit) and update packages with known problems. - Verify every new package exists, has a real repository, and has a believable history.
- Check every form and URL input. Look for parameterized queries and escaped output, validated on the server.
- Test access by hand. Change IDs in URLs while logged in as a normal user. Try admin pages without an admin account.
- Review the login code. Confirm password hashing, a strong signing key, rate limiting, and safe cookie flags.
- Turn off debug mode and remove test accounts and sample data.
- Check your headers and HTTPS with the security headers tool.
- Keep a staging copy to test on, and never test destructive actions on live customer data.
You can also ask the AI to review its own work, with a prompt like "list any security problems in this code, including injection, access control and secrets." It is a useful extra pair of eyes, but not a replacement for the steps above. The same model that made a mistake can miss it again.
What a checklist and scanners can't tell you
Automated scanners are good at spotting known patterns, such as outdated libraries and missing headers. They are weak at business logic: can a customer change a price in the request, can one user see another's invoice, can a coupon be reused forever. AI-written apps often contain this kind of custom logic. Our post on manual vs automated penetration testing covers the difference.
If you want a quick outside look first, the free website security check is a passive scan of a domain you own. It does not replace a manual test.
Key takeaways
- AI-generated code can contain security vulnerabilities, because it copies common patterns and rarely thinks about attackers.
- The usual suspects are missing input validation, hardcoded secrets, outdated or invented packages, and weak authentication or access checks.
- Search your code and Git history for secrets, run
npm auditorpip-audit, and verify any package you do not recognize. - Test access by hand: change an ID in a URL and see whether you can reach someone else's data.
- Treat AI output as a first draft, and have a human review it before real customers use it.
Want a human to check it?
A checklist catches the obvious problems. A person testing your site by hand can find the ones that depend on how your app actually works. Bug Circuit's Essential plan is $49 one-time and covers 1 website with 3 manual audits to request within one month, each ending in a written report with severity, evidence and fix steps. It is a focused small-site test, not a compliance certification or a multi-week enterprise pentest. We explain the issues. Fixing them is a separate service we quote per issue, and you pay only if you agree. See pricing for the details.
A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.
See pricing