JAVASCRIPT

Prevent SQL Injection with Parameterized Queries in Node.js

Implement parameterized queries with Node.js and PostgreSQL (or other SQL databases) to effectively prevent SQL injection vulnerabilities by separating SQL logic from user input.

// Install pg (PostgreSQL client for Node.js): npm install pg
const { Client } = require('pg');

// Database connection configuration (replace with your actual credentials)
const dbConfig = {
  user: 'your_username',
  host: 'localhost',
  database: 'your_database',
  password: 'your_password',
  port: 5432,
};

/**
 * Fetches user data using a parameterized query, preventing SQL injection.
 * @param {string} userId The user ID to query.
 * @returns {Promise<Array>} A promise that resolves with the query results.
 */
async function getUserById(userId) {
  const client = new Client(dbConfig);

  try {
    await client.connect();

    // UNSAFE: Direct string concatenation (VULNERABLE to SQL Injection)
    // const unsafeQuery = `SELECT * FROM users WHERE id = ${userId}`;
    // const unsafeResult = await client.query(unsafeQuery);

    // SAFE: Parameterized query (PREVENTS SQL Injection)
    // Use placeholders ($1, $2, etc. for pg) and pass values in an array.
    const safeQuery = 'SELECT id, username, email FROM users WHERE id = $1';
    const safeResult = await client.query(safeQuery, [userId]);

    console.log('User fetched securely:', safeResult.rows);
    return safeResult.rows;
  } catch (error) {
    console.error('Database query error:', error);
    throw error;
  } finally {
    await client.end();
  }
}

// Example Usage:
// Safe input
getUserById('123');

// Malicious input (will be treated as a string literal '123 OR 1=1' and not execute 'DROP TABLE')
getUserById('123 OR 1=1; DROP TABLE users;');

// More realistic malicious input attempting to bypass authentication
// getUserById("1' OR '1'='1"); // This would be dangerous with string concatenation
How it works: This Node.js snippet demonstrates how to prevent SQL Injection attacks by using parameterized queries. Instead of directly embedding user input into the SQL query string (which allows malicious input to alter query logic), parameterized queries use placeholders (e.g., `$1` for PostgreSQL's `pg` library) and pass user input as a separate array of parameters. The database driver then correctly separates the SQL command from the user-provided data, ensuring that input is treated as literal values, not executable code, thereby neutralizing injection attempts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs