javascript / beginner
Snippet
Preventing Cross-Site Scripting by Avoiding Unsafe HTML Injection
Cross-Site Scripting (XSS) is avoided in Next.js components by rendering variables directly in JSX, allowing React to automatically escape potentially malicious scripts.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
// app/profile/page.jsexport default function UserProfile({ searchParams }) {// Safe: React automatically escapes strings inside JSX tagsconst username = searchParams.name || 'Guest';return (<div><h1>Welcome, {username}!</h1></div>);}
nextjs
Breakdown
1
export default function UserProfile({ searchParams }) {
Declares a Next.js page component accepting URL query parameters.
2
const username = searchParams.name || 'Guest';
Extracts the untrusted user input string or falls back to a default value.
3
<h1>Welcome, {username}!</h1>
Safely renders the user input inside JSX text nodes with automatic escaping.