1. Content-Security-Policy
default-src 'self' tells the browser to load resources only from your own origin, blocking most injected scripts.
res.setHeader("Content-Security-Policy", "default-src 'self'");Typorithm · medium
Step 1 of 8 · intro card
Web Security (OWASP)
CSRF tricks a logged-in user's browser into making an unwanted request. The defenses are SameSite cookies and anti-CSRF tokens. Security headers — CSP, HSTS, X-Frame-Options — and httpOnly cookies harden the browser side.
Cross-Site Request Forgery abuses the fact that browsers attach a user's cookies to requests automatically. A malicious page can trigger a request to your site, and the browser sends the victim's session cookie along, performing an action as them without their consent.
The primary defenses are SameSite cookies and anti-CSRF tokens. sameSite: 'strict' tells the browser not to send the session cookie on requests that originate from another site, which neutralizes the classic CSRF flow. Anti-CSRF tokens add a secret the attacker's page cannot guess.
Security headers harden the rest of the browser surface: Content-Security-Policy limits where scripts and resources may come from, X-Frame-Options: DENY prevents clickjacking via framing, and Strict-Transport-Security forces HTTPS. Marking the session cookie httpOnly keeps it out of reach of any injected JavaScript.
CSRF rides the user's auto-sent cookies.
SameSite cookies and CSRF tokens are the core fix.
CSP, HSTS, X-Frame-Options, httpOnly harden the browser.
res.setHeader("Content-Security-Policy", "default-src 'self'");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Strict-Transport-Security", "max-age=63072000");
res.cookie("session", id, { httpOnly: true, sameSite: "strict" });Connect each part of the code to the concept before you type.
default-src 'self' tells the browser to load resources only from your own origin, blocking most injected scripts.
res.setHeader("Content-Security-Policy", "default-src 'self'");DENY stops the page from being embedded in a frame, preventing clickjacking.
res.setHeader("X-Frame-Options", "DENY");Strict-Transport-Security forces HTTPS for the given max-age, stopping protocol-downgrade attacks.
res.setHeader("Strict-Transport-Security", "max-age=63072000");httpOnly hides the cookie from JavaScript and sameSite: strict stops it being sent on cross-site requests, blunting CSRF.
res.cookie("session", id, { httpOnly: true, sameSite: "strict" });SameSite strict means the cookie is never attached to requests originating from another site, which is the core CSRF defense.
sameSite: "strict"Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.