My account

Interview questions

1Destructuring a reactive objectEasy–Vue fundamentals

Question: On the product list page of our online shop, the user can set a minimum price. A teammate wrote this component:

<script setup lang="ts">
import { computed, reactive } from 'vue'

const filters = reactive({ minPrice: 0, onlyInStock: false })
const { minPrice } = filters

const label = computed(() => `From ${minPrice} USD`)
</script>

<template>
  <input v-model.number="filters.minPrice" type="number" />
  <p>{{ label }}</p>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: Destructuring a reactive object copies its current values. So minPrice is a plain number, 0, with no link to filters. The computed reads this plain number, so Vue never tracks filters.minPrice, and the label always says “From 0 USD”. Read filters.minPrice inside the computed, or use toRefs (and then minPrice.value), or use a ref from the start.

Hint (if the candidate says there is no problem): The user types 50 in the input. The input shows 50, and in Vue devtools filters.minPrice is 50. But the text under the input still says “From 0 USD”. There is no error in the console.

Why does this happen? (step by step)

  1. The reactive function returns a Proxy. Vue only sees reads and writes that go through this Proxy.
  2. The line with the destructuring reads filters.minPrice once, when setup runs. That read happens outside any effect, so nothing is tracked.
  3. The variable minPrice now holds the number 0. A number is not reactive. It is a copy, not a link.
  4. The computed reads minPrice. This is a plain variable, not the Proxy. So the computed has no reactive dependency at all.
  5. A computed with no dependencies never runs again. The label stays “From 0 USD” forever.
  6. The input uses filters.minPrice directly, so the input itself works. That is why the bug is easy to miss.

The fix:

<script setup lang="ts">
import { computed, ref } from 'vue'

const minPrice = ref(0)
const onlyInStock = ref(false)

const label = computed(() => `From ${minPrice.value} USD`)
</script>

<template>
  <input v-model.number="minPrice" type="number" />
  <p>{{ label }}</p>
</template>
  1. With ref, there is nothing to destructure. Every read goes through the value property, which Vue tracks.
  2. If you want to keep the reactive object, read filters.minPrice inside the computed, or destructure with toRefs. Then each variable is a ref linked to the object, and you read it through the value property.
  3. The trade-off: in script, a ref needs the value property. Many teams accept this, because the Vue docs suggest ref as the main way to declare state.

Follow-up question: In Vue 3.5, a teammate writes the line “const { price } = defineProps” with a type for price. Does destructuring props have the same problem?

Follow-up answer:

  • In Vue 3.5 and later, no. The compiler rewrites every use of price in the same script setup into a read of props.price. So price stays reactive in the template and in computed.
  • Before Vue 3.5, it had the same problem: price was a plain copy.
  • One trap is still there: you cannot pass price directly to watch, because watch would get a plain value. Use a getter function that returns price. The compiler catches this case and reports it.
  • This compiler help is only for defineProps. A normal reactive object, or a Pinia store, still loses reactivity when you destructure it.

Red flag: Says “reactive makes everything reactive, so a variable taken from it is reactive too”. Or fixes the bug by adding a watch that copies filters.minPrice into another variable.

Report a problem or send a better text

Edit on GitHub

2v-if and v-for on the same elementEasy–Vue fundamentals

Question: The shop should not show products that are sold out. A teammate changed the product list like this:

<script setup lang="ts">
import { ref } from 'vue'

type Product = { id: number; name: string; soldOut: boolean }

const products = ref<Product[]>([
  { id: 1, name: 'Running shoes', soldOut: false },
  { id: 2, name: 'Rain jacket', soldOut: true },
  { id: 3, name: 'Socks', soldOut: false },
])
</script>

<template>
  <ul>
    <li v-for="product in products" v-if="!product.soldOut" :key="product.id">
      {{ product.name }}
    </li>
  </ul>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: In Vue 3, when v-if and v-for are on the same element, v-if runs first. So the v-if condition cannot see the loop variable product. Reading soldOut from it fails, and the list breaks. Filter the list in a computed and loop over the result. Or put the v-for on a template tag and the v-if on the li inside it.

Hint (if the candidate says there is no problem): The page shows no list. In development the console shows a warning that the property “product” was accessed during render but is not defined, and then a TypeError about reading soldOut of undefined.

Why does this happen? (step by step)

  1. Vue compiles the template into a render function.
  2. In Vue 3, v-if has a higher priority than v-for on the same element. The compiler puts the condition outside the loop.
  3. Outside the loop, there is no product variable yet. Vue looks for product on the component, and it is not there.
  4. So product is undefined, and reading soldOut on undefined throws a TypeError. The render fails.
  5. In Vue 2 the priority was the opposite: v-for ran first. Code like this worked there, and people copied the habit. The Vue style guide says never to put both on the same element, in any version.

The fix:

<script setup lang="ts">
import { computed, ref } from 'vue'

type Product = { id: number; name: string; soldOut: boolean }

const products = ref<Product[]>([
  { id: 1, name: 'Running shoes', soldOut: false },
  { id: 2, name: 'Rain jacket', soldOut: true },
  { id: 3, name: 'Socks', soldOut: false },
])

const availableProducts = computed(() =>
  products.value.filter((product) => !product.soldOut),
)
</script>

<template>
  <ul>
    <li v-for="product in availableProducts" :key="product.id">
      {{ product.name }}
    </li>
  </ul>
</template>
  1. The computed filters the list once and caches it. It runs again only when products changes.
  2. The template stays simple: it only loops.
  3. You can now also use availableProducts.length to show a “no products” message.
  4. Another valid fix: a template tag with the v-for and the key, and the li with the v-if inside it. This works, but it filters on every render and the template is harder to read.

Follow-up question: Why does v-for need a key, and why is the index a bad key here?

Follow-up answer:

  • Vue uses the key to match old elements with new ones when the list changes. With a stable id, Vue moves, adds and removes the right elements.
  • With the index, the key belongs to a position, not to a product. When the rain jacket comes back in stock, every product after it gets a new index. Vue then reuses elements for the wrong products.
  • For plain text this costs only some extra updates. But if a row has its own state, like a quantity input or an open menu, that state can now appear on another product.
  • Use a unique and stable id from the data, like product.id.

Red flag: Says “it is fine, v-for runs first and then v-if filters each item”. This was true in Vue 2, not in Vue 3. Or uses the index as the key.

Report a problem or send a better text

Edit on GitHub

3A child changes its propEasy–Vue fundamentals

Question: On the cart page, each row has a small quantity control. The cart page passes the quantity of the item to it. A teammate wrote the control like this:

<script setup lang="ts">
const props = defineProps<{ quantity: number }>()

function increase() {
  props.quantity++
}
</script>

<template>
  <button type="button" @click="increase">+</button>
  <span>{{ props.quantity }}</span>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The child changes a prop. Props are one-way: the parent owns the data, and the child only reads it. Vue makes the props object read-only for the child, so in development the change is blocked with a warning and the number does not go up. The child should emit an event with the new value, or use defineModel, and the parent should update its own state.

Hint (if the candidate says there is no problem): The user clicks the plus button. The number stays the same. In development the console shows a warning that a set operation on the key “quantity” failed because the target is readonly.

Why does this happen? (step by step)

  1. The cart page owns the cart items. It passes the quantity down as a prop.
  2. Vue gives the child a read-only view of its props. Writing to it in development only shows a warning.
  3. Even if the write went through, the data would have two owners. The parent thinks the quantity is 2, the child shows 3, and the cart total in the parent is wrong.
  4. The next time the parent renders the child with its own value, the child’s change can be overwritten.
  5. Vue calls this one-way data flow. It makes it easy to find who changed a value: always the owner.

The fix:

The child asks for a change. The simplest way is defineModel (Vue 3.4 and later):

<script setup lang="ts">
const quantity = defineModel<number>('quantity', { required: true })
</script>

<template>
  <button type="button" :disabled="quantity <= 1" @click="quantity--">-</button>
  <span>{{ quantity }}</span>
  <button type="button" @click="quantity++">+</button>
</template>

The parent binds it with v-model:

<template>
  <CartItemQuantity v-model:quantity="item.qty" />
</template>
  1. Writing to the quantity ref in the child emits the update:quantity event. The child does not change the prop itself.
  2. The parent receives the event and updates item.qty. Then the new value flows down as the prop.
  3. The same thing without defineModel: declare the update:quantity event with defineEmits and call emit with quantity + 1. The parent listens to the event.
  4. If the cart lives in a Pinia store, the child can also call a store action like setQuantity. The rule is the same: the owner changes the data.

Follow-up question: The prop is not a number but an object, the whole cart item, and the child writes item.qty++. Does Vue block this too?

Follow-up answer:

  • No. Only the props object itself is read-only, and only at the first level. The item object belongs to the parent. If it is reactive, the change works and even updates the screen, with no warning.
  • So the code “works”, but it has the same design problem: the child changes the parent’s data in secret. When a bug appears, nobody looks for the change in the child.
  • The Vue docs say you should avoid this. Emit an event, or call an action of the store that owns the cart.

Red flag: Says “copy the prop into a local ref and change that” without seeing that the parent and the cart total never learn about the change. Or says “it is an object, so changing it is fine”.

Report a problem or send a better text

Edit on GitHub

4Cart total kept in sync with watchMedium–Vue fundamentals

Question: The cart page shows the items and the total price. The items come from the server when the page opens. A teammate wrote this:

<script setup lang="ts">
import { ref, watch } from 'vue'

type CartItem = { id: number; name: string; price: number; qty: number }

const props = defineProps<{ initialItems: CartItem[] }>()

const items = ref<CartItem[]>(props.initialItems)
const total = ref(0)

watch(
  items,
  (list) => {
    total.value = list.reduce((sum, item) => sum + item.price * item.qty, 0)
  },
  { deep: true },
)
</script>

<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
      <input v-model.number="item.qty" type="number" min="1" />
    </li>
  </ul>
  <p>Total: {{ total }} USD</p>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The total is a value we can calculate from the items, but here it is kept as separate state and copied with a watcher. A watcher is lazy: it runs only after the first change. So when the page opens, the total shows 0 even though the cart has items. Use computed. It is correct from the first render, it is cached, and there is no second copy that can go out of sync.

Hint (if the candidate says there is no problem): The user opens the cart with two items. The page says “Total: 0 USD”. When the user changes a quantity, the total suddenly becomes correct.

Why does this happen? (step by step)

  1. The total ref starts at 0.
  2. The watch function does not run the callback when it is created. It waits for the first change. Only the immediate option changes this.
  3. The page renders with total equal to 0.
  4. When the user edits a quantity, the deep watcher sees the change, and the total becomes right.
  5. Even after adding the immediate option, the design is still weak:
    • There are two sources of truth: items and total. Every new place that changes items must also keep total right.
    • A deep watcher walks the whole array and every item to find changes.
    • Someone can write to total by mistake, and then it is wrong until the next change.

The fix:

<script setup lang="ts">
import { computed, ref } from 'vue'

type CartItem = { id: number; name: string; price: number; qty: number }

const props = defineProps<{ initialItems: CartItem[] }>()

const items = ref<CartItem[]>(props.initialItems)

const total = computed(() =>
  items.value.reduce((sum, item) => sum + item.price * item.qty, 0),
)
</script>

<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
      <input v-model.number="item.qty" type="number" min="1" />
    </li>
  </ul>
  <p>Total: {{ total }} USD</p>
</template>
  1. The computed reads items, and every price and qty, so Vue tracks exactly what it needs.
  2. It is right on the first render. No immediate option is needed.
  3. It is cached. Showing the total in many places does not calculate it many times.
  4. It is read-only by default. Nobody can set the total by mistake.
  5. A side note: the items ref holds the same array the parent passed at setup time. Editing qty changes the parent’s objects in secret, and if the parent later passes a new array, this component does not see it. For a cart, the cleaner design is to keep the items in one owner, like a Pinia store.

Follow-up question: So when is watch the right tool on this page?

Follow-up answer:

  • When a change must cause a side effect outside Vue state. For example, saving the cart to localStorage, sending the new quantity to the server, or sending an analytics event.
watch(
  items,
  (list) => {
    localStorage.setItem('cart', JSON.stringify(list))
  },
  { deep: true },
)
  • Simple rule: if you can calculate it, use computed. If you must do something, use watch.

Red flag: Says “just add immediate: true and it is fine” without seeing the second source of truth. Or uses watch for every derived value because “watch is more flexible”.

Report a problem or send a better text

Edit on GitHub

5Watching one property of a reactive objectMedium–Vue fundamentals

Question: The shop wants the browser tab title to show the number of items in the cart, like “(3) Shop”. A teammate added this to the header component:

<script setup lang="ts">
import { reactive, watch } from 'vue'

type CartItem = { id: number; name: string; qty: number }

const cart = reactive({ count: 0, items: [] as CartItem[] })

watch(cart.count, (count) => {
  document.title = count > 0 ? `(${count}) Shop` : 'Shop'
})

function addItem(item: CartItem) {
  cart.items.push(item)
  cart.count += item.qty
}
</script>

<template>
  <button type="button" @click="addItem({ id: 1, name: 'Socks', qty: 1 })">Add socks</button>
  <span>{{ cart.count }}</span>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The watch function gets cart.count, and that is only the number 0 at that moment. A number is not a ref, not a reactive object and not a getter, so Vue cannot watch it. In development Vue shows an “invalid watch source” warning, and the callback never runs. Pass a getter function that returns cart.count.

Hint (if the candidate says there is no problem): The badge next to the button goes up to 1, 2, 3. But the tab title never changes. In development the console has a warning that starts with “Invalid watch source”.

Why does this happen? (step by step)

  1. JavaScript runs the expression cart.count before it calls watch. The value is 0.
  2. So watch receives the number 0. It has no idea where this number came from.
  3. A watch source must be a ref, a reactive object, a getter function, or an array of these. Vue warns and does not create a working watcher.
  4. The badge works because the template reads cart.count through the Proxy while it renders. That read is tracked.
  5. The difference: the template reads the property inside an effect. The watch call read it once, outside any effect, and passed only the result.

The fix:

watch(
  () => cart.count,
  (count) => {
    document.title = count > 0 ? `(${count}) Shop` : 'Shop'
  },
  { immediate: true },
)
  1. The getter function reads cart.count every time Vue runs it. That read is tracked, so Vue knows when count changes.
  2. The immediate option sets the title once at the start too.
  3. An even simpler version: a computed for the title and a watchEffect that writes document.title. Both read through the Proxy, so both are tracked.
  4. Also worth noting: count is a second copy of information that is already in items. A computed that sums the quantities of items would remove this extra state.

Follow-up question: The teammate also wants to save the cart when items change, and writes a watch with a getter that returns cart.items. Adding an item does not trigger it. Why?

Follow-up answer:

  • The getter returns the same array object every time. Pushing an item changes the array, but the getter still returns the same reference. Vue sees “same value” and does not call the callback.
  • A getter that returns an object is not deep by default.
  • Option one: pass the reactive array itself as the source, like watch with cart.items. A reactive object as a source is watched deeply.
  • Option two: keep the getter and add the deep option.
  • Option three: watch only what you need, for example a getter that returns cart.items.length. It is cheaper, but it misses a change of qty inside an item.

Red flag: Says “watch works with any value, so it should fire”. Or “fixes” it with setInterval that checks the count.

Report a problem or send a better text

Edit on GitHub

6A ref in an if statementEasy–Vue fundamentals

Question: The shop has a mini cart that slides in from the side. The Escape key should close it, and we send an analytics event when the user closes it. A teammate wrote this:

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { trackEvent } from './analytics'

const isCartOpen = ref(false)

function onKeydown(event: KeyboardEvent) {
  if (event.key !== 'Escape') return
  if (isCartOpen) {
    trackEvent('cart_closed')
    isCartOpen.value = false
  }
}

onMounted(() => window.addEventListener('keydown', onKeydown))
onUnmounted(() => window.removeEventListener('keydown', onKeydown))
</script>

<template>
  <button type="button" @click="isCartOpen = true">Cart</button>
  <aside v-show="isCartOpen" class="mini-cart">Your cart</aside>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The if statement checks the ref object, not its value. A ref is an object, and every object is truthy in JavaScript. So the condition is always true, even when the cart is closed. Every Escape press sends a “cart_closed” event. Write isCartOpen.value in script.

Hint (if the candidate says there is no problem): The analytics dashboard shows many more “cart_closed” events than “cart_opened” events. Some users who never opened the cart have dozens of them. On the screen everything looks fine.

Why does this happen? (step by step)

  1. The ref function returns an object with a value property. The real boolean is inside value.
  2. In the template, Vue unwraps top-level refs. So v-show with isCartOpen works, and the click handler that sets isCartOpen to true also works.
  3. In script there is no unwrapping. The name isCartOpen means the ref object itself.
  4. In JavaScript, every object is truthy, even an object whose value is false.
  5. So the if statement is always true. The event is sent on every Escape press. Setting value to false again changes nothing on the screen, so nobody notices.
  6. TypeScript does not report this, because checking an object in an if statement is valid code.

The fix:

function onKeydown(event: KeyboardEvent) {
  if (event.key !== 'Escape') return
  if (isCartOpen.value) {
    trackEvent('cart_closed')
    isCartOpen.value = false
  }
}
  1. In script, always read and write the value property of a ref.
  2. A lint rule helps: eslint-plugin-vue has a rule called no-ref-as-operand that reports a ref used directly in a condition or in math.
  3. Name booleans and refs clearly, and keep the code that uses them small, so a missing value property is easy to see in review.

Follow-up question: In the template you do not need the value property. Is that always true?

Follow-up answer:

  • Vue only unwraps top-level refs in the template: refs declared in script setup, or returned from setup.
  • A ref inside a plain object is not unwrapped in an expression. If you have an object called totals with a ref called sum inside it, then sum plus one in the template gives a string like “[object Object]1”, not a number.
  • Fix it by moving the ref to the top level, for example by destructuring it in script: then sum is a top-level ref.
  • Refs inside a reactive object are unwrapped when you read them, so they also need no value property.

Red flag: Does not see the problem because “the cart opens and closes fine”. Or says “Vue always unwraps refs”, without the difference between script and template.

Report a problem or send a better text

Edit on GitHub

7Destructuring a Pinia storeMedium–State in Vue

Question: The shop keeps the cart in a Pinia setup store:

// stores/cart.ts
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export type CartItem = { id: number; name: string; price: number; qty: number }

export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])
  const total = computed(() =>
    items.value.reduce((sum, item) => sum + item.price * item.qty, 0),
  )

  function add(product: Omit<CartItem, 'qty'>) {
    const existing = items.value.find((item) => item.id === product.id)
    if (existing) existing.qty++
    else items.value.push({ ...product, qty: 1 })
  }

  function remove(id: number) {
    items.value = items.value.filter((item) => item.id !== id)
  }

  return { items, total, add, remove }
})

A teammate wrote the header summary like this:

<script setup lang="ts">
import { useCartStore } from '../stores/cart'

const { items, total, add } = useCartStore()
</script>

<template>
  <p>{{ items.length }} items, {{ total }} USD</p>
  <button type="button" @click="add({ id: 7, name: 'Socks', price: 8 })">Add socks</button>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The store is a reactive object. Destructuring it copies the current values at that moment. So total is a plain number and never updates. The items variable still points to the same array for now, so adding works, but when remove assigns a new array, the header keeps the old one. Use storeToRefs for state and getters. Actions like add can be destructured directly.

Hint (if the candidate says there is no problem): The user clicks “Add socks”. The item count goes from 0 to 1, but the total stays at 0 USD. Later, the user removes an item on the cart page, and the header count does not go down. Vue devtools shows the store with the right values.

Why does this happen? (step by step)

  1. The useCartStore function returns the store. The store is a reactive object, and Pinia unwraps the refs inside it.
  2. Destructuring reads store.total once, during setup. The result is the number 0. A number has no link to the store.
  3. Destructuring reads store.items once too. The result is the reactive array inside the ref, not the ref itself.
  4. The add action pushes into that same array. The template reads items.length through the array’s Proxy, so the count updates. This makes the bug look random.
  5. The remove action assigns a new array to the ref. The header still holds the old array, so from now on it shows stale items.
  6. The add function works fine, because actions are plain functions bound to the store.

The fix:

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useCartStore } from '../stores/cart'

const cart = useCartStore()
const { items, total } = storeToRefs(cart) // refs that stay linked
const { add } = cart // actions can be destructured directly
</script>

<template>
  <p>{{ items.length }} items, {{ total }} USD</p>
  <button type="button" @click="add({ id: 7, name: 'Socks', price: 8 })">Add socks</button>
</template>
  1. The storeToRefs function returns refs for state and getters. Each ref reads from the store, so it is always current.
  2. It skips actions, so you take actions from the store itself.
  3. The simplest option is not to destructure at all: keep cart and write cart.total and cart.items.length in the template.
  4. In script, the refs from storeToRefs need the value property, like any ref.

Follow-up question: Why does Pinia have storeToRefs? Why not use the toRefs function from Vue on the store?

Follow-up answer:

  • The toRefs function makes a ref for every property of the object. On a store, that includes the actions and other internal properties.
  • The storeToRefs function only makes refs for the state and the getters, and skips the actions. That is exactly what you want to destructure.
  • In both cases, the key idea is the same: a ref keeps the link, a plain value copy does not.

Red flag: Says “it is a Pinia store, so everything taken from it is reactive”. Or tests only the add button, sees the count go up, and says it works.

Report a problem or send a better text

Edit on GitHub

8Showing product reviews with v-htmlMedium–Vue fundamentalsFrontend security

Question: Customers can write reviews on product pages. Any logged-in user can post one, and every visitor of the product page sees it. The product manager wanted line breaks and bold text in reviews, so a teammate wrote this:

<script setup lang="ts">
type Review = { id: number; author: string; text: string }

defineProps<{ review: Review }>()
</script>

<template>
  <article class="review">
    <h4>{{ review.author }}</h4>
    <p v-html="review.text"></p>
  </article>
</template>

The review text is saved in the database exactly as the user typed it. You see this in code review. What do you think? Is there a problem?

Short answer: This is a stored XSS hole. The v-html directive puts the string into the page as real HTML, without escaping. Any user can post a review with HTML that runs JavaScript, for example an image tag with an onerror attribute. That script then runs in the browser of every visitor of the product page, with their session. Show user text with normal text interpolation. If you really need formatting, use a limited format like Markdown and sanitize the HTML with a trusted library before you render it.

Hint (if the candidate says there is no problem): A security researcher posts a review that contains an image tag with a broken src and an onerror attribute. Since then, every visitor of that product page sends a request to a strange domain.

Why does this happen? (step by step)

  1. Double curly braces escape text. Characters like the less-than sign are shown as characters, never parsed as HTML. That is why normal Vue templates are safe by default.
  2. The v-html directive skips this protection. It sets the innerHTML of the element to the string.
  3. A script tag inserted with innerHTML does not run. But event handler attributes do. An image with a broken src and an onerror attribute runs its code when the image fails to load.
  4. The text is stored in the database. So the attack runs again for every visitor, not only for the attacker.
  5. The script runs on our domain. It can read what the page can read, call our API as the visitor, change the page, or send the user to a fake login form.
  6. The Vue docs say it directly: use v-html only on trusted content, never on content from users.

The fix:

For plain text with line breaks, no HTML is needed at all:

<script setup lang="ts">
type Review = { id: number; author: string; text: string }

defineProps<{ review: Review }>()
</script>

<template>
  <article class="review">
    <h4>{{ review.author }}</h4>
    <p class="review-text">{{ review.text }}</p>
  </article>
</template>

<style scoped>
.review-text {
  white-space: pre-line; /* keep the user's line breaks */
}
</style>
  1. The text is escaped, so any HTML the user typed is shown as harmless text.
  2. The CSS white-space property keeps the line breaks.
  3. If the product manager really needs bold text, let users write a small format like Markdown. Turn it into HTML, then sanitize that HTML with a well-known library such as DOMPurify, with an allow-list of a few tags. Only then use v-html.
  4. Defense in depth: a Content Security Policy that blocks inline scripts makes many XSS attacks fail. Session cookies with the HttpOnly flag cannot be read by JavaScript.
  5. The trade-off: sanitizing adds a library and some work, and you must keep it updated. Plain text has no such cost.

Follow-up question: The backend team says “we already sanitize the review when we save it”. Is v-html safe now?

Follow-up answer:

  • It is better, but it is risky to depend only on that. Old reviews in the database may be from before the sanitizer existed.
  • Other code paths may write reviews later, like an import job or an admin tool, and skip the sanitizer.
  • What is safe depends on where the text is used. HTML that is safe in one place may not be safe in another.
  • So sanitize close to where you render HTML, or better, do not render user HTML at all. Then add CSP as a second layer.

Red flag: Says “Vue escapes everything, so XSS is not possible in Vue”, without knowing that v-html is the exception. Or tries to block only the word “script” in the text.

Report a problem or send a better text

Edit on GitHub

9State at module level in a composableMedium to hard–State in Vue

Question: The checkout page of our shop is rendered on the server (SSR) with Node.js, then it becomes interactive in the browser. On the same page there are two forms: the buyer’s address, and a “send as a gift” address. Both use this composable:

// useAddressForm.ts
import { computed, reactive } from 'vue'

const form = reactive({ name: '', street: '', city: '' })

export function useAddressForm(prefill?: { name: string }) {
  if (prefill) form.name = prefill.name

  const isValid = computed(
    () => form.name !== '' && form.street !== '' && form.city !== '',
  )

  function reset() {
    form.name = ''
    form.street = ''
    form.city = ''
  }

  return { form, isValid, reset }
}

The buyer form calls it with the name of the logged-in user. The gift form calls it with no argument. You see this in code review. What do you think? Is there a problem?

Short answer: The form object is created at module level, once, when the file is first imported. So every call of the composable returns the same object. In the browser, the two forms share one address: typing in one changes the other. On the server it is worse: the Node.js process imports the module once and renders pages for many users, so the name of one user can appear in the page of another. Create the state inside the function. If you really need shared state, use a Pinia store, which with SSR gets a new instance for each request.

Hint (if the candidate says there is no problem): In the browser, a user types the gift address and sees the buyer address change too. In production, a guest customer who is not logged in reports that the checkout page showed the name of a stranger in the address form for a moment, and then the field became empty.

Why does this happen? (step by step)

  1. A JavaScript module runs only once. Every import gets the same module, with the same top-level variables.
  2. So the reactive form object exists once. The composable does not create it. It only returns it.
  3. In the browser, both forms receive the same object. The v-model of each input writes into the same name, street and city. The reset function of one form clears the other too.
  4. On the server, one Node.js process handles requests from many users. The module stays loaded between requests.
  5. User A opens checkout. The server writes A’s name into the shared form. Then user B, a guest who is not logged in, opens checkout. Nothing sets the name for B, so the HTML for B contains A’s name.
  6. This is called cross-request state pollution. It is a privacy problem, not just a UI bug.

The fix:

// useAddressForm.ts
import { computed, reactive } from 'vue'

export function useAddressForm(prefill?: { name: string }) {
  const form = reactive({ name: prefill?.name ?? '', street: '', city: '' }) // new for each call

  const isValid = computed(
    () => form.name !== '' && form.street !== '' && form.city !== '',
  )

  function reset() {
    form.name = ''
    form.street = ''
    form.city = ''
  }

  return { form, isValid, reset }
}
  1. Now each call creates its own form. The two forms on the page are independent.
  2. On the server, each request renders new components, so each request gets new state.
  3. If some state must really be shared, for example the cart, put it in a Pinia store. With SSR, the app creates a new Pinia instance for each request, so stores are not shared between users.
  4. Keep only things that are truly the same for everyone at module level: constants, pure helper functions, configuration.

Follow-up question: In a small app with no SSR, is module-level state in a composable always wrong?

Follow-up answer:

  • No. In a browser-only app, module-level state is shared by everything in one tab, and that is sometimes what you want. The Vue docs even show it as a simple global store.
  • The problem is that it is hidden. A reader sees a function called useSomething and expects new state on each call.
  • If you do it on purpose, make it clear in the name and in a comment. For anything bigger, a Pinia store gives the same sharing plus devtools, SSR safety and a clear place to look.
  • If the app might use SSR later, avoid it from the start.

Red flag: Says “a composable is a function, so its state is always new”. Or sees the shared form in the browser but does not see the risk of leaking data between users on the server.

Report a problem or send a better text

Edit on GitHub

1050,000 rows in a deep refHardWeight ×2–State in VueWeb performance

Question: The shop has an admin page for the warehouse team. It loads the whole inventory, about 50,000 rows, and lets staff filter by name. Staff use normal office laptops. The page is read-only. A teammate wrote this:

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'

type Row = { id: number; sku: string; name: string; price: number; stock: number }

const rows = ref<Row[]>([])
const search = ref('')

const visibleRows = computed(() =>
  rows.value.filter((row) => row.name.toLowerCase().includes(search.value.toLowerCase())),
)

onMounted(async () => {
  const res = await fetch('/api/admin/inventory')
  rows.value = await res.json()
})
</script>

<template>
  <input v-model="search" type="search" placeholder="Filter by name" />
  <table>
    <tbody>
      <tr v-for="row in visibleRows" :key="row.id">
        <td>{{ row.sku }}</td>
        <td>{{ row.name }}</td>
        <td>{{ row.price }}</td>
        <td>{{ row.stock }}</td>
      </tr>
    </tbody>
  </table>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: The code is correct, but it does much more work than needed. First, a normal ref makes the array deeply reactive: every row gets wrapped in a Proxy when it is read, and every property read in the filter and the render is tracked. For read-only data this is pure overhead. Use shallowRef so only the array replacement is tracked. Second, and often bigger, the page can render up to 50,000 table rows, which is a huge DOM. Use pagination or a virtual list, or filter on the server. Measure before and after.

Hint (if the candidate says there is no problem): After the data loads, the page freezes for a moment. Each key press in the filter box feels slow, and the INP of the page is far above 200 ms. The browser’s performance panel shows long tasks, and the memory of the tab is high.

Why does this happen? (step by step)

  1. A ref that holds an array passes it to the reactive function. The array becomes a deep reactive Proxy.
  2. Vue creates nested Proxies lazily, when an object is read. The filter reads every row, so every row gets a Proxy, and Vue keeps extra data for tracking.
  3. Each read of row.name inside the computed goes through a Proxy and is tracked as a dependency. That is 50,000 tracked reads for one filter run, on every key press.
  4. The render then reads sku, name, price and stock of every visible row through Proxies again, and tracks them too.
  5. All of this is for data that never changes in place. We only replace the whole list.
  6. On top of that, an empty filter shows 50,000 table rows with 4 cells each. Creating and laying out that many DOM nodes is slow by itself, with or without reactivity.

The fix:

<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue'

type Row = { id: number; sku: string; name: string; price: number; stock: number }
type IndexedRow = Row & { searchName: string }

const PAGE_SIZE = 100

const rows = shallowRef<IndexedRow[]>([]) // only .value is tracked
const search = ref('')
const page = ref(1)

const visibleRows = computed(() => {
  const q = search.value.toLowerCase()
  return rows.value.filter((row) => row.searchName.includes(q))
})

const pageRows = computed(() =>
  visibleRows.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE),
)

onMounted(async () => {
  const res = await fetch('/api/admin/inventory')
  const data: Row[] = await res.json()
  rows.value = data.map((row) => ({ ...row, searchName: row.name.toLowerCase() }))
})
</script>

<template>
  <input v-model="search" type="search" placeholder="Filter by name" @input="page = 1" />
  <p>{{ visibleRows.length }} rows</p>
  <table>
    <tbody>
      <tr v-for="row in pageRows" :key="row.id">
        <td>{{ row.sku }}</td>
        <td>{{ row.name }}</td>
        <td>{{ row.price }}</td>
        <td>{{ row.stock }}</td>
      </tr>
    </tbody>
  </table>
  <button type="button" :disabled="page === 1" @click="page--">Previous</button>
  <button type="button" :disabled="page * PAGE_SIZE >= visibleRows.length" @click="page++">
    Next
  </button>
</template>
  1. The shallowRef only tracks its value property. The rows stay plain objects. No Proxy per row, no tracking per property.
  2. The lowercase name is calculated once, when the data loads, not 50,000 times on each key press.
  3. Only one page of rows is rendered. The DOM stays small. A virtual list, which renders only the rows on screen, is another good option.
  4. The markRaw function is the tool for a single object that must never become reactive, like a chart library instance stored in reactive state. For a big list, shallowRef is usually simpler.
  5. Even better for very big data: filter and paginate on the server, so the browser never downloads 50,000 rows.
  6. The trade-off: with shallowRef, changing a field of a row in place does not update the screen. You must replace the array, or call triggerRef. Measure with the browser’s performance panel to confirm the gain.

Follow-up question: Staff now want to edit the stock of a row inline. How do you update one row with a shallowRef?

Follow-up answer:

  • Replace the array with a new one, where only the changed row is a new object:
function updateStock(id: number, stock: number) {
  rows.value = rows.value.map((row) => (row.id === id ? { ...row, stock } : row))
}
  • This walks the array once, but it creates no Proxies and tracks nothing per row, so for 50,000 plain objects it is usually fast.
  • Another option: change the row in place and then call triggerRef on rows. It is shorter, but it is easy to forget the triggerRef call.
  • If edits become frequent, keep the row being edited in its own small ref, and write it back when the user saves.

Red flag: Says “Vue is slow, let’s use another framework” without measuring. Or adds a debounce on the input and stops there: it hides the delay but each run is still slow and the DOM is still huge.

Report a problem or send a better text

Edit on GitHub

11Fetching in a watcher when the id changesMedium to hard–Vue fundamentalsJavaScript fundamentals

Question: The product page has “previous” and “next” arrows. The parent passes the product id as a prop. Many of our users shop on phones with a slow mobile network. A teammate wrote the product details component like this:

<script setup lang="ts">
import { ref, watch } from 'vue'

type Product = { id: number; name: string; price: number }

const { productId } = defineProps<{ productId: number }>()
const product = ref<Product | null>(null)

watch(
  () => productId,
  async (id) => {
    const res = await fetch(`/api/products/${id}`)
    product.value = await res.json()
  },
  { immediate: true },
)
</script>

<template>
  <h1 v-if="product">{{ product.name }}</h1>
</template>

You see this in code review. What do you think? Is there a problem?

Short answer: This is a race condition. Each id change starts a new request, but nothing stops the old ones. Responses can arrive in any order, so the last response to arrive wins, not the last request. On a slow network, the page can show the wrong product. Cancel the old request when the id changes: create an AbortController in the callback and abort it with onWatcherCleanup (Vue 3.5). Also check res.ok and handle errors.

Hint (if the candidate says there is no problem): A user on a train taps “next” twice quickly. The URL and the arrows say product 12, but the title shows product 11. Sometimes the title changes twice in a row. On a fast office network, nobody can reproduce it.

Why does this happen? (step by step)

  1. The id changes from 10 to 11. The watcher starts request A for product 11.
  2. Before A finishes, the id changes to 12. The watcher starts request B for product 12. Request A is still running.
  3. Request B is fast and finishes first. The page shows product 12. Correct, for now.
  4. Request A is slow and finishes later. Its callback still runs and writes product 11 into product.value.
  5. Now the page shows product 11 while the user is on product 12. The watcher runs each callback to the end, because nothing tells the old one to stop.
  6. There is a second problem: if the server returns an error status like 404 or 500, the code still parses the body and treats it as a product.

The fix:

<script setup lang="ts">
import { onWatcherCleanup, ref, watch } from 'vue'

type Product = { id: number; name: string; price: number }

const { productId } = defineProps<{ productId: number }>()
const product = ref<Product | null>(null)
const error = ref<string | null>(null)

watch(
  () => productId,
  async (id) => {
    const controller = new AbortController()
    onWatcherCleanup(() => controller.abort()) // call before the first await

    error.value = null
    try {
      const res = await fetch(`/api/products/${id}`, { signal: controller.signal })
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      product.value = await res.json()
    } catch {
      if (controller.signal.aborted) return // a newer id is loading
      error.value = 'Could not load the product.'
    }
  },
  { immediate: true },
)
</script>

<template>
  <p v-if="error">{{ error }}</p>
  <h1 v-else-if="product">{{ product.name }}</h1>
</template>
  1. Vue calls the cleanup function before it runs the callback again, and when the component unmounts.
  2. The cleanup aborts the old request. The fetch of the old request rejects, the catch block sees that the signal was aborted, and returns without touching the state.
  3. Only the request for the current id can write to product.
  4. The res.ok check turns error statuses into real errors.
  5. Aborting also saves bandwidth on slow networks, because the browser stops downloading the old response. The server may still finish its work, so this does not replace server-side limits.
  6. The trade-off: a few more lines. A server-data library like TanStack Query for Vue does this, plus caching, for you.

Follow-up question: Why must onWatcherCleanup be called before the first await? And what can you use in Vue versions before 3.5?

Follow-up answer:

  • The onWatcherCleanup function finds the watcher that is running right now. Vue knows this only during the synchronous part of the callback. After an await, the callback continues later, when Vue may be running something else. So the cleanup is not registered, and Vue shows a warning in development.
  • The watch callback also receives a third argument, an onCleanup function. It is bound to its watcher, so it works even after an await. This argument existed before Vue 3.5 too.
  • Without AbortController, a simple flag also works: set a cancelled variable to true in the cleanup, and skip the state update if it is true. It does not stop the download, but it stops the wrong write.

Red flag: Says “JavaScript is single-threaded, so there is no race condition”. Or adds a loading flag and disables the arrows, which hides the problem but makes the page slower to use.

Report a problem or send a better text

Edit on GitHub

12Design the state of a product filter pageDesignWeight ×2–Vue fundamentalsState in VueWeb performance

Question: Design the product list page of our online shop in Vue. The shop has about 20,000 products. The page has a search box, a category filter, a sort order and pages of results. Most users are on phones. Users often send a link of a filtered list to friends, and they use the back button a lot. The header shows a cart badge on every page. Explain where each piece of state lives, how data flows, and what the hard parts are. Explain your design step by step.

Short answer: Each piece of state goes to the place that matches who needs it and how long it must live. Search, category, sort and page live in the URL query, so links, refresh and the back button work. A composable reads and validates them. The product list is server data: the server filters and paginates, and the browser keeps a cached copy keyed by the query, with loading and error states and cancelling of stale requests. The cart lives in a Pinia store because far apart parts of the app share it. UI details, like the search draft while typing or an open filter panel, stay as local refs.

Requirements and numbers:

  1. Twenty thousand products is too many to download to a phone. Filtering, sorting and paging must happen on the server. One page of maybe 24 to 48 products is enough.
  2. Shareable links mean the URL must fully describe the list. Someone who opens the link must see the same results.
  3. The back button must go back to the previous filter, with no strange extra steps.
  4. Phones on slow networks mean requests can finish out of order. An old answer must never replace a new one.
  5. Questions to ask: do we need server rendering for SEO? Are prices per user? How fresh must stock information be?

Where each piece of state lives:

  1. The URL query: search, category, sort, page. It is the single source of truth for “which list are we looking at”.
  2. Local refs: the text in the search box while the user is typing, whether the filter panel is open on mobile. Nobody else needs them, and they should not be in a shared link.
  3. Server data: the current page of products and the total count. It is a copy of the server. It needs loading, error, cancel, and ideally a cache.
  4. A Pinia store: the cart and the logged-in user. The header, the product page and the checkout all use them.
  5. Computed values: everything you can calculate, like “has more pages” or the API URL. Never a second copy in state.

Data flow (step by step):

  1. The user picks a category. The page calls setFilter, which writes the new query to the URL and resets the page to 1.
  2. The router updates the route. The filters computed reads the new query and validates it.
  3. The API URL computed changes. The server-data composable sees a new URL, aborts the old request and starts a new one.
  4. While loading, the page keeps showing the old results with a loading state, so the layout does not jump.
  5. The answer arrives and the list renders. If the user presses back, the URL changes again, and the same flow runs in reverse.

The filters composable:

// useProductFilters.ts
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const SORTS = ['popular', 'price-asc', 'price-desc'] as const
export type Sort = (typeof SORTS)[number]
export type Filters = { search: string; category: string; sort: Sort; page: number }

function readString(value: unknown, fallback: string): string {
  return typeof value === 'string' ? value : fallback
}

export function useProductFilters() {
  const route = useRoute()
  const router = useRouter()

  // The URL is the single source of truth. Bad values fall back to defaults.
  const filters = computed<Filters>(() => {
    const sort = readString(route.query.sort, 'popular')
    const page = Math.floor(Number(route.query.page))
    return {
      search: readString(route.query.search, ''),
      category: readString(route.query.category, 'all'),
      sort: (SORTS as readonly string[]).includes(sort) ? (sort as Sort) : 'popular',
      page: page >= 1 ? page : 1,
    }
  })

  // A new filter starts again from page 1
  function setFilter(changes: Partial<Omit<Filters, 'page'>>, options = { replace: false }) {
    const query = { ...route.query, ...changes, page: undefined }
    return options.replace ? router.replace({ query }) : router.push({ query })
  }

  function setPage(page: number) {
    return router.push({ query: { ...route.query, page: String(page) } })
  }

  return { filters, setFilter, setPage }
}

The page:

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useFetchJson } from '../composables/useFetchJson'
import { useProductFilters } from '../composables/useProductFilters'

type ProductPage = { items: { id: number; name: string; price: number }[]; total: number }

const { filters, setFilter, setPage } = useProductFilters()

const apiUrl = computed(() => {
  const { search, category, sort, page } = filters.value
  const params = new URLSearchParams({ search, category, sort, page: String(page) })
  return `/api/products?${params}`
})

// Server data: a new URL starts a new request and aborts the old one
const { data, error, loading } = useFetchJson<ProductPage>(apiUrl)

// The search box keeps a local draft, so each key press does not change the URL
const searchDraft = ref(filters.value.search)
let timer: ReturnType<typeof setTimeout> | undefined

watch(searchDraft, (value) => {
  clearTimeout(timer)
  if (value === filters.value.search) return
  timer = setTimeout(() => setFilter({ search: value }, { replace: true }), 300)
})

// Back button: the URL changed, so the draft follows it
watch(
  () => filters.value.search,
  (value) => {
    searchDraft.value = value
  },
)
</script>

<template>
  <input v-model="searchDraft" type="search" placeholder="Search products" />
  <p v-if="error">Could not load products.</p>
  <ul :aria-busy="loading">
    <li v-for="product in data?.items ?? []" :key="product.id">{{ product.name }}</li>
  </ul>
  <button type="button" :disabled="filters.page === 1" @click="setPage(filters.page - 1)">
    Previous
  </button>
  <button type="button" @click="setPage(filters.page + 1)">Next</button>
</template>

Hard parts and trade-offs:

  • Push or replace: a discrete choice, like a category or a page, uses push, so the back button can undo it. Typing in the search box uses replace after a short debounce. Otherwise every key press becomes a history entry.
  • Validation: the user can edit the URL. Every query value is a string or missing. Parse it, check it against allowed values, and fall back to a default.
  • Reset the page: a new filter must go back to page 1. Otherwise the user can land on page 7 of a list that has only 2 pages.
  • Stale answers: fast filter changes on a slow network can finish out of order. Abort the old request, as useFetchJson does with onWatcherCleanup.
  • Cache: the small composable above fetches again after the back button. A server-data library like TanStack Query for Vue caches by key, so going back shows the list at once and refreshes it in the background. The cost is one more dependency.
  • What not to put in Pinia: the filters and the product list. If they live in a store, the URL and the store can disagree, and links stop working. The store is for the cart and the user.
  • Performance on phones: render only one page, give images a fixed size and lazy loading below the fold, and prefetch the next page when the user is near the end.
  • Accessibility: announce the result count in a polite live region when the filters change, so screen reader users know the list changed.

How it scales: the browser only ever holds one page of results, so 20,000 or 2 million products look the same to it. The server needs indexes for the filters and sorts it supports. Popular filter URLs can also be cached on a CDN, because the URL fully describes the response.

Follow-up question: Product managers want the shop to remember the user’s last sort order on the next visit, and to remember whether the filter panel was open. Where do you put these?

Follow-up answer:

  • The open or closed panel is pure UI. Keep it in a local ref, or in localStorage if it should survive a reload. It does not belong in the URL, because a friend who opens the link does not care.
  • The last sort order is a user preference. Save it in localStorage, or in the user profile on the server for logged-in users.
  • The URL still wins. Use the saved sort only when the URL has no sort value. Otherwise a shared link would show a different list for each person.
  • When you apply the saved sort, use replace, so the back button does not stop at an extra step.

Red flag: Puts filters and the product list in a Pinia store and ignores the URL, so links and the back button break. Or downloads all 20,000 products and filters them in the browser on a phone.

Report a problem or send a better text

Edit on GitHub

13Related products show the old productMedium–Routing in VueVue fundamentals

Question: This is our product page. At the bottom there is a list of related products, each one a RouterLink to /products/:id.

<!-- ProductPage.vue, route: /products/:id -->
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const product = ref<Product | null>(null);

onMounted(async () => {
  product.value = await getProduct(route.params.id as string);
});
</script>

<template>
  <h1>{{ product?.name }}</h1>
  <RelatedProducts :product-id="route.params.id" />
</template>

Users say: “I click a related product, the URL changes, but the page still shows the old product. A refresh fixes it.” Why? How do you fix it?

Short answer: Both URLs match the same route, so Vue Router reuses the same ProductPage instance. It is not unmounted and mounted again, so onMounted does not run again and the old product stays. Watch route.params.id with immediate: true (or use onBeforeRouteUpdate), and cancel or ignore old requests so a slow answer cannot overwrite a newer one.

Hint (if the candidate is stuck): Put a console.log in onMounted. It prints only once, even after three clicks on related products.

Why does this happen? (step by step)

  1. /products/1 and /products/2 match the same route record with the same component.
  2. The router only changes the route params. The RouterView keeps the same component instance, which is faster and keeps state.
  3. onMounted runs once per instance, so the fetch runs only for the first id.
  4. The template reads route.params.id, so the related list updates, but product does not.

The fix:

const route = useRoute();
const product = ref<Product | null>(null);

watch(
  () => route.params.id as string,
  async (id, _old, onCleanup) => {
    const controller = new AbortController();
    onCleanup(() => controller.abort()); // a newer id cancels this one
    product.value = await getProduct(id, controller.signal);
  },
  { immediate: true },
);
  1. immediate: true runs it for the first id too, so onMounted is not needed.
  2. onCleanup runs when the id changes again before the request ends. The old request is aborted.
  3. Reset or keep the old product while loading, and show a loading state, so the user sees that something happens.
  4. Scroll to the top after the change (router scrollBehavior), because the user expects a new page.

Follow-up question: A teammate says: “Just put :key="route.fullPath" on the RouterView.” Is that OK?

Follow-up answer:

  • It works: every URL change mounts a new page, so onMounted runs again.
  • But all state of the page is lost (for example an open tab or a half-filled review form), and everything renders again, including parts that did not change.
  • It also changes on every query change, like ?tab=reviews. Watching the param is more precise.

Red flag: Says the router is broken, or fixes it with window.location.href = ... (a full page reload).

Report a problem or send a better text

Edit on GitHub

14Two orders from one checkoutMedium–Forms and validation in VueFrontend security

Question: This is the pay button of our checkout form:

<script setup lang="ts">
const form = reactive({ email: '', address: '' });
const errors = computed(() => ({
  email: form.email.includes('@') ? '' : 'Email is required',
  address: form.address ? '' : 'Address is required',
}));

async function pay() {
  if (errors.value.email || errors.value.address) return;
  await api.createOrder(form);
  router.push('/thank-you');
}
</script>

<template>
  <input v-model="form.email" placeholder="Email" />
  <span class="red">{{ errors.email }}</span>
  <input v-model="form.address" placeholder="Address" />
  <span class="red">{{ errors.address }}</span>
  <button @click="pay">Pay</button>
</template>

You see this in code review. What problems do you see?

Short answer: The main bug: nothing stops a second click while the request runs, so a fast double click (or a slow network and a retry) creates two orders. Disable the button while submitting, and send an idempotency key so the server creates only one order. Also: the rules are only in the browser, so the server must validate again with the same rules; the errors show on page load; there are no labels (only placeholders) and errors are not linked to inputs for screen readers; and it is not a real form, so Enter does not submit.

Hint (if the candidate sees only one problem): Support says some customers were charged twice. A security test sent an order with an empty address directly to the API. A screen reader user said “I cannot find what is wrong”.

Why does this happen? (step by step)

  1. pay is async. Between the first click and the answer, the button still works, so a second click calls createOrder again.
  2. A disabled button alone is not enough: a timeout, a retry or a second tab can still send the same order twice.
  3. The errors are a computed with no “touched” state, so both messages are visible as soon as the page opens.
  4. Anyone can call the API without this page, so a check in the browser protects nothing.

The fix:

<script setup lang="ts">
const submitting = ref(false);
const submitted = ref(false);
const orderKey = crypto.randomUUID();

async function pay() {
  submitted.value = true;
  const result = checkoutSchema.safeParse(form);
  if (!result.success || submitting.value) return focusFirstError();

  submitting.value = true;
  try {
    await api.createOrder(result.data, { idempotencyKey: orderKey });
    router.push('/thank-you');
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <form @submit.prevent="pay" novalidate>
    <TextField id="email" label="Email" v-model="form.email" :error="shownErrors.email" />
    <TextField id="address" label="Address" v-model="form.address" :error="shownErrors.address" />
    <button type="submit" :disabled="submitting">Pay</button>
  </form>
</template>
  1. The server uses the idempotency key: a second request with the same key returns the first result and does not charge again.
  2. The server validates with the same schema (shared code, for example Zod).
  3. shownErrors shows an error only after blur or after submit.
  4. TextField has a label, aria-invalid and aria-describedby, and the first wrong field gets the focus.

Follow-up question: Where should the idempotency key be created, and when should it change?

Follow-up answer:

  • Create it once per checkout attempt in the browser (or get it from the server with the cart), not once per click.
  • Keep the same key for retries of the same order.
  • Make a new key only when the user changes the cart or starts a new order.

Red flag: Thinks :disabled is enough, or says validation in the browser is safe because “users cannot change our JavaScript”.

Report a problem or send a better text

Edit on GitHub

15A Nuxt product page that fetches twiceHardWeight ×2–Nuxt and server rendering

Question: We moved the shop to Nuxt. This is the product page:

<!-- pages/products/[id].vue -->
<script setup lang="ts">
const route = useRoute();
const product = await $fetch(`/api/products/${route.params.id}`);
const seenAt = new Date().toLocaleTimeString();
</script>

<template>
  <h1>{{ product.name }}</h1>
  <p>Price: {{ product.price }}</p>
  <small>Price checked at {{ seenAt }}</small>
</template>

The API logs show two calls for every page view, and the browser console shows a hydration warning. Explain both. How do you fix them?

Short answer: Code in setup runs on the server and again in the browser during hydration. A plain $fetch in setup calls the API in both places, so there are two calls. Use useFetch (or useAsyncData): the server sends the result in the page payload and the browser reuses it. The hydration warning comes from new Date(): the server and the browser render different times (and maybe a different time zone), so the HTML does not match. Make the time once on the server and send it with the data, or render it only in the browser (onMounted or ClientOnly).

Hint (if the candidate is stuck): Add console.log(import.meta.server ? 'server' : 'client') in setup. You see both.

Why does this happen? (step by step)

  1. On a request, Nuxt runs the page’s setup on the server, renders HTML and sends it.
  2. In the browser, Vue runs setup again to hydrate, so it can connect the components to the HTML.
  3. $fetch does not know about this. It just makes a request each time it runs.
  4. useFetch stores its result under a key in the payload (the data inside the HTML). In the browser it finds the key and does not fetch.
  5. The time string made in the browser is different from the one in the server HTML, so Vue sees a mismatch.

The fix:

<script setup lang="ts">
const route = useRoute();
const { data: product, error } = await useFetch(
  () => `/api/products/${route.params.id}`,
);
if (error.value) throw createError({ statusCode: 404 });
</script>

<template>
  <h1>{{ product!.name }}</h1>
  <p>Price: {{ product!.price }}</p>
  <!-- checkedAt comes from the API, formatted with a fixed time zone -->
  <small>Price checked at <NuxtTime :datetime="product!.checkedAt" /></small>
</template>
  1. One API call per view, made on the server.
  2. A missing product gives a real 404 status, not an empty page with 200.
  3. The time is data from the server. If you want the user’s local time, format it only after mount.
  4. Keep using $fetch in click handlers, like “Add to cart”.

Follow-up question: The cart composable has const items = ref([]) at the top of the file, outside the function. It worked as a single-page app. What happens with SSR?

Follow-up answer:

  • On the server, one Node process serves many users, and module state lives as long as the process.
  • So all users share the same cart on the server: one user can see another user’s items in the HTML. This is cross-request state pollution, and a privacy bug.
  • Use useState('cart', () => []) or a Pinia store, which are created per request.

Red flag: Says “turn off SSR” as the fix for everything, or hides the warning without understanding the mismatch.

Report a problem or send a better text

Edit on GitHub

16Scroll to the new item goes to the old endHardWeight ×2–How Vue works inside

Question: In the admin panel, “Add product” adds a row and should scroll to it:

const products = ref<Product[]>([]);
const listEl = ref<HTMLElement | null>(null);

function addProduct(p: Product) {
  products.value.push(p);
  console.log(listEl.value!.children.length); // one less than products
  listEl.value!.lastElementChild!.scrollIntoView();
}

It scrolls to the row before the new one, and the log shows one row less than the array. Explain what Vue does here, step by step. How do you fix it?

Short answer: Vue does not update the DOM when you change state. The change triggers the component’s render effect, and Vue puts its update job into a queue. The queue runs in a microtask after the current code ends, so many changes give one render. Right after push, the DOM is still old. Wait for the render with await nextTick() before you read or scroll the DOM.

Hint (if the candidate is stuck): Put the scroll inside setTimeout(..., 0). It works. Why?

Why does this happen? (step by step)

  1. products.value is a reactive array (a Proxy). push changes its length and adds an index, so the set trap calls trigger.
  2. trigger finds the effects that read this array during the last render: the component’s render effect.
  3. It does not run the render now. It adds the update job to the queue (only once, even for many changes) and schedules a flush in a microtask.
  4. The rest of addProduct runs with the old DOM: the new row does not exist yet.
  5. After the function returns, the microtask runs the queue: the component renders and patches the DOM.

The fix:

async function addProduct(p: Product) {
  products.value.push(p);
  await nextTick(); // waits until the queue has run
  listEl.value!.lastElementChild!.scrollIntoView({ block: 'nearest' });
}
  1. nextTick returns a promise that resolves after the pending updates are done.
  2. If the code is a reaction to state, a watch with flush: 'post' also runs after the DOM update.
  3. setTimeout works too, but it waits longer than needed (a macrotask) and hides the real reason.

Follow-up question: The list has 20,000 products and typing in the filter box is slow. The data is read-only. What do you check, and what can you change?

Follow-up answer:

  • Measure with Vue DevTools and the browser profiler: is the time in reactivity, in render, or in the DOM?
  • A deep ref makes a Proxy for every product that is read and tracks every property. Use shallowRef (or markRaw on the items) and replace the array instead of changing items inside it.
  • Make the filtered list a computed, so it runs once per filter change.
  • Render only the visible rows with a virtual list. 20,000 DOM rows are slow even without Vue.

Red flag: Says “Vue is slow, add setTimeout” without being able to explain the queue, or thinks every change renders at once.

Report a problem or send a better text

Edit on GitHub