XSS, CSRF, SQL Injection, and Common Web Security Risks
🎯 Introduction
By the end of this article, you will be able to map common attacks to concrete input, identity, and data access protections.
🧱 XSS: Untrusted content executes as script
Cross-site scripting (XSS) occurs when a website treats untrusted input as executable page content. For example, rendering a user biography as HTML may allow embedded scripts to read data or perform actions under the website's identity.
Render ordinary text as text. Vue interpolation treats values as text by default; do not use v-html merely to display a user biography. If rich text is required, use a maintained HTML sanitizer with an allowlist of tags and attributes, rather than removing a few <script> strings.
Even when the backend returns the correct JSON media type, the frontend must render it appropriately. HttpOnly prevents scripts from reading cookies directly, but malicious scripts can still send requests from an authenticated page. It does not resolve XSS by itself.
🍪 CSRF: The browser automatically sends credentials for an unwanted action
Cross-site request forgery (CSRF) exploits automatically included login cookies to trigger a state-changing operation from another page. The attacker may not need to read the response; performing the operation alone can cause harm.
Cookie-authenticated write endpoints can check a trusted Origin and use a server-issued anti-forgery token. Bind the token to the session, submit it in a header from the legitimate page, and compare it on the server before executing business logic. Other websites normally cannot read it.
Create csrf-origin.mjs to demonstrate strict origin checking for browser write requests:
export function requireTrustedOrigin(req, res, next) {
if (req.headers.origin !== 'https://app.example.com') {
return res.status(403).json({ error: 'Request origin is not allowed' });
}
next();
}
Use this Express route middleware before cookie-authenticated write endpoints. Only a successful check calls next and enters business processing. This policy also rejects requests without Origin and suits endpoints that explicitly require a browser origin. Server-to-server calls should use separate authentication rather than weakening browser write checks for compatibility.
SameSite is an additional restriction, and GET must not modify business data. XSS in a trusted page may also expose anti-forgery tokens, so address both risks separately.
🗃 SQL injection: Input changes the query's meaning
Never concatenate a username into SQL. Use driver parameter binding so input is compared as a value rather than executed as SQL structure.
This function accepts an established mysql2 Promise connection and uses the practice table from the MySQL Integration course:
export async function findByName(connection, name) {
const [rows] = await connection.execute(
'SELECT id, username FROM user WHERE username = ?', [name]
);
return rows;
}
Call it from a Repository data query function. It returns matching rows, or an empty array if none match. Quotes in user input must remain name content rather than change query conditions.
Column and table names cannot generally be replaced with value placeholders. Map them from an allowlist, as in the list endpoint article. Parameter binding does not replace authorization.
📁 File paths and external URLs also cross trust boundaries
Do not append a client-supplied filename to a server directory and read it directly: it may target configuration outside that directory. Use server-generated file IDs, look up controlled storage records, and then determine the read location.
Requesting arbitrary client-supplied URLs on the server may expose internal services. This is server-side request forgery (SSRF). Prefer server-configured addresses and allowed paths for third-party integrations, and limit redirects, timeouts, and response size.
Do not concatenate user input into shell commands either. Validate parameters where they are actually used, not only in page forms.
🔎 Verify that protections actually work
| Scenario | Expected result |
|---|---|
| User biography contains HTML tags | Display as text or sanitize strictly before rendering |
| Write endpoint receives an untrusted Origin | Reject before modification; data remains unchanged |
| Username contains quotes | Treat as an ordinary query value without changing SQL structure |
| File request contains path traversal content | Never access an arbitrary disk path |
| Client submits an internal service address | Do not accept it as an arbitrary request target |
Security checks must prevent disallowed effects. “No error occurred” is not a sufficient acceptance criterion.
❓ Questions and Answers
Q1: Is replacing certain characters in all input sufficient?
No. HTML, SQL, paths, and commands follow different rules. Use appropriate encoding, binding, or allowlists at each point of use.
Q2: Can CORS prevent every cross-site write request?
No. Some requests are sent without preflight. Verify CSRF protection on the server before changing data.
Q3: Is content safe from XSS if only logged-in users can submit it?
No. Authenticated accounts can submit malicious content that affects other users viewing it.
🧪 Practice
Identify a trust boundary for user biographies, SQL queries, and file downloads. List the observable result of successful protection for each.
// Write your code or record your verification results here
