Input Sanitization & Injection Prevention
Defend edge applications against XSS, SQL injection, and related attacks by sanitizing input and encoding output correctly.
Input Sanitization & Injection Prevention is a free Edge Computing with Cloudflare Workers & Deno lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Edge Computing with Cloudflare Workers & Deno learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Sanitization Matters
Even at the edge, untrusted input is the root of most attacks. Sanitization and proper output encoding stop:
- Cross-Site Scripting (XSS)
- SQL / query injection
- Header and log injection
Validation checks shape, sanitization makes input safe to use.
Understanding XSS
XSS happens when attacker-controlled data is rendered as HTML and executes as script.
If a Worker echoes user input into a page without encoding, an attacker can inject scripts.
// Dangerous: user input goes straight into HTML
const html = '<div>' + userInput + '</div>';Output Encoding for HTML
The fix for XSS is context-aware output encoding. Escape HTML-special characters before rendering.
function escapeHtml(s) {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}Preventing SQL Injection
Never build SQL by string concatenation. Use parameterized queries, the D1 and Deno drivers bind values safely.
// Safe: bound parameter, never concatenated
const { results } = await env.DB
.prepare('SELECT * FROM users WHERE email = ?')
.bind(email)
.all();The Danger of Concatenation
Concatenated SQL lets an attacker break out of the intended query.
// NEVER do this
const sql = "SELECT * FROM users WHERE email = '" + email + "'";
// email = "' OR '1'='1" returns every rowValidate Then Sanitize
Combine both defenses: validate that input matches an expected pattern, then sanitize for the context it is used in.
const emailRe = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
if (!emailRe.test(email)) {
return new Response('Invalid email', { status: 400 });
}Header & Redirect Injection
User input placed into response headers or redirect URLs can inject newlines or open redirects.
- Strip CR/LF from header values
- Allowlist redirect destinations
const clean = value.replace(/[\r\n]/g, '');
headers.set('X-User-Tag', clean);Content Security Policy
A CSP header is a strong second line of defense against XSS, it restricts what scripts may run.
headers.set(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'"
);Sanitizing Rich HTML
When you must accept HTML (e.g. user comments), use a vetted sanitizer library rather than regex, allowlist safe tags and attributes.
import DOMPurify from 'isomorphic-dompurify';
const safe = DOMPurify.sanitize(userHtml);Defense in Depth
No single control is enough. Layer defenses:
- Validate input shape
- Use parameterized queries
- Encode output per context
- Set CSP and security headers
If one layer fails, the others still protect you.
Best Practices Summary
To keep edge apps safe:
- Treat all input as hostile
- Never concatenate SQL or HTML with raw input
- Encode for the exact output context
- Add CSP and strip control characters from headers
Quick Check
What is the most reliable way to prevent SQL injection in a D1 query?
Recap
You hardened your app against injection:
- Encode output to stop XSS
- Use parameterized queries to stop SQL injection
- Strip control characters and allowlist redirects
- Add CSP and sanitize rich HTML with a trusted library
Defense in depth keeps edge applications resilient even when one layer slips.
Frequently asked questions
Is the “Input Sanitization & Injection Prevention” lesson free?
Yes — the full text of “Input Sanitization & Injection Prevention” is free to read here on the web, and the Edge Computing with Cloudflare Workers & Deno course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Edge Computing with Cloudflare Workers & Deno course, upgrade to CoddyKit PRO.
What will I learn in “Input Sanitization & Injection Prevention”?
Defend edge applications against XSS, SQL injection, and related attacks by sanitizing input and encoding output correctly. You practise Edge Computing with Cloudflare Workers & Deno with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Edge Computing with Cloudflare Workers & Deno?
No prior experience is required. Edge Computing with Cloudflare Workers & Deno on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Input Sanitization & Injection Prevention” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Edge Computing with Cloudflare Workers & Deno lesson?
Yes. Every Edge Computing with Cloudflare Workers & Deno lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Authentication & Authorization
- Rate Limiting & DDoS Protection
- Secure Secrets Management
- Input Sanitization & Injection Prevention