JAVASCRIPT

Preventing SQL Injection with Prepared Statements (Node.js)

Learn to secure your Node.js application against SQL injection using parameterized queries with a PostgreSQL database driver, a critical defense.

const { Pool } = require('pg');

const pool = new Pool({
  user: 'youruser',
  host: 'localhost',
  database: 'yourdatabase',
  password: 'yourpassword',
  port: 5432,
});

async function getUserById(id) {
  try {
    // Use parameterized queries to prevent SQL injection
    const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
    return result.rows[0];
  } catch (err) {
    console.error('Error executing query', err.stack);
    throw err;
  }
}

// Example usage:
// getUserById(1).then(user => console.log(user));
// getUserById('DROP TABLE users;--').then(user => console.log(user)); // This will NOT execute the malicious query
How it works: This snippet demonstrates how to prevent SQL injection attacks in a Node.js application using the 'pg' (PostgreSQL) library. Instead of concatenating user input directly into SQL queries, it uses prepared statements (parameterized queries). The 'id' variable is passed as a separate parameter ([$1]), ensuring that the database driver correctly sanitizes and separates the data from the SQL command structure, preventing malicious input from being interpreted as executable SQL.

Need help integrating this into your project?

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

Hire DigitalCodeLabs