SQL Injection and Cross-Site Scripting Explained for Builders
Understand why injection flaws happen and how parameterized queries, output encoding and layered defenses prevent them.
Key takeaways
- Injection happens when untrusted text is glued into a command that another system will interpret.
- Parameterized queries stop SQL injection by sending the query's structure separately from its values.
- XSS is prevented mainly by encoding output for its context, which modern template systems do by default.
- Input validation and security headers are useful extra layers, but neither replaces correct queries and encoding.
- Review the places where you deliberately bypass your framework's protections, since flaws cluster there.
SQL injection and cross-site scripting share one root cause: text supplied by someone else gets treated as instructions. In SQL injection, your database reads input as part of a query. In cross-site scripting (XSS), a visitor's browser reads input as part of your page's code.
The fix for both is to keep data and code apart. Use parameterized queries for databases, encode output for the place it lands on a page, and add further layers so a single mistake does less damage. This guide is about recognizing and preventing these flaws in code you build.
The shared idea: data that turns into code
Your application constantly builds text for other interpreters: SQL for a database, HTML for a browser, command lines for a shell, file paths for the operating system. Each has characters with special meaning, such as quotes, angle brackets and semicolons.
If you join your text and a stranger's text into one string, the interpreter can't tell which parts you wrote. A value that contains the right special characters can end the data portion early and be read as instructions.
Untrusted input is broader than form fields. It includes URL parameters, cookies, request headers, uploaded file names, data from outside APIs, imported spreadsheets and anything previously stored in your own database that originally came from a user.
How SQL injection happens
Consider a login lookup built by joining strings:
query = "SELECT id FROM users WHERE email = '" + email + "'" The author expects email to be an address. A quote character in the value closes the string early, and whatever follows becomes part of the SQL. Even an innocent name containing an apostrophe breaks this query, which is a good early warning sign.
The consequences can include reading other people's records, changing or deleting data and bypassing sign-in checks. How far it goes depends on what the database account is allowed to do.
Fix it with parameterized queries
A parameterized query, often implemented as a prepared statement, puts placeholders in the SQL and passes values separately. The database parses the structure first, so a value stays a value no matter which characters it holds.
# Python with a DB-API driver such as sqlite3
cursor.execute("SELECT id FROM users WHERE email = ?", (email,)) // Node.js with a PostgreSQL client
await db.query("SELECT id FROM users WHERE email = $1", [email]); // PHP with PDO
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]); Placeholder syntax varies by driver. The important part is that your code never inserts the value into the query string itself.
Placeholders work for values, not for table names, column names or keywords such as ASC and DESC. When users choose a sort column, map their choice to a fixed list you wrote:
allowed = {"name": "name", "date": "created_at"}
column = allowed.get(requested_sort, "created_at") Object-relational mappers parameterize their normal methods, but most also offer raw query functions. Search your code for those and check each one. Stored procedures are safe only if they don't build SQL by joining strings internally.
How cross-site scripting happens
XSS occurs when your site delivers someone else's script to a visitor's browser as if it were yours. Because it runs under your domain, it can read page content, send requests as the signed-in user and change what the person sees, for example by showing a fake sign-in form.
It comes in three broad forms.
- Stored XSS: harmful content is saved on your server, such as in a comment or profile field, and served to everyone who views it.
- Reflected XSS: content from the request, such as a search term in the URL, is echoed straight back into the response.
- DOM-based XSS: the flaw sits in your front-end JavaScript, which takes a value from the address bar or a message and writes it into the page unsafely.
The third kind may never appear in server logs, so server-side checks alone will miss it.
Encode output for its context
Output encoding converts special characters into a harmless representation. In HTML, < becomes <, so the browser displays a less-than sign instead of starting a tag.
The correct encoding depends on where the value goes. HTML body text, attribute values, URLs, JavaScript and CSS each have different rules. Template engines such as those in common web frameworks escape HTML automatically, and libraries such as React do the same for text content.
Problems cluster in the escape hatches:
- template filters or flags that mark text as "safe" or "raw"
-
innerHTML,outerHTMLanddocument.writein browser code - React's
dangerouslySetInnerHTMLand similar features - user-supplied URLs placed in
href, where ajavascript:scheme would execute
In browser code, prefer textContent for text, as discussed in the DOM explained. For links, accept only the schemes you expect, such as https:.
If users may submit formatted HTML, run it through a well-maintained sanitizer library that keeps an allow list of tags and attributes. Writing your own filter with pattern matching tends to miss cases. The HTML entity encoder is handy for seeing what encoded text looks like.
The same mistake in other places
Once you recognize the pattern, you'll see it beyond databases and web pages.
Shell commands. Building a command line from a file name or a domain name invites command injection. Use your language's functions that pass arguments as a list without invoking a shell, or avoid the external program altogether by using a library.
File paths. A download feature that appends a requested name to a folder can be steered outside that folder with .. segments. Look files up by an ID you control, or resolve the final path and confirm it is still inside the intended directory.
Other query languages. Document databases, directory services and XML queries have their own syntax. A request body that arrives as an object where you expected a string can change a document query, so check types as well as content.
Spreadsheets and email. A value beginning with = in an exported file may be treated as a formula by spreadsheet software, a hazard described in CSV pitfalls. Line breaks placed into email header fields can add headers if a mail function doesn't reject them.
The question to ask each time is the same: which program will read this string, and which characters mean something to it?
Add layers that limit damage
No single control catches every mistake, so combine several.
Validate input. Check that a quantity is a number in range, that a date parses, that a choice is on your list. This improves data quality and removes many surprises. It can't be your only defense, because legitimate text often contains quotes and brackets.
Give accounts least privilege. The web application's database user rarely needs to drop tables or read unrelated databases.
Hide details in errors. Show visitors a generic message and log the specifics privately.
Protect session cookies. The HttpOnly attribute keeps scripts from reading a cookie, and Secure and SameSite limit where it travels. XSS can still act through the page, so this reduces harm without removing it. See how cookies work.
Set a Content Security Policy. It tells the browser which scripts may run, which can stop an injected one. Setup is covered in CSP in practice.
Consider a web application firewall. A WAF can filter some hostile requests, but treat it as a safety net while you fix the code.
Find flaws in your own code
Start with a review. Search for query strings assembled with +, template literals or string formatting, and for every raw HTML escape hatch. Trace each one back to where its data originates.
Static analysis tools and dependency scanners can automate part of this and run on every change. Keep frameworks and libraries updated, since flaws in them are found and patched regularly.
Dynamic scanners probe a running application. Run them only against systems you own or are authorized in writing to test, preferably a staging copy with fake data, because they can create or damage records. The comparison of testing and scanning explains when to bring in professionals.
Add regression tests: feed names containing apostrophes and text containing angle brackets through your forms, and assert that they are stored and displayed literally.
If you find a vulnerability
Fix the immediate flaw, then search for the same pattern elsewhere, because it is rarely unique. Review logs for signs of use. If data may have been exposed, rotate affected credentials and session keys, and get advice on your notification duties, which differ by jurisdiction.
Publish a simple way for outside researchers to report problems to you, such as a security contact address. A clear channel makes it more likely you hear about a flaw from someone who wants it fixed, as described in responsible disclosure.