CodeBlanks Logo Icon CodeBlanks

Summary - Security

JavaScript course · Expert · Lesson 30/63

Build a safe comment render function with textContent, an escape function and CSP headers.

Summary - Security

In this group you learned about XSS attacks and their defenses. Three main topics: safe DOM updates (textContent), avoiding eval for dynamic access, and escaping input data.

You can also tell the browser which sources are safe with Content-Security-Policy and grant selective permission with a nonce. Together these layers give defense in depth.

Exercise Render a comment safely

Write a function renderComment, parameter comment. Create an element with const el = document.createElement('div'). Assign the comment with el.textContent = comment. Return the element with return el.

Show example solution
First define the function, then create the div element, assign comment to textContent, finally return el.
Example solution:
function renderComment(comment) {
  const el = document.createElement('div');
  el.textContent = comment;
  return el;
}

Exercise Escape a comment and write it safely

Write a function showComment, parameter text. Escape the text with const safe = escapeHtml(text). Create an element with const el = document.createElement('div'). Assign el.textContent = safe. Add it to the page with document.body.appendChild(el).

Show example solution
First escape, then create the div, then assign to textContent, finally append to body.
Example solution:
function showComment(text) {
  const safe = escapeHtml(text);
  const el = document.createElement('div');
  el.textContent = safe;
  document.body.appendChild(el);
}

Test yourself

  1. Match the security concepts

    textContent
    safe text
    innerHTML
    risky HTML
    eval
    runs code
    nonce
    single use
  2. Which is the most effective defense against XSS?

    • Escape user input and write it with textContent
    • Write the input directly to innerHTML
    • Run the input with eval
    • Save the input to localStorage
    Show answer

    Escape user input and write it with textContent — Correct! Escaping plus textContent stops XSS at its root.

All lessons in Expert