Project: Secure comments app
Overview of the 5-lesson secure comments project: XSS-safe rendering and CSP.
Project: Secure comments app
In this 5-lesson project we'll build a secure comments app. The user writes a comment in a form; the app adds it to the list safely.
The structure we'll build step by step:
- Comment form and container selection
- Submit listener and input reading
- XSS-safe rendering with
textContentandescapeHtml - CSP meta tag and script
nonce - App init and input clearing
Each lesson continues on top of the previous one's solution.
Project structure
Our app has two parts: a form and a container. We'll add the text from the form to the container safely.
We'll use two security layers:
textContentto insert text as plain text, not HTML- A CSP meta tag to allow scripts only from safe sources
Together these layers block both DOM injection and script execution.
Exercise Select container and form
The page has <div id="comments"> and <form id="commentForm"> elements ready. Select the #comments element into commentsEl and the #commentForm element into commentForm using document.querySelector.
Show example solution
const commentsEl = document.querySelector("#comments");
const commentForm = document.querySelector("#commentForm");
Test yourself
-
Which property creates an XSS risk?
el.____ = userInput;- textContent
- createElement
- innerHTML
- appendChild
Show answer
innerHTML — Correct! innerHTML parses raw HTML and can run scripts.
-
Write the safe property
const p = document.createElement("p"); p.____ = userInput;Show answer
const p = document.createElement("p"); p.textContent = userInput; -
Match the security terms
- XSS
- Malicious script injection
- textContent
- Plain text insertion
- CSP
- Script source restriction
- nonce
- One-time value