Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 21.3 — Unsafe URLs and Attributes
React · Example 2 of 3

Validate user URLs with an allow-list

new URL with no base rejects ravi.example.com (it has no scheme), so it's shown as plain text; you could try again with https:// in front if you want to be friendly. The parser lower-cases the scheme and host, so HTTPS://Shop... is recognised and normalised. Links that pass open in a new tab with rel="noopener noreferrer".

A URL can carry code (javascript:), point somewhere harmful, or hand your page to another tab. React 19 blocks javascript: URLs, but you still validate user URLs with new URL and a protocol allow-list, add rel="noopener noreferrer" to new-tab links, and never spread untrusted objects into props.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write ExternalLink that validates its href, opens in a new tab safely, and tells screen reader users it opens a new tab.

02

Write safeRedirect(next) and show its result for /orders?id=7, //evil.example, https://evil.example and undefined.

03

A Card does <div {...card}>. The API returns { title, body, id }. Rewrite it safely.

Explain it without notes

01

What does React 19 do with a javascript: URL in href, and what doesn't it protect you from?

02

How do you validate a URL a user typed, and why not with a regex or startsWith?

03

What is an open redirect, and how do you prevent one in a React Router app?

04

Why is <Component {...apiData} /> dangerous?

Validate user URLs with an allow-list

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

"https://asha.dev/blog" -> https://asha.dev/blog
"ravi.example.com" -> null
"data:text/html,hi" -> null
"javascript:void(0)" -> null
"mailto:hi@asha.dev" -> mailto:hi@asha.dev
"HTTPS://Shop.Example.com" -> https://shop.example.com/