Security

SQL Injection in TypeScript: Prevention with Prisma

TypeScript's static typing doesn't prevent SQL injection. String annotations on username: string don't prevent malicious SQL from being a valid string.


❌ Vulnerable TypeScript Query

async function getUser(username: string): Promise<User | null> {
  const result = await db.query(
    `SELECT * FROM users WHERE username = '${username}'`
  );
  return result.rows[0] ?? null;
}

✅ Safe Parameterized Query

async function getUser(username: string): Promise<User | null> {
  const result = await db.query(
    'SELECT * FROM users WHERE username = $1',
    [username]
  );
  return (result.rows[0] as User) ?? null;
}
// Or with Prisma:
// const user = await prisma.user.findUnique({ where: { username } });
💡

Pro tip: Prisma generates TypeScript types from your database schema AND builds parameterized queries automatically — two layers of protection in one tool.

Paste this code into LearnCodeGuide

Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze TypeScript Code →

Related Guides

Typescript XssJavascript Sql InjectionPython Sql Injection