← Interview prep

Frontend interview questions

Browser performance, accessibility, and frontend systems.

59 questions · Page 2 of 3

Want the full pack? Interview packs · Mock interview · Mentora

Page 2 of 3

Questions 21–40 of 59 · 0 of 20 on this page marked learned

21.frontend-0021Mediummid

How does a CDN decide what to cache, and what do s-maxage, Vary and a purge do?

A CDN stores responses at edge servers and serves them for a cache key made of the URL and the headers named in Vary. Cache-Control controls how long: s-maxage applies to shared caches only. A purge removes entries early when content changes before the time is over.

Full answer

A CDN (content delivery network) is a set of servers close to users. A request goes to the nearest edge server. If it holds a fresh copy, it answers at once. If not, it asks the origin, stores the response if the rules allow, and answers. This cuts distance, protects the origin from load and can absorb traffic spikes.

The main ideas to explain:

  • Cache key. The key normally includes the host and the URL path, and often the query string. If a response varies by header, the server lists the header in Vary, for example Vary: Accept-Encoding, and the CDN keeps one copy for each value. Vary: Cookie or a unique query parameter such as a tracking id can split the cache into thousands of entries and kill the hit rate.
  • Freshness. max-age applies to every cache. s-maxage applies only to shared caches such as a CDN and overrides max-age there. A common design is a short browser time with a longer CDN time: Cache-Control: public, max-age=60, s-maxage=3600.
  • Stale handling. stale-while-revalidate lets a cache answer with an old copy while it fetches a new one in the background. stale-if-error allows old copies when the origin fails. Check that your CDN supports these directives.
  • Purge. The origin can ask the CDN to delete an entry by URL or by tag after a content change. Purging is the escape hatch for content that changes at unknown times, but it is better to design URLs so that purging is rare, as hashed assets do.
  • Private data. Responses with private or user-specific data must not be stored in a shared cache.

Check the real behaviour with response headers. Many CDNs add a header that tells whether the response was a hit or a miss. The names differ between providers.

A useful rule: cache by default what is the same for everybody, and be explicit about what is not.

http
HTTP/1.1 200 OK
Cache-Control: public, max-age=60, s-maxage=3600, stale-while-revalidate=30
Vary: Accept-Encoding
ETag: "a1b2c3d4"
Content-Type: text/html; charset=utf-8

This is an example response header block. It was not run against a CDN, and the support for each directive depends on the provider.

Key points

  • An edge server answers from its cache and goes to the origin only on a miss.
  • The cache key is the URL plus headers listed in Vary.
  • s-maxage sets the time for shared caches only.
  • Purging removes content early. Hashed URLs avoid most purges.
  • Never cache user-specific responses in a shared cache.

Common mistakes

  • Using Vary: Cookie on a public page and destroying the hit rate.
  • Caching a response that sets a session cookie.
  • Relying on purge for every release instead of hashed asset names.
  • Assuming all CDNs use the same header names and defaults.

Follow-ups

  • How would you cache an API response that differs by language?
  • What is an origin shield?
  • How do you find out why a URL is a cache miss?

Tips

  • Explain the cache key first. Most real problems come from it.
  • Name the hit and miss headers as something to check for each provider.
22.frontend-0022Mediummid

What is a service worker, how does its lifecycle work, and how do you serve a file from the cache when the user is offline?

A service worker is a script that runs in the background and sits between the page and the network. It goes through install, waiting and activate, and once active it can answer fetch events from the Cache Storage, so a cached file works offline.

Full answer

A service worker is a JavaScript file registered by a page. It runs in its own thread, has no access to the DOM and works on the origin level. It needs a secure context: HTTPS, or localhost for development.

Lifecycle:

  1. Register. The page calls navigator.serviceWorker.register('/sw.js'). The scope defaults to the folder of the script, so a script at /sw.js can control the whole site.
  2. Install. The install event fires once for a new script. This is the place to pre-cache files with event.waitUntil(...). The worker does not move on until the promise settles.
  3. Waiting. If an older worker still controls open pages, the new one waits until those pages are closed, unless it calls skipWaiting().
  4. Activate. The activate event is the place to delete old caches. The worker controls only pages that load after activation, unless it calls clients.claim(). This is why the first visit is not controlled, and a reload is.
  5. Fetch. Each request from a controlled page triggers a fetch event. The worker calls event.respondWith(...) with a response from the cache, the network or a mix.

The snippet uses the simplest strategy, cache first. During install it stores / and /data.json. In fetch it answers from the cache if there is a match and falls back to the network. Offline, the stored files are still served.

Strategy choice is a design decision. Cache first suits files that never change at the same URL, such as hashed assets. Network first suits data that should be fresh and falls back to the cache offline. Stale-while-revalidate answers at once from the cache and updates it in the background.

Important limits: the cache has no automatic expiry, so you must manage versions. The Cache API stores only responses to GET requests. Storage is limited and the browser may remove it under pressure.

javascript
// page script: register the worker
if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js');

// ---- sw.js
const CACHE = 'static-v1';
self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(['/', '/data.json'])));
});
self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  event.respondWith(caches.match(event.request).then((hit) => hit || fetch(event.request)));
});

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. A local server on localhost was used, which counts as a secure context. After a reload the page was controlled, and with the browser set offline the cached data file and the home page were still returned. Other browsers and real network loss were not tested.

Key points

  • A service worker is a background script between the page and the network.
  • Lifecycle: register, install, waiting, activate, then fetch events.
  • Pre-cache in install. Delete old caches in activate.
  • A new page load is needed for control, unless clients.claim is used.
  • Choose cache first, network first or stale-while-revalidate per resource type.

Common mistakes

  • Testing on plain HTTP over a real host name, where registration is not allowed.
  • Expecting the worker to control the page on the first visit.
  • Caching HTML cache first, so users never see a new version.
  • Forgetting that the worker has no DOM access.

Follow-ups

  • What does event.waitUntil do?
  • How does a service worker differ from the HTTP cache?
  • When would you choose network first?

Tips

  • Walk through the lifecycle in order and say what each event is for.
  • Say why the first visit is not controlled, because it shows real experience.
23.frontend-0023Hardsenior

After a deploy, some users still see the old version of a site that has a service worker. How do you debug it and fix it?

Usually an old worker is still controlling open tabs, or the worker cached the HTML first and keeps serving it. Version the cache name, delete old caches on activate, serve sw.js with no-cache, and decide deliberately whether to use skipWaiting and clients.claim.

Full answer

Several separate causes produce the same symptom, so check them one by one.

  1. The old worker is still in control. A new worker installs and then waits while any page uses the old one. Users with a long-lived tab or a pinned tab stay on the old version. Check Application, Service Workers in DevTools: a worker in the waiting state is the sign.
  2. The worker caches the HTML. With cache first on navigations, the old HTML and the old file names are served until the worker itself changes. Use network first for navigation requests, or revalidate them.
  3. The sw.js file is cached by a CDN or a proxy. Browsers check the worker file on navigation and at most about every 24 hours, and they bypass the HTTP cache for the main script by default, but an edge cache in front of the origin can still serve an old copy. Serve sw.js with Cache-Control: no-cache.
  4. The cache is never cleaned. A cache named static is reused, so old and new files mix. A versioned name such as app-v2 lets the activate handler delete every other cache.
  5. The byte content of sw.js did not change. The browser only starts an update when the file differs. A build that embeds a release id or a manifest hash in the file solves this.

Fix choices:

  • skipWaiting() in install makes the new worker activate at once, and clients.claim() in activate takes control of open pages. This gets users to the new version fast, but an open page can now run old JavaScript with new cached files. Safer: show a banner such as "A new version is ready" and call skipWaiting when the user agrees, then reload.
  • Delete old caches in activate.
  • Keep a kill switch: a worker that unregisters itself and clears the caches, ready to deploy if a worker breaks the site.

The test starts a local server that serves a sw.js with a version in it. It registers version 1, changes the server to version 2, calls registration.update() and checks that the cache list changes from app-v1 to app-v2.

javascript
// sw.js (the release id is written in by the build)
const VERSION = 'v1';
const CACHE = `app-${VERSION}`;

self.addEventListener('install', (event) => {
  self.skipWaiting();
  event.waitUntil(caches.open(CACHE).then((cache) => cache.add('/data.json')));
});

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    for (const key of await caches.keys()) if (key !== CACHE) await caches.delete(key);
    await self.clients.claim();
  })());
});

self.addEventListener('fetch', (event) => {
  if (event.request.mode === 'navigate') return; // let the network handle pages
  event.respondWith(caches.match(event.request).then((hit) => hit || fetch(event.request)));
});

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. A local server returned sw.js with version v1, then v2. After registration.update() the cache list changed from app-v1 to app-v2. Several open tabs, CDN caching of sw.js and an update banner were not run.

Key points

  • An old worker keeps control while its tabs are open, and a new one waits.
  • Cache-first HTML pins users to old file names.
  • Serve sw.js with no-cache and make sure its bytes change per release.
  • Version cache names and delete old ones in activate.
  • Prefer a user-approved update over a forced skipWaiting.

Common mistakes

  • Hard refreshing the page and thinking the problem is solved for every user.
  • Caching sw.js for a long time.
  • Using skipWaiting without thinking about pages that already run old code.
  • Changing the files but not the worker bytes, so no update starts.

Follow-ups

  • What is a kill switch worker?
  • How would you tell users that a new version is ready?
  • What does updateViaCache control?

Tips

  • Give a checklist in order of likelihood, then the fix and the safer UX.
  • Say how you would verify the fix on a real user's browser with DevTools.
24.frontend-0024Mediummid

What is static site generation, and how does incremental static regeneration (ISR) keep static pages fresh?

SSG builds HTML ahead of time and serves it from a CDN, which is fast but only as fresh as the last build. ISR keeps the pages static but rebuilds a page in the background after a set time, so the next visitor gets a newer copy without a full site rebuild.

Full answer

Static site generation (SSG) renders pages at build time. The output is plain HTML files, which any CDN can serve with very low latency and no server work per request. It is a good fit for docs, blogs and marketing pages. The weak point is freshness: a changed price or a new article appears only after the next build, and a site with 100,000 pages can take a long time to rebuild.

Incremental static regeneration (ISR) is a common answer in frameworks such as Next.js. The page stays static, with a revalidation time, for example 60 seconds.

  • Within the time, every visitor gets the stored page.
  • After the time, the next visitor still gets the stored (stale) page. At the same moment, the server regenerates the page in the background.
  • When regeneration ends, the stored page is replaced, and later visitors get the new one.
  • Pages that were not built yet can be generated on the first request and then stored.
  • Many frameworks also allow on-demand revalidation, so a CMS webhook can refresh one page at once.

This is the same idea as the HTTP directive stale-while-revalidate, applied to a page store. The trade-off is that one visitor can see a copy that is older than the revalidation time, and the freshness is "eventually".

Do not use SSG or ISR for pages that differ for each user. Fetch personal parts in the browser after load, or use SSR for those routes.

The script below models the idea with a fake clock. The first request builds the page. A request after 30 seconds is served from the store. A request after 61 seconds gets the stale page and starts a rebuild. The next request gets the new page. This is a small model, not the code of a framework.

javascript
function createIsr(render, revalidateMs, now) {
  let page = null, builtAt = 0, pending = null;
  return {
    async get() {
      if (!page) { page = await render(); builtAt = now(); return { html: page, status: 'MISS' }; }
      if (now() - builtAt < revalidateMs) return { html: page, status: 'HIT' };
      if (!pending) {
        pending = render().then((html) => { page = html; builtAt = now(); pending = null; });
      }
      return { html: page, status: 'STALE', done: pending };
    },
  };
}

let clock = 0, version = 1;
const isr = createIsr(async () => `<p>price v${version}</p>`, 60_000, () => clock);
async function visit() {
  const r = await isr.get();
  console.log(`${clock / 1000}s ${r.status} ${r.html}`);
  return r;
}

await visit();               // first build
version = 2; clock = 30_000;
await visit();               // still fresh, old content
clock = 61_000;
const stale = await visit(); // stale copy is served, rebuild starts
await stale.done;
clock = 62_000;
await visit();               // new content

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node and the output was identical in two runs. The code is a small model of the idea with a fake clock. It is not the implementation of any framework, and no CDN or build was run.

Key points

  • SSG renders HTML at build time and serves it from a CDN.
  • Its weakness is freshness and long builds for many pages.
  • ISR serves a stored page, then rebuilds it in the background after the time is over.
  • On-demand revalidation refreshes a page when the content changes.
  • Personalised content does not belong in a static page.

Common mistakes

  • Thinking ISR removes the stale page: one visitor still gets the old copy.
  • Using SSG for pages that depend on the logged-in user.
  • Setting a revalidation time of a few seconds, which acts like SSR with extra complexity.
  • Forgetting that a CDN in front can add its own caching.

Follow-ups

  • How does on-demand revalidation differ from a time-based one?
  • What happens if the regeneration fails?
  • How would you show prices that must always be current?

Tips

  • Describe the three states: first build, hit and stale.
  • Relate ISR to stale-while-revalidate to show that it is a known pattern.
25.frontend-0025Mediummid

What is hydration, and what causes a hydration mismatch? How do you debug one?

Hydration attaches event handlers and state to HTML that the server already produced, reusing the existing nodes. A mismatch happens when the first client render produces different output than the server HTML, for example because of dates, random values or browser-only checks.

Full answer

With SSR or static generation, the browser first shows HTML that is not interactive: it has no click handlers and no state. When the JavaScript bundle loads, the framework runs the same components in the browser and walks the existing DOM next to the output. If they agree, it keeps the existing nodes and attaches the listeners. This is hydration. Compared with a full client render, it avoids throwing away and rebuilding the DOM, but the JavaScript still has to download and run, so a page can look ready and not respond for a moment.

A hydration mismatch is when the server HTML and the first client render are different. Typical causes:

  • Values that change between server and browser: Date.now(), new Date() with time zones, Math.random(), generated ids.
  • Code that reads browser-only data during render: window.innerWidth, localStorage, navigator.language.
  • Data that differs: the server rendered with one response and the client got another.
  • Invalid HTML nesting, such as a div inside a p. The parser repairs it, and the DOM no longer matches the markup that the framework expects.
  • Browser extensions or translators that change the DOM before hydration.

Frameworks react in different ways. React logs a warning or error in development and may discard the server HTML and render again on the client. The user can see a flicker, and the performance gain is lost.

Fixes:

  1. Make the first render depend only on data that is the same on both sides. Pass the server time or a seed as a prop.
  2. Move browser-only values into an effect, which runs only after hydration. Render a neutral value first.
  3. Use the framework's escape hatch for an unavoidable difference, such as suppressHydrationWarning in React for a timestamp text.
  4. Validate the HTML nesting.

The page below is a small model without a framework. The button in the HTML came from the server. Hydration checks that the markup agrees with what the client would render, then reuses the same node and adds the handler. If the numbers disagree, the check reports a mismatch.

html
<div id="app"><button id="like" type="button">Likes: 3</button></div>
<script>
  const render = (state) => `<button id="like" type="button">Likes: ${state.likes}</button>`;
  const state = { likes: 3 };
  const app = document.getElementById('app');
  const serverNode = app.firstElementChild;

  // Hydrate: compare, then reuse the existing node and attach the handler.
  window.mismatch = app.innerHTML !== render(state);
  if (!window.mismatch) {
    serverNode.addEventListener('click', () => {
      state.likes += 1;
      serverNode.textContent = `Likes: ${state.likes}`;
    });
  }
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The click handler updated the same button node twice, and changed server markup made the check report a mismatch. This is a small model without a framework. A real framework hydration error was not run.

Key points

  • Hydration reuses server HTML and attaches handlers and state.
  • A mismatch means the first client render differs from the server HTML.
  • Dates, random values and browser-only reads during render are the usual causes.
  • Move browser-only values into an effect, and pass shared data as props.
  • Mismatches can cost the performance gain and cause flicker.

Common mistakes

  • Reading window or localStorage directly in the render function.
  • Using the current time in the first render.
  • Hiding the warning instead of removing the cause.
  • Assuming a hydrated page is interactive as soon as it is visible.

Follow-ups

  • Why does invalid HTML nesting cause a mismatch?
  • What are islands and partial hydration?
  • How can you measure the time between a visible page and an interactive one?

Tips

  • List causes in two groups: different values and different data.
  • Give the effect fix, which is the one interviewers want.
26.frontend-0026Hardsenior

What is streaming server rendering, and how do selective hydration, islands and server components reduce the JavaScript sent to the browser?

Streaming sends the HTML in pieces: the shell first, and slow parts later as their data becomes ready. Selective hydration, islands and server components then limit how much JavaScript must run, by hydrating only the interactive parts, or by never sending code for parts that need no interactivity.

Full answer

Classic SSR waits for all data before it sends anything. One slow query delays the whole page and raises TTFB. Streaming uses chunked transfer encoding: the server writes the shell with the header and the main content at once, flushes it, and writes slower sections later when their data is ready. The browser parses and paints the first chunk while the rest is still coming. This helps TTFB and LCP when the main content is fast and a small section is slow.

Frameworks build on this in different ways:

  • Suspense boundaries mark the parts that may arrive late. The server sends a placeholder first, and later sends the real content with a small inline script or instruction that swaps it in.
  • Selective hydration lets the client hydrate parts as their code arrives, and in React it can prioritise the part the user clicked on.
  • Islands architecture renders the page as static HTML and hydrates only marked interactive islands such as a search box or a video player. Everything else needs no JavaScript.
  • Server components run only on the server. Their code and large dependencies, such as a Markdown parser, never go to the browser, and only the output is sent. Interactive client components are still hydrated.

Cost and risks:

  • Streaming makes the status code and headers fixed before the slow part runs, so an error later cannot change the status to 500. Handle errors in the stream.
  • Some proxies buffer responses and defeat streaming. Test the real deployment path.
  • Crawlers and users without JavaScript still get the HTML, which is useful.

The Node script writes the shell, waits 150 milliseconds, and writes the rest. A client reads the response as a stream and shows that the shell arrived before the slow part.

javascript
import http from 'node:http';

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const server = http.createServer(async (req, res) => {
  res.setHeader('content-type', 'text/html');
  res.write('<!doctype html><h1>Course</h1><p>Shell is ready</p>');
  await sleep(150);                       // a slow query
  res.end('<ul><li>Recommended lesson</li></ul>');
});
await new Promise((resolve) => server.listen(0, resolve));

const res = await fetch(`http://localhost:${server.address().port}/`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
const start = performance.now();
const seen = [];
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  seen.push({ at: performance.now() - start, text: decoder.decode(value) });
}
console.log('shell came first:', seen[0].text.includes('Shell is ready'));
console.log('slow part came later:', seen.at(-1).text.includes('Recommended') && seen.at(-1).at - seen[0].at > 100);
server.close();

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node and the output was identical in two runs. The timing check uses a wide margin. A framework with Suspense, a proxy or a CDN was not used.

Key points

  • Streaming flushes the shell first and sends slow parts when ready.
  • It helps TTFB and LCP when only a small part of the page is slow.
  • Selective hydration and islands limit the code that runs in the browser.
  • Server components keep code and dependencies off the client.
  • After streaming starts the status code cannot change.

Common mistakes

  • Assuming streaming makes the total work smaller. It only changes when the user sees the parts.
  • Forgetting that a proxy can buffer the response.
  • Putting the LCP element behind a slow Suspense boundary.
  • Treating islands and server components as the same thing.

Follow-ups

  • How do you handle an error that happens after the shell was sent?
  • What does a client component boundary mean in a server component tree?
  • Which metric can get worse with streaming?

Tips

  • Explain the mechanism first (chunks), then the framework names.
  • Name one risk, such as buffering or status codes, to show depth.
27.frontend-0027Mediummid

Which parts of a page does the front end control for search, and how do you add a title, a canonical link and structured data correctly?

The front end controls the unique title and description, one canonical URL, a clear heading structure, links that crawlers can follow, social metadata and JSON-LD structured data. Most of it must be in the HTML that the server returns, so it works before JavaScript runs.

Full answer

Search engines read the HTML, follow links and try to understand the page. The front end can help with these items:

  • A unique <title> for each page that describes the page, and a unique meta name="description" that can be used as the snippet. Neither is a direct ranking promise, but both affect how the result looks and whether people click.
  • One <link rel="canonical"> with an absolute URL, pointing to the preferred address of the content. It handles duplicates caused by query strings or alternative paths.
  • A single clear h1 and an ordered heading outline. Use real headings and links (<a href>), because a div with a click handler cannot be followed.
  • The correct status code. A missing page must return 404, not a 200 page that says "not found". This is a server or framework setting, and single-page apps often get it wrong.
  • meta name="robots" or an X-Robots-Tag header only for pages that must not be indexed. A mistaken noindex on production is a classic launch bug.
  • Open Graph and Twitter Card tags control the preview when the link is shared.
  • Structured data in JSON-LD, which describes the page with the schema.org vocabulary, for example Course or Article. It is written in a script type="application/ld+json" block and must match the visible content.
  • Fast, stable pages. Core Web Vitals are part of the page experience signals, and a page that loads slowly can lose visitors whatever its ranking.

Rendering matters. Crawlers can run JavaScript, but rendering is queued and can be incomplete. Put the title, canonical link, main text and structured data in the server HTML or in the static HTML, and not only in code that runs after load.

The snippet is a head with these parts. The test parses it in Chrome and checks that the JSON-LD is valid, the canonical URL is absolute and there is one h1. Google's Rich Results Test was not run, so validate real pages with it.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Intro to Algebra: free online course | Schoolabe</title>
  <meta name="description" content="A beginner course on algebra with short lessons, practice questions and a final quiz.">
  <link rel="canonical" href="https://schoolabe.com/courses/intro-to-algebra">
  <meta property="og:title" content="Intro to Algebra">
  <script type="application/ld+json">
    { "@context": "https://schema.org", "@type": "Course",
      "name": "Intro to Algebra",
      "description": "A beginner course on algebra.",
      "provider": { "@type": "Organization", "name": "Schoolabe", "url": "https://schoolabe.com" } }
  </script>
</head>
<body>
  <h1>Intro to Algebra</h1>
  <a href="/courses">All courses</a>
</body>
</html>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome: the JSON-LD parses, the canonical URL is absolute and there is one h1. Rich result validation by a search engine was not run.

Key points

  • Unique title and description for each page, in the server HTML.
  • One absolute canonical URL, and real links and headings.
  • Return the right status code, and use noindex only on purpose.
  • JSON-LD must be valid and match the visible content.
  • Do not depend on late JavaScript for the important tags.

Common mistakes

  • Setting the title and meta tags only in client code that runs after load.
  • Returning 200 for a not-found page.
  • Using the same title and description on every page.
  • Adding structured data for content that is not on the page.

Follow-ups

  • How does a canonical link differ from a redirect?
  • How would you test what a crawler sees?
  • What does noindex do compared with a robots.txt disallow?

Tips

  • Group the items into content, URL, status and structured data.
  • Tie each item to what the server must send.
28.frontend-0028Hardsenior

A learning platform has a home page, a course catalogue, course pages with prices, a logged-in lesson player and a student dashboard. Which rendering strategy would you pick for each, and why?

Use static generation for the home page, incremental regeneration for the catalogue and course pages, client rendering for the logged-in player and dashboard, and SSR only where per-request data must be in the first HTML. The choice follows from how often the data changes, how personal it is, and whether search and first paint matter.

Full answer

A good answer states the questions first and then applies them to each page.

Questions to ask for every route:

  1. Is the content the same for everybody, or is it personal?
  2. How often does it change, and how bad is a stale copy?
  3. Does it need to be found by search or shared as a link?
  4. How much interactivity does it have?
  5. What is the traffic, and what does a server render cost at that traffic?

Applied to the five pages:

  • Home page: the same for everyone and changes rarely. Static generation, served from a CDN. Personal touches, such as a greeting, load in the browser after the first paint.
  • Course catalogue: mostly shared, changes when courses are added. ISR with a revalidation time of minutes, or on-demand revalidation when an editor publishes. Filters and search can run in the browser against a data endpoint.
  • Course pages with prices: needs search traffic and fast LCP, but prices change. ISR with on-demand revalidation when the price changes. If the price is different by country or promotion, render the page statically and fetch the final price on the client, or segment the cache by region at the CDN. If a wrong price has legal weight, show the price from the checkout service at the point of purchase.
  • Lesson player behind a login: personal, interactive, not indexed. CSR after an authenticated shell. Stream video separately, and prefetch the next lesson.
  • Student dashboard: personal and changes with each visit. CSR with data from authenticated APIs. SSR is possible if the first view must show data without a spinner, at the cost of server work and care about caching private data.

Trade-offs to say aloud:

  • Staleness against cost: more static means cheaper and faster, and fresher means more server work.
  • Consistency: a static page and a live API can disagree for a short time. Decide where the source of truth is.
  • Operational cost: one mixed framework is simpler than three separate systems.
  • Measure after the launch with field LCP, INP and server cost per page.

No choice is permanent. The decision is revisited when traffic or data patterns change.

Key points

  • Decide per route from personalisation, change rate, SEO need, interactivity and traffic.
  • Static for shared and rarely changing pages. ISR for shared pages that change.
  • CSR for private, interactive screens that are not indexed.
  • SSR for per-request content that must be in the first HTML.
  • State the staleness and cost trade-offs, and plan to measure.

Common mistakes

  • Picking one strategy for the whole site.
  • Using SSR for personal pages without thinking about caching private data.
  • Ignoring price consistency between a cached page and the checkout.
  • Choosing by trend instead of the data.

Follow-ups

  • How would you show a price that depends on the visitor's country?
  • What would change if the dashboard had to work offline?
  • How would you measure whether the choices worked?

Tips

  • Start with the five questions, because they show a method that works on any page.
  • Give a reason in one sentence for each page.
29.frontend-0029Mediummid

When does a browser send a CORS preflight request, and what must the server answer for the real request to go ahead?

A preflight is an automatic OPTIONS request that the browser sends before a cross-origin request that is not simple, for example one with a method such as PUT or DELETE, a JSON content type or an Authorization header. The server must answer with the allowed methods and headers, and only then does the browser send the real request.

Full answer

A cross-origin request is "simple" when it uses GET, HEAD or POST, has only a few safe headers, and for POST uses a content type of application/x-www-form-urlencoded, multipart/form-data or text/plain. These are the kinds of requests that an HTML form could already send before CORS existed, so the browser sends them straight away and then checks the response headers.

Anything else needs a preflight. Common triggers:

  • A method other than GET, HEAD or POST, such as PUT, PATCH or DELETE.
  • Content-Type: application/json.
  • A custom header such as Authorization or X-Request-Id.

The browser first sends OPTIONS with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server answers, usually with status 204 and these headers:

  • Access-Control-Allow-Origin: the allowed origin.
  • Access-Control-Allow-Methods: the methods the real request may use.
  • Access-Control-Allow-Headers: the headers the real request may send.
  • Access-Control-Max-Age: how many seconds the browser may remember the answer, which saves a round trip on later calls. Browsers cap this value.

If the preflight fails or does not list a method or header, the browser never sends the real request, and the page sees a network error. The server log then shows only OPTIONS.

The preflight request carries no cookies, so protect the OPTIONS route accordingly: it must not require authentication, or it will always fail. When credentials are used on the real request, the answer must also include Access-Control-Allow-Credentials: true and a specific origin.

In the test, the page sends a PUT with a JSON body and an Authorization header. The server log shows OPTIONS then PUT. When the server forgets to allow Authorization, the log shows OPTIONS only.

Preflights cost latency. Reduce them with Access-Control-Max-Age, by keeping the API on the same origin behind a proxy, or by avoiding custom headers where a simple request is enough.

javascript
import http from 'node:http';

const allowedOrigin = process.env.ALLOWED ?? 'https://app.example.com';
const seen = [];

http.createServer((req, res) => {
  if (req.url === '/seen') return res.end(JSON.stringify(seen));
  seen.push(req.method);
  if (req.headers.origin === allowedOrigin) {
    res.setHeader('Access-Control-Allow-Origin', allowedOrigin);
    res.setHeader('Vary', 'Origin');
  }
  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Max-Age', '600');
    res.statusCode = 204;
    return res.end();
  }
  res.end('saved');
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The page and the API ran on different localhost ports. The PUT with a JSON body and Authorization header gave OPTIONS then PUT. When Authorization was left out of Allow-Headers, only OPTIONS reached the server. A simple GET sent no preflight.

Key points

  • Non-simple requests trigger an automatic OPTIONS preflight.
  • Triggers: methods like PUT or DELETE, JSON content type, custom headers.
  • The server must list the method and headers the real request will use.
  • If the preflight fails, the real request is never sent.
  • Access-Control-Max-Age caches the answer for a limited time.

Common mistakes

  • Requiring authentication on the OPTIONS route, so the preflight can never pass.
  • Allowing the method but forgetting a header such as Authorization.
  • Returning the CORS headers only on the real response and not on the preflight.
  • Thinking the preflight is sent by the developer's code.

Follow-ups

  • How do you avoid a preflight for a simple search request?
  • Why does a preflight not carry cookies?
  • What changes when the real request uses credentials?

Tips

  • List the three triggers and the four answer headers.
  • Mention how to see the OPTIONS request in the Network tab.
30.frontend-0030Hardsenior

A page shows a CORS error, but the API works in curl and the Network tab shows a 500 response. How do you find and fix the problem?

A CORS error only says the browser could not read the response. Check the actual status, the preflight, whether the CORS headers are on every response including errors and redirects, and whether credentials need a specific origin. A very common cause is a server that adds the headers only on the success path.

Full answer

The console message is the same for many different faults, so work through them in order.

  1. Open the Network tab and find the failing request. Look at both the OPTIONS preflight and the real request. A failing preflight means the real request was not sent. A 500 or a 404 on the real request means that the server code failed, and the CORS message is hiding the real error.
  2. Compare headers. Does the response have Access-Control-Allow-Origin that matches the page origin exactly? An origin has no trailing slash and no path, and http and https differ.
  3. Check every response type. An error handler, a 404 route, a proxy or a gateway timeout page often does not pass through the middleware that adds the CORS headers. The page then reports a CORS error for what is really a server error. Add the headers before routing, so that they are present on all responses.
  4. Check redirects. A preflight must not be redirected. A 301 from http to https or from a missing slash breaks it. Call the final URL.
  5. Check credentials. With fetch(url, { credentials: 'include' }) the server must send Access-Control-Allow-Credentials: true and a specific origin. The wildcard * is rejected.
  6. Check caches. If the answer differs by origin, a missing Vary: Origin lets a cache return the headers of another origin.
  7. Rule out the front end. Using mode: 'no-cors' does not fix anything, because the response becomes opaque.

Reproduce with curl -i -H 'Origin: https://app.example.com' URL and read the headers. This works because the check is only a header comparison, though curl will not enforce the result.

The test below runs the fixed server and two broken variants, and a page that calls /boom, which returns a 500. With the headers set before the routing, the page can read the 500 status and the JSON error body. When the headers are added only on success, the same call fails with a network error. When the wildcard is used with credentials, it also fails.

javascript
import http from 'node:http';

const allowed = new Set((process.env.ALLOWED ?? 'https://app.example.com').split(','));

function cors(req, res) {
  const origin = req.headers.origin;
  res.setHeader('Vary', 'Origin');
  if (origin && allowed.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }
}

http.createServer((req, res) => {
  cors(req, res);                        // before routing, so errors get the headers too
  res.setHeader('Content-Type', 'application/json');
  if (req.url === '/boom') {
    res.statusCode = 500;
    return res.end(JSON.stringify({ error: 'database down' }));
  }
  res.end(JSON.stringify({ ok: true }));
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Three server versions were run against a page on another localhost port: the shown code returned the 500 status and JSON body to the page, a version that adds headers only on success was blocked, and a version using * with credentials was blocked.

Key points

  • The CORS message hides the real status. Read the Network tab first.
  • Add CORS headers to all responses, including errors, before routing.
  • Preflights must not be redirected or require authentication.
  • With credentials, use a specific origin and Allow-Credentials true.
  • Use Vary: Origin when the header depends on the request.

Common mistakes

  • Debugging only in the console and never opening the Network tab.
  • Adding the headers in the success handler only.
  • Using * together with credentials.
  • Turning on no-cors and thinking the issue is solved.

Follow-ups

  • How do you test a CORS rule without a browser?
  • What does a reverse proxy change about where to set the headers?
  • Why must the allowed origin be compared exactly and not with endsWith?

Tips

  • Give the order of checks, and say which tool shows each one.
  • Mention the error response path, which is the cause that most candidates miss.
31.frontend-0031Mediummid

A page shows 'Results for' followed by the search text from the URL, using innerHTML. What attack does that allow, and how do you fix it and prevent the whole class of bug?

This is DOM-based XSS: a crafted link makes the attacker's JavaScript run in your page and your origin. XSS can also be stored or reflected. Prevent it by treating all data as text, using textContent or a framework's escaping, sanitizing any HTML you must allow, avoiding dangerous sinks, and adding a Content Security Policy as a second layer.

Full answer

In XSS the attacker's script runs with the privileges of your site. It can read the page, call your API as the user, change the page and send data out. If tokens are readable by scripts, they can be stolen.

Types:

  • Stored XSS. The payload is saved on the server, for example in a comment, and shown to every visitor.
  • Reflected XSS. The payload is in the request, for example a query parameter that the server puts into the page, and a victim opens a crafted link.
  • DOM-based XSS. The payload never goes through the server. Client code takes a value from location, postMessage or storage and writes it into a dangerous sink.

Dangerous sinks include innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, setTimeout with a string, javascript: URLs in href, and framework escape hatches such as dangerouslySetInnerHTML or v-html.

Prevention, in order of value:

  1. Use safe sinks. textContent, setAttribute for harmless attributes and framework templates escape text for you. Escaping must match the place: HTML text, attribute, URL and script contexts differ.
  2. Never build HTML by joining strings with user data.
  3. If users must supply HTML, such as rich text, sanitize it with a maintained sanitizer library on the server or the client, with an allowlist of tags and attributes. Writing a regex filter is a known source of bypasses.
  4. Validate URL schemes. Allow http, https and mailto, and reject javascript:.
  5. Add a Content Security Policy and cookies with HttpOnly. These limit the damage, but they do not replace output handling.

A note: a <script> tag inserted through innerHTML does not run, but an image onerror attribute does. Do not rely on that as a defence.

The page below writes the same input into two elements. The innerHTML version creates an image whose error handler runs, and sets a flag. The textContent version shows the same text without creating an element. The escapeHtml function shows what a template engine does for you.

html
<div id="unsafe"></div>
<div id="safe"></div>
<script>
  const userInput = '<img src="/no-such-image" onerror="window.attacked = true">';

  unsafe.innerHTML = userInput;     // parsed as HTML: the handler runs
  safe.textContent = userInput;     // shown as text: no element is created

  const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  window.escaped = escapeHtml(userInput);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome. The unsafe version sets the flag, the safe version creates no image, and the escaped text has no angle brackets. The escape function covers the HTML text and quoted attribute contexts only. It is a teaching example, and a maintained library should be used in real code.

Key points

  • XSS runs attacker code in your origin. Types: stored, reflected, DOM-based.
  • Treat data as text. Use textContent and framework escaping.
  • Sanitize HTML with a maintained library and an allowlist when HTML is required.
  • Validate URL schemes such as javascript:.
  • CSP and HttpOnly cookies limit damage as a second layer.

Common mistakes

  • Blocking only the script tag, while image handlers and svg still work.
  • Using a regex to strip tags.
  • Escaping once for HTML and using the value in a URL or script context.
  • Using dangerouslySetInnerHTML or v-html with unsanitized data.

Follow-ups

  • Why is escaping context dependent?
  • How do Trusted Types reduce DOM XSS?
  • Why is a javascript: link dangerous in an href?

Tips

  • Name the three types and one sink for each.
  • Say that framework defaults help, and name the escape hatches.
32.frontend-0032Mediummid

What is a Content Security Policy, and how does a nonce let you allow your own inline script while blocking injected ones?

A Content Security Policy (CSP) is a response header that tells the browser which sources of scripts, styles, images and other resources are allowed. With a nonce policy, only scripts that carry the random per-response nonce can run, so injected inline scripts and inline event handlers are blocked.

Full answer

CSP is a second line of defence against XSS. Even if an attacker finds a way to inject markup, the browser refuses to run what the policy does not allow.

The policy is a list of directives:

  • default-src 'self' is the fallback for every type of resource, here the site's own origin.
  • script-src controls scripts. Sources can be origins, hashes or nonces.
  • object-src 'none' removes old plugin content.
  • base-uri 'self' stops an injected <base> tag from changing relative URLs.
  • frame-ancestors controls who may embed the page.
  • report-to or report-uri sends violation reports to an endpoint.

Allowing inline scripts with 'unsafe-inline' removes most of the value of the policy, because injected inline scripts are inline scripts. The better way is a nonce or a hash.

  • A nonce is a random value generated for each response. The server puts it in the header, script-src 'nonce-R4nd0m', and on every script tag it trusts, <script nonce="R4nd0m">. An attacker who injects markup cannot know the nonce for this response. It must be unpredictable and new each time. A fixed nonce is useless.
  • A hash allows one exact inline script by its content hash, which suits a static page.
  • 'strict-dynamic' lets a trusted script load further scripts, which helps with bundlers and tag managers.

Roll out in steps. First use Content-Security-Policy-Report-Only and read the reports. Then enforce the policy and keep monitoring. Inline event handler attributes such as onclick are blocked, so they must become addEventListener calls.

The Node server below sends a policy with a fresh nonce on each response. The page has one script with the nonce, one without, and an image with an inline onerror attribute. The test shows that only the first script runs and the browser reports violations for the others.

javascript
import http from 'node:http';
import { randomBytes } from 'node:crypto';

http.createServer((req, res) => {
  const nonce = randomBytes(16).toString('base64');
  res.setHeader('Content-Security-Policy',
    `default-src 'self'; script-src 'nonce-${nonce}'; object-src 'none'; base-uri 'self'`);
  res.setHeader('Content-Type', 'text/html');
  res.end(`<!doctype html><title>csp</title>
<script nonce="${nonce}">window.trusted = true;</script>
<script>window.injected = true;</script>
<img src="/missing.png" onerror="window.handler = true">`);
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Run with a Node server and headless Chrome. Only the script with the nonce ran, the unmarked inline script and the inline error handler were blocked, the console reported violations, and the nonce differed between two responses.

Key points

  • CSP is a header that allowlists the sources the browser may use.
  • unsafe-inline weakens script-src, so avoid it.
  • A nonce is random for each response and appears in the header and on trusted scripts.
  • Inline event handlers are blocked and must become addEventListener calls.
  • Roll out with Report-Only first, then enforce.

Common mistakes

  • Using a fixed nonce, or one generated at build time.
  • Adding unsafe-inline to make the errors go away.
  • Setting the policy only in a meta tag and expecting every directive to work there.
  • Skipping the report-only step and breaking the site.

Follow-ups

  • Why is a hash a better fit for a static page?
  • What does strict-dynamic do?
  • Which directives cannot be set in a meta tag?

Tips

  • Explain why a nonce beats unsafe-inline in one sentence.
  • Mention the Report-Only rollout.
33.frontend-0033Mediummid

What is CSRF, and how do SameSite cookies and CSRF tokens protect against it?

CSRF is when another site makes the user's browser send a request that carries the user's cookies, so the server thinks it is a real action. SameSite cookies stop the browser from sending the cookie on cross-site requests: Lax allows top-level GET navigation only, Strict allows none, and None allows all but needs Secure. CSRF tokens and origin checks add a second layer.

Full answer

Cookies are attached to a request based on the destination, not on who started the request. If a user is logged in to bank.example and visits evil.example, a hidden form on the evil page can post to bank.example/transfer, and the browser adds the bank cookie. That is cross-site request forgery. The attacker cannot read the response, but the action happens.

Terms: a site is the registrable domain (example.com, with its scheme). A request is same-site when the initiating page and the target share a site. Subdomains of one site are the same site, but different origins.

The SameSite attribute controls cross-site sending:

  • Strict: the cookie is sent only for same-site requests. Following a link from another site starts without the cookie, so the user can look logged out on arrival.
  • Lax: the cookie is also sent on top-level navigations that use a safe method such as GET, but not on cross-site POST, iframes, images or fetch. Chrome treats cookies with no SameSite attribute as Lax by default, though other browsers can differ, so set it explicitly.
  • None: always sent, including cross-site. Requires Secure. Use it for embedded widgets or single sign-on, with care.

Other cookie flags: HttpOnly hides the cookie from JavaScript, Secure sends it only over HTTPS, and __Host- prefix rules tie a cookie to the exact host.

SameSite is not enough alone:

  • A same-site attacker, such as a vulnerable sibling subdomain, still passes.
  • State-changing actions must never use GET.
  • Add a CSRF token: a random value that the server ties to the session and the page sends in a header or form field. A forged request from another site cannot read it. Also check the Origin header on unsafe methods.
  • A custom request header, such as X-Requested-With, forces a CORS preflight for cross-site calls, which helps when CORS is strict.

The test below uses localhost and 127.0.0.1, which are different sites. The server sets three cookies. A form on 127.0.0.1 posts to localhost, and then a link goes there with GET. The server reports the cookies it received.

javascript
import http from 'node:http';

http.createServer((req, res) => {
  if (req.url === '/login') {
    res.setHeader('Set-Cookie', [
      'lax=1; SameSite=Lax; HttpOnly',
      'strict=1; SameSite=Strict; HttpOnly',
      'none=1; SameSite=None; Secure',
    ]);
    return res.end('logged in');
  }
  // /transfer and /whoami report which cookies arrived
  const names = (req.headers.cookie ?? '').split('; ').filter(Boolean).map((c) => c.split('=')[0]).sort();
  res.setHeader('Content-Type', 'text/plain');
  res.end(`${req.method} ${req.url} cookies: ${names.join(',') || 'none'}`);
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. localhost and 127.0.0.1 were used as two different sites. A cross-site form POST sent only the SameSite=None cookie. A cross-site GET navigation sent the Lax and None cookies. All three were sent on a same-site visit. Defaults for third-party cookies differ between browsers, and only Chrome was run.

Key points

  • CSRF abuses the fact that cookies are sent based on the destination.
  • Lax sends cookies on top-level GET navigation only. Strict never sends cross-site. None needs Secure.
  • Set SameSite explicitly because defaults differ between browsers.
  • Use CSRF tokens or Origin checks for state-changing requests.
  • Never change state on GET.

Common mistakes

  • Thinking CORS stops CSRF. A form post is not a CORS request.
  • Relying on the browser default for SameSite.
  • Using SameSite=None without Secure, which browsers reject.
  • Changing data with GET requests, which Lax cookies still allow from links.

Follow-ups

  • Why is a subdomain takeover a problem for SameSite protection?
  • How does a double-submit cookie token work?
  • Which cookie flags protect against XSS theft, and which against CSRF?

Tips

  • Define site versus origin before explaining SameSite.
  • State the three values with one example effect each.
34.frontend-0034Hardsenior

Where should a single-page app store an authentication token, and what can an attacker do in each case if there is an XSS bug?

A token in localStorage can be read and sent away by any script that runs in the page, so one XSS bug leaks it. A session in an HttpOnly cookie cannot be read by scripts, but the attacker's script can still make requests that carry it, and the cookie then needs CSRF protection. Neither option is safe against XSS, so prevention and short lifetimes matter most.

Full answer

The choice is a trade-off between two risks, XSS and CSRF.

Token in localStorage or sessionStorage, sent in an Authorization header:

  • Any script in the origin can read it, including injected scripts and compromised third-party libraries. After a single XSS bug the attacker can copy the token and use it from anywhere, for as long as it is valid.
  • It is not sent automatically, so there is no CSRF risk from this token.
  • Easy to use for APIs on other domains.

Session or token in an HttpOnly; Secure; SameSite cookie:

  • Scripts cannot read it, so it cannot be copied out of the browser by XSS.
  • The browser sends it automatically, so a forged cross-site request is possible. Use SameSite=Lax or Strict, a CSRF token or an Origin check.
  • With XSS the attacker's script can still call your API from the victim's browser, and the cookie goes along. The damage is limited to the time the victim has the page open, and the attacker cannot take the session home.

A balanced design that many teams use: a short-lived access token kept in memory, and a long-lived refresh token in an HttpOnly, Secure, SameSite cookie scoped to the refresh path. On page load the app asks the refresh endpoint for a new access token. Rotating refresh tokens and revoking them on reuse limits theft further. The backend-for-frontend pattern goes further, and keeps all tokens on a server that gives the browser only a session cookie.

Whichever way is chosen, reduce XSS: escape output, set a strict CSP, vet third-party scripts and use Subresource Integrity.

The test serves a page that sets an HttpOnly cookie and also stores a token in localStorage. A script that plays the attacker reads both. It gets the storage token but cannot see the cookie, yet a fetch call from the same page is still authenticated by the cookie.

javascript
import http from 'node:http';

const page = `<!doctype html><title>app</title><p>app</p>
<script>
  localStorage.setItem('token', 'abc123');
  // What injected script could do:
  window.stolen = { cookie: document.cookie, token: localStorage.getItem('token') };
  window.me = fetch('/me').then((r) => r.text());
</script>`;

http.createServer((req, res) => {
  if (req.url === '/me') {
    const ok = (req.headers.cookie ?? '').includes('session=s3cret');
    return res.end(ok ? 'user: asha' : 'anonymous');
  }
  res.setHeader('Set-Cookie', 'session=s3cret; HttpOnly; SameSite=Lax; Path=/');
  res.setHeader('Content-Type', 'text/html');
  res.end(page);
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The script that stands for injected code read the localStorage token, could not see the HttpOnly cookie in document.cookie, and a fetch from the page was still authenticated by the cookie.

Key points

  • localStorage tokens are readable by any script in the origin.
  • HttpOnly cookies cannot be read by scripts, but XSS can still make authenticated calls.
  • Cookies need SameSite and CSRF protection because they are sent automatically.
  • Short-lived memory access token plus an HttpOnly refresh cookie is a common design.
  • Preventing XSS matters in every design.

Common mistakes

  • Saying HttpOnly cookies make XSS harmless.
  • Saying localStorage is fine because the site has no XSS today.
  • Using long-lived access tokens with no rotation or revocation.
  • Forgetting the Secure flag and sending cookies over HTTP.

Follow-ups

  • What is the backend-for-frontend pattern?
  • How does refresh token rotation detect theft?
  • How would a strict CSP change the XSS risk?

Tips

  • Present it as a trade-off with a recommendation, not as a single right answer.
  • Name the in-memory token plus refresh cookie design.
35.frontend-0035Mediummid

Which HTTP security headers should a site send, and what does each one protect against?

Common ones are Strict-Transport-Security to force HTTPS, X-Content-Type-Options nosniff to stop type guessing, frame-ancestors in CSP to stop clickjacking, Referrer-Policy to limit URL leaks, Permissions-Policy to turn off unused features, and a Content Security Policy against XSS.

Full answer

Security headers are cheap, and each one closes a particular risk.

  • Strict-Transport-Security: max-age=31536000; includeSubDomains. After one HTTPS visit the browser refuses plain HTTP for the site for that time, which stops downgrade and cookie theft on the first request. Roll it out slowly, because a mistake on a subdomain is hard to reverse. Preload lists exist but are a long commitment.
  • X-Content-Type-Options: nosniff. The browser must trust the declared Content-Type. It stops a text or image upload from being run as a script.
  • Content-Security-Policy: frame-ancestors 'none' (or 'self'). This controls who may embed the page in a frame and protects against clickjacking, where a page is hidden in a transparent frame and the user is tricked into clicking it. The older X-Frame-Options header does the same, and frame-ancestors is preferred when both are present.
  • Content-Security-Policy with script-src. Limits the damage of XSS.
  • Referrer-Policy: strict-origin-when-cross-origin. Sends only the origin to other sites, so private paths and query strings do not leak. It is also the default in current browsers, but explicit is better.
  • Permissions-Policy: camera=(), microphone=(). Disables powerful features for the page and for embedded frames that do not need them.
  • Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy. Isolate the page from other windows, and are needed for some features such as high resolution timers and shared memory.
  • Cookie flags: Secure, HttpOnly, SameSite.

Headers are set by the server, a CDN or a hosting configuration, and not by the HTML. Only a few can be set in a meta tag, and frame-ancestors is not one of them.

The Node server below sends several of these. The test loads it in an iframe from another origin, and Chrome blocks the frame because of frame-ancestors 'none'. A variant without the header loads inside the frame. Scanners such as the Mozilla Observatory report missing headers, but they were not run here.

javascript
import http from 'node:http';

http.createServer((req, res) => {
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
  res.setHeader('Permissions-Policy', 'camera=(), microphone=()');
  if (process.env.EMBED !== 'yes') res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
  res.setHeader('Content-Type', 'text/html');
  res.end('<!doctype html><title>bank</title><h1>Transfer money</h1>');
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The server was framed from another localhost origin. With frame-ancestors none, Chrome blocked the frame. Without that header, the frame loaded. The five headers were present in the response. No scanner was run.

Key points

  • HSTS forces HTTPS. nosniff stops MIME type guessing.
  • frame-ancestors stops clickjacking by controlling who may embed the page.
  • Referrer-Policy limits what URL data other sites receive.
  • Permissions-Policy turns off features the page does not need.
  • Set these on the server or CDN. A meta tag supports only a few.

Common mistakes

  • Setting frame-ancestors in a meta tag, where it is ignored.
  • Enabling HSTS with includeSubDomains without checking every subdomain.
  • Treating headers as a replacement for escaping and validation.
  • Copying a header list without understanding which risk each one covers.

Follow-ups

  • What is clickjacking and how does the attack work?
  • Why is HSTS preload a serious commitment?
  • What does nosniff protect in a file upload feature?

Tips

  • Pair every header with the attack it prevents.
  • Say who sets them: server or CDN.
36.frontend-0036Mediummid

What is Subresource Integrity, and how do you protect a page from a tampered third-party script?

Subresource Integrity (SRI) adds a hash of the expected file to a script or link tag. The browser downloads the file, hashes it and refuses to run it if the hash does not match, so a compromised CDN cannot silently change the code. It fits files that never change at their URL.

Full answer

A page that loads a library from a CDN trusts that CDN completely. If the CDN or the package account is compromised, the attacker's code runs in your origin, with the same power as your own code.

SRI limits this. You add an integrity attribute with the algorithm and the base64 digest of the exact file:

<script src="https://cdn.example.com/lib.js" integrity="sha384-..." crossorigin="anonymous"></script>

The browser fetches the file, computes the hash and runs it only if it matches. A mismatch blocks the script and writes an error to the console. For files on another origin, the server must allow CORS, and the tag needs crossorigin="anonymous", otherwise the browser cannot check the bytes.

How to create the value: hash the file with SHA-256, SHA-384 or SHA-512 and encode the digest with base64. Tools such as openssl dgst -sha384 -binary lib.js | openssl base64 -A or a few lines of Node do it. Build tools can add the attribute to the output HTML automatically.

Limits:

  • The URL must serve identical bytes. Any URL that changes without notice, such as latest or a tag manager snippet, will break. Pin a version.
  • It checks only the file, not what the file loads next.
  • It does not protect against code you already trust that turns hostile in a new release. Review updates and pin versions.
  • A page with a strict CSP can also require integrity metadata for scripts.

Other supply chain steps: lock files and reviewed dependency updates, npm audit in CI, the fewest third-party scripts that the business allows, and loading the rest in a sandboxed iframe or a worker.

The Node script computes the attribute for a small file. The test serves the file and runs the tag in Chrome. The script runs when the hash matches. When the served file is changed by one character, Chrome blocks it.

javascript
import { createHash } from 'node:crypto';

const file = 'window.libLoaded = true;\n';
const digest = createHash('sha384').update(file).digest('base64');
console.log(`<script src="/lib.js" integrity="sha384-${digest}" crossorigin="anonymous"></script>`);

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The Node script printed the tag, and the test used it in Chrome. A file with the matching hash ran, and the same file with one extra comment was blocked with an integrity error.

Key points

  • SRI pins a script or style to a hash, and the browser refuses mismatches.
  • Cross-origin files need crossorigin anonymous and CORS headers.
  • Pin an exact version, because SRI breaks on files that change.
  • It protects the file, not what the file loads.
  • Combine with lock files, review and fewer third-party scripts.

Common mistakes

  • Adding integrity to a URL that serves different bytes over time.
  • Forgetting crossorigin for a cross-origin file.
  • Thinking SRI protects against a malicious new package version that you chose to install.
  • Computing the hash from a different copy of the file than the one served.

Follow-ups

  • Which hash algorithms can integrity use?
  • What happens to the page when the hash fails?
  • How would you handle a tag manager that you cannot pin?

Tips

  • Show the attribute and say what the browser does with it.
  • Mention the CORS requirement, since it trips people.
37.frontend-0037Mediummid

How do you use postMessage between a page and an iframe safely?

Send with an explicit target origin and never with the wildcard for private data. When receiving, check event.origin against an allowlist, and validate the shape and size of event.data before using it, because any window can send a message to your page.

Full answer

window.postMessage(data, targetOrigin) is the supported way for windows from different origins to talk, for example a page and an embedded payment or video widget. It works because the browser sends the message with the true origin of the sender, and the receiver can look at it.

Two sides, two rules.

Sending:

  • Always pass the exact targetOrigin, such as 'https://widgets.example.com'. The browser delivers the message only if the receiving window is on that origin. With '*', the message goes to whatever page is in the frame at that moment, which may have been navigated to an attacker's site.
  • Do not send secrets unless the target origin is exact.

Receiving:

  • Listen with window.addEventListener('message', handler). Any window that has a reference to yours can send a message, including a malicious one that embedded you or opened you.
  • Check event.origin against an allowlist with strict equality. Do not use includes or endsWith, because https://app.schoolabe.com.evil.example passes an includes check.
  • Check event.source when you expect a particular window.
  • Validate event.data: the type, the allowed fields and the size. Treat it as untrusted input, and never put it into innerHTML or eval.
  • Ignore messages that are not for you, because libraries and browser extensions also post messages.

Message passing with structured clone allows many types, but not functions. Use a small protocol with a type field and handle each type explicitly.

The snippet is a receiver with an allowlist. In the test, a parent page on one origin and a second page on another origin both embed the same child frame and post a resize message. The child accepts the trusted parent and ignores the other. The test replaced the trusted origin placeholder with the real test origin.

javascript
const TRUSTED = 'https://app.schoolabe.com';
window.accepted = 0;

window.addEventListener('message', (event) => {
  if (event.origin !== TRUSTED) return;                  // exact match only
  const data = event.data;
  if (!data || data.type !== 'resize') return;           // our own small protocol
  const height = Number(data.height);
  if (!Number.isFinite(height) || height < 0 || height > 2000) return;
  document.body.style.height = `${height}px`;
  window.accepted += 1;
});

// Sending side, in the parent page:
// frame.contentWindow.postMessage({ type: 'resize', height: 300 }, 'https://widgets.example.com');

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. A child frame on 127.0.0.1 was embedded by two parent pages on different localhost ports, with the first one trusted. The trusted parent's message was accepted, and the other parent's message was ignored. The test replaced the placeholder origin with the real test origin.

Key points

  • postMessage is the safe cross-origin channel, with the real origin attached.
  • Send with an exact target origin, never * for private data.
  • Receive with a strict equality check on event.origin.
  • Validate type, shape and size of the data.
  • Never put message data into innerHTML or eval.

Common mistakes

  • Checking origin with includes or endsWith.
  • Using * as the target origin for sensitive data.
  • Trusting event.data without validation.
  • Forgetting to ignore messages that are not part of your protocol.

Follow-ups

  • What does event.source give you?
  • How would you reply to the sender safely?
  • How does this compare to a MessageChannel?

Tips

  • Explain both directions: target origin on send, event.origin on receive.
  • Give the includes bypass as the common error.
38.frontend-0038Easyfresher

What is the accessibility tree, and why is a native button better than a div with a click handler?

The browser builds an accessibility tree from the DOM, with a role, a name and a state for each element. Assistive tools such as screen readers use it. A native button gets the role, keyboard focus, Enter and Space activation for free, while a div has none of them.

Full answer

Assistive technology does not read pixels. It reads the accessibility tree, which the browser builds from the DOM and ARIA attributes. Each node has:

  • a role, which says what the thing is: button, link, heading, textbox;
  • a name, the text that identifies it: "Save";
  • a state or value, such as checked, expanded or disabled.

Native elements provide all of this by default. A <button> has the role button, takes its name from the text inside, appears in the Tab order, and activates on Enter and Space. It also works with voice control, which looks for the visible name, and with the operating system's high contrast mode.

A <div onclick="..."> has the role generic, no name that says it can be activated, no tab stop, and no keyboard activation. To repair it, you have to add role="button", tabindex="0", key handlers for Enter and Space, and focus styles. That is more code than the native element and still misses some behaviour, such as the disabled state and form submission.

Rules to remember:

  1. Use the native element when one exists: button, a href, input, select, details, dialog, nav, main, h1 to h6.
  2. Use a link for navigation, and a button for actions on the page.
  3. Use ARIA only to fill gaps that HTML cannot cover.
  4. Test with the keyboard alone, and look at the tree in the DevTools Accessibility panel.

The page below has a real button and a div with a click handler. The test reads the accessibility tree snapshot, which lists a button named Save, while the div appears only as plain text. It also presses Tab, and only the button receives focus. Pressing Enter triggers the button's handler.

html
<button id="real" type="button">Save</button>
<div id="fake" onclick="window.fakeClicked = true">Save</div>
<script>
  window.clicks = 0;
  real.addEventListener('click', () => { window.clicks += 1; });
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check read the accessibility snapshot, pressed Tab and Enter with real key presses, and confirmed that only the button took focus and ran its handler. No screen reader was run.

Key points

  • Assistive tools use the accessibility tree: role, name and state.
  • Native elements supply role, focus and keyboard behaviour for free.
  • A div with onclick has no role, no focus and no keyboard support.
  • Use links for navigation and buttons for actions.
  • Test with the keyboard and the Accessibility panel.

Common mistakes

  • Adding role="button" to a div and forgetting tabindex and key handlers.
  • Using a link with href="#" as an action button.
  • Removing the focus outline without a replacement.
  • Believing that ARIA changes behaviour. It only changes what is announced.

Follow-ups

  • What does the first rule of ARIA say?
  • How is the accessible name of a button computed?
  • When is a link better than a button?

Tips

  • Name role, name and state, and give one example of each.
  • Say that you check by using only the keyboard.
39.frontend-0039Mediummid

How does the browser work out the accessible name of a control, and how do you check that a control has the name you expect?

The accessible name comes from, in order of strength: aria-labelledby, aria-label, then native sources such as a label element, alt text or the element's text content, and finally title. Check it in the accessibility tree or with a test query such as getByRole with a name.

Full answer

A screen reader announces a control by role and name, for example "Search, edit text" or "Close, button". If the name is missing or wrong, the control is unusable.

The browser follows the accessible name computation. In simplified form, for most controls:

  1. aria-labelledby points to other elements by id, and their text is used. It wins over everything else.
  2. aria-label supplies a string directly.
  3. The native source: the <label> linked to an input, alt for an image, <legend> for a fieldset, <caption> for a table, or the text inside a button or link.
  4. title or placeholder as a last resort. They are weak: title shows only on hover, and placeholder disappears when typing.

Practical guidance:

  • Prefer visible text. A visible <label for> helps everybody, including people with cognitive or motor difficulties, and voice control users can say the label.
  • Use aria-label for icon-only buttons, such as a magnifier button: aria-label="Search". Remember that translated pages must translate it too.
  • The visible text and the accessible name should match, or contain the visible text, so that voice control commands like "click Search" work (WCAG 2.5.3, Label in Name).
  • Images that carry meaning need alt. Decorative ones need alt="".
  • Mark an icon inside a named button with aria-hidden="true" so that it does not add noise.

How to check:

  • The Accessibility panel in DevTools shows the computed name.
  • In tests, getByRole('button', { name: 'Search' }) fails when the name is wrong, so the test also guards accessibility.
  • Automated checkers find missing names, but not wrong names.

The test below builds four controls with different sources and uses Playwright's accessibility snapshot to read the names that Chrome computed.

html
<label for="email">Email address</label>
<input id="email" type="email">

<button type="button" aria-label="Search"><svg aria-hidden="true" width="12" height="12"><circle cx="6" cy="6" r="5"/></svg></button>

<h2 id="t">Newsletter</h2>
<input type="text" aria-labelledby="t">

<img src="/logo.png" alt="Schoolabe logo">

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check read the accessibility snapshot in Chrome. All four controls had the expected names. No screen reader was run, and other browsers compute names slightly differently in rare cases.

Key points

  • The name comes from aria-labelledby, aria-label, native sources, then title.
  • Visible labels are best. Use aria-label for icon-only controls.
  • Match the visible text so that voice control works.
  • Decorative images use empty alt.
  • Check names in DevTools or with getByRole in tests.

Common mistakes

  • Using placeholder as the only label.
  • An aria-label that differs from the visible text.
  • Leaving an icon button with no name.
  • Adding aria-label to a div with no role, where it may be ignored.

Follow-ups

  • Which wins when both aria-label and a label element exist?
  • How does aria-describedby differ from aria-labelledby?
  • Why can a good test query double as an accessibility check?

Tips

  • List the sources in order of strength.
  • Give the icon button case as the main reason for aria-label.
40.frontend-0040Mediummid

In a single-page app, what does a screen reader user miss after a route change, and how do you fix it with focus and a live region?

A normal page load resets focus and announces the new page. A client-side route change does neither, so the user hears nothing. Update the document title, move focus to the new page heading or main region, and use a polite live region for status messages.

Full answer

A full page load gives a screen reader user several things for free: focus goes to the top of the document, the new title is announced, and the reading position resets. A single-page app replaces content without a load. Focus stays on the link that was clicked, which may no longer exist, and the screen reader says nothing. Keyboard users have to Tab through the navigation again to reach the new content.

A repair has three parts:

  1. Update document.title on every route change, so that history, tabs and screen readers have a distinct name for the view.
  2. Move focus to a sensible target after the new view is rendered. A common choice is the h1 of the new page, given tabindex="-1" so that it can receive programmatic focus without joining the Tab order. Another choice is the main element. Call focus() after the DOM update, for example in an effect after render.
  3. Announce state changes that do not move focus, using a live region.

Live regions (aria-live):

  • role="status" or aria-live="polite" waits until the user is idle. Use it for "3 results found", "Saved", or "Page loaded".
  • role="alert" or aria-live="assertive" interrupts. Use it rarely, for errors that block progress.
  • The region must exist in the DOM before its text changes. A region inserted together with its message is often not announced.
  • Keep messages short and replace the text, instead of adding endless child nodes.

Test with a real screen reader too. Support differs between combinations of browser and reader, and an automated check cannot hear the output.

The page below simulates a route change. It sets the title, swaps the content, focuses the heading, and writes a message to a status region. The test checks the active element and the region text. No screen reader was run.

html
<nav><a href="#/courses" id="go">Courses</a></nav>
<main id="view"><h1 tabindex="-1" id="heading">Home</h1></main>
<p id="live" role="status"></p>
<script>
  function navigate(title) {
    document.title = title;
    view.innerHTML = '<h1 tabindex="-1" id="heading"></h1>';
    document.getElementById('heading').textContent = title;
    document.getElementById('heading').focus();          // move focus after the DOM update
    live.textContent = `${title} page loaded`;           // polite announcement
  }
  go.addEventListener('click', (e) => { e.preventDefault(); navigate('Courses'); });
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check clicked the link and read the focused element, the title and the live region text. No screen reader was run, so what is announced was not heard.

Key points

  • Client-side navigation does not move focus or announce the new view.
  • Update document.title on each route change.
  • Focus the new h1 with tabindex -1, or the main region, after render.
  • Use a polite status region for messages. Reserve alert for blocking errors.
  • The live region must exist before the text changes.

Common mistakes

  • Leaving focus on a link that was removed from the page.
  • Giving the heading tabindex 0, which adds it to the Tab order.
  • Creating the live region at the same time as its message.
  • Using assertive for every message.

Follow-ups

  • What does tabindex -1 do compared to 0?
  • How would you restore focus when the user goes back?
  • Why test with more than one screen reader?

Tips

  • Say what a full page load does for free, then rebuild it in three steps.
  • Mention testing with a real screen reader.