sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEIntermediate3 min read

What is cross-site scripting and how do you reduce the risk?

XSS occurs when untrusted input runs as script in another user's browser.

Frontend Quality#security#browser
THE ANSWER / PLAIN ENGLISH

The idea to remember.

XSS occurs when untrusted input runs as script in another user's browser. Escape output, avoid unsafe HTML insertion and use a carefully configured content security policy as defense in depth.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: test visible behavior

01 / BEGINNER

Prefer what users can see to implementation details.

JSX / EXAMPLE
test('shows a heading', () => {
  render(<Questions />);
  expect(screen.getByRole('heading', { name: /questions/i })).toBeVisible();
});

Intermediate: test asynchronous UI

02 / INTERMEDIATE

Wait for an accessible result instead of sleeping a fixed interval.

JSX / EXAMPLE
test('loads results', async () => {
  render(<SearchPage />);
  await user.click(screen.getByRole('button', { name: /search/i }));
  expect(await screen.findByText('Results ready')).toBeVisible();
});

Real scenario: protect an API route

03 / REAL SCENARIO

Apply validation and authorization server-side; client checks improve UX only.

JSX / EXAMPLE
app.post('/api/orders', authenticate, async (req, res) => {
  if (!isValidOrder(req.body)) return res.status(400).json({ error: 'Invalid order' });
  if (!canOrder(req.user, req.body)) return res.status(403).end();
  res.json(await createOrder(req.user.id, req.body));
});

Try it in your own words.

Explain what is cross-site scripting and how do you reduce the risk without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse Frontend Quality study guides ↗
← Back to question library

Have something
in mind?

Start a conversation