Course contentsShow
← Node.js
Lesson 758 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Query Parameterization against Injection

You will utilize prepared statements to prevent malicious user input from executing arbitrary code.

Query Parameterization against Injection

In this lesson, you will learn how to use prepared statements to ensure that user input is treated strictly as data, effectively neutralizing SQL injection attacks.

When you build a database query in Node.js, it is tempting to use template literals to insert variables directly into your SQL string. For example: db.query("SELECT * FROM users WHERE name = '" + userInput + "'").

This is extremely dangerous. If a malicious user provides an input like ' OR '1'='1, your query becomes SELECT * FROM users WHERE name = '' OR '1'='1', which forces the database to return every record in the table. This is known as SQL Injection.

The Solution: Prepared Statements

To prevent this, we use Query Parameterization. Instead of building the string yourself, you send the query structure and the user data to the database driver as two separate entities. The database driver ensures that the data is treated purely as a literal value and never as executable code.

Here is how you do it using a placeholder (usually ? or $1):

// The database driver handles the sanitization
const query = 'SELECT * FROM users WHERE name = ?';
const values = [userInput];

db.execute(query, values, (err, results) => {
  if (err) throw err;
  console.log(results);
});

In this code, the database driver receives the command to look for a name, and then it receives the "name" as a separate piece of information. If the user tries to inject a command like OR '1'='1, the database will simply look for a user whose literal name is the string ' OR '1'='1. Since no user has that strange name, the attack fails, and your application remains secure.

By separating the "instruction" from the "data," you guarantee that even if a user provides malicious input, the database engine will not execute it as part of your query logic.

Key Takeaway: Never concatenate user input directly into SQL strings; always use placeholders and parameter arrays to keep your data and your queries safely separated.