JAVASCRIPT
Prevent SQL Injection with Prepared Statements (Node.js/PostgreSQL)
Discover how to protect your Node.js application from SQL injection attacks by using parameterized queries with the 'pg' library for PostgreSQL, ensuring secure database interactions.
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_user',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
async function getUserById(userId) {
try {
// THIS IS THE SECURE WAY: Use parameterized queries
const queryText = 'SELECT id, username, email FROM users WHERE id = $1';
const values = [userId]; // Pass user input as a separate value array
const result = await pool.query(queryText, values);
console.log('User found:', result.rows[0]);
return result.rows[0];
} catch (error) {
console.error('Error executing query', error.stack);
throw error;
}
}
// Example usage:
(async () => {
try {
await getUserById(1); // Valid user ID
// Attempting to inject will fail securely:
await getUserById("1 OR 1=1 --"); // This will be treated as a string, not SQL
} finally {
await pool.end();
}
})();
How it works: This Node.js snippet demonstrates how to prevent SQL injection vulnerabilities using parameterized queries with the `pg` library for PostgreSQL. Instead of concatenating user input directly into the SQL string, the input is passed as a separate `values` array. The database driver then correctly separates the SQL command from the user data, ensuring that malicious input (like `1 OR 1=1 --`) is treated as a literal string value rather than executable SQL code, thus protecting the database from unauthorized access or manipulation.