Bird
Raised Fist0
Svelteframework~20 mins

Middleware patterns with hooks in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery in Svelte
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Svelte middleware hook?

Consider this SvelteKit handle hook that modifies the response headers. What will the browser receive as the Content-Type header?

Svelte
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  response.headers.set('Content-Type', 'application/json');
  return response;
}
AThe response will have no 'Content-Type' header.
BThe response will keep the original 'Content-Type' header from the resolved response.
CThe response will have 'Content-Type' set to 'application/json'.
DThe code will throw a runtime error because headers are immutable.
Attempts:
2 left
💡 Hint

Think about whether the response.headers object is mutable and if setting headers after resolve works.

❓ lifecycle
intermediate
2:00remaining
In what order do these SvelteKit hooks run during a request?

Given these hooks in hooks.server.js, what is the correct order they execute when a request comes in?

Svelte
export async function handle({ event, resolve }) {
  console.log('handle start');
  const response = await resolve(event);
  console.log('handle end');
  return response;
}

export async function handleFetch({ request, fetch }) {
  console.log('handleFetch');
  return fetch(request);
}

export async function getSession(event) {
  console.log('getSession');
  return { user: null };
}
A3, 1, 2
B3, 2, 1
C1, 3, 2
D2, 3, 1
Attempts:
2 left
💡 Hint

Remember that handle wraps the whole request, handleFetch runs during fetch calls inside handle, and getSession runs after handle.

🔧 Debug
advanced
2:00remaining
Why does this SvelteKit middleware hook cause a runtime error?

Examine this handle hook code. Why does it throw an error when a request is made?

Svelte
export async function handle({ event, resolve }) {
  const response = resolve(event);
  response.headers.set('x-custom', 'value');
  return response;
}
ABecause <code>handle</code> must return a string, not a response object.
BBecause <code>headers</code> is a read-only property and cannot be set.
CBecause <code>event</code> is missing required properties.
DBecause <code>resolve</code> is not awaited, <code>response</code> is a Promise, so <code>headers</code> is undefined.
Attempts:
2 left
💡 Hint

Check if resolve returns a Promise and if you need to wait for it.

📝 Syntax
advanced
2:00remaining
Which option correctly implements a SvelteKit handle hook that adds a cookie?

Choose the code that correctly adds a cookie named session with value abc123 to the response.

A
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  response.headers['set-cookie'] = 'session=abc123; Path=/; HttpOnly';
  return response;
}
B
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  response.headers.set('set-cookie', 'session=abc123; Path=/; HttpOnly');
  return response;
}
C
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  response.headers.append('set-cookie', 'session=abc123; Path=/; HttpOnly');
  return response;
}
D
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  response.headers.add('set-cookie', 'session=abc123; Path=/; HttpOnly');
  return response;
}
Attempts:
2 left
💡 Hint

Check the correct method to set headers on the response object.

❓ state_output
expert
3:00remaining
What is the final value of event.locals.user after this middleware chain?

Given these two handle hooks in hooks.server.js, what will event.locals.user be when the request reaches the page?

Svelte
export async function handle({ event, resolve }) {
  event.locals.user = 'guest';
  const response = await resolve(event);
  return response;
}

export async function handle({ event, resolve }) {
  if (event.request.headers.get('authorization') === 'Bearer token123') {
    event.locals.user = 'admin';
  }
  return resolve(event);
}
AThe code throws an error due to duplicate handle functions.
B"admin"
Cundefined
D"guest"
Attempts:
2 left
💡 Hint

Consider how SvelteKit handles multiple handle exports in the same file.

Practice

(1/5)
1. Which Svelte hook is best suited to run code right after a component appears on the page?
easy
A. onDestroy
B. onMount
C. afterUpdate
D. beforeUpdate

Solution

  1. Step 1: Understand when onMount runs

    onMount runs once right after the component is added to the page.
  2. Step 2: Compare with other hooks

    beforeUpdate and afterUpdate run on updates, onDestroy runs when component is removed.
  3. Final Answer:

    onMount -> Option B
  4. Quick Check:

    Run code after component appears = onMount [OK]
Hint: Use onMount for code after component loads [OK]
Common Mistakes:
  • Confusing onMount with beforeUpdate
  • Using onDestroy to run code on load
  • Thinking afterUpdate runs only once
2. Which is the correct syntax to import and use the onDestroy hook in a Svelte component?
easy
A. import { onDestroy } from 'svelte/hooks'; onDestroy(() => { /* cleanup */ });
B. import onDestroy from 'svelte'; onDestroy(() => { /* cleanup */ });
C. import { onDestroy } from 'svelte'; onDestroy = () => { /* cleanup */ };
D. import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ });

Solution

  1. Step 1: Check correct import syntax

    Svelte exports hooks like onDestroy as named exports from 'svelte'.
  2. Step 2: Verify usage

    The hook is called as a function with a callback: onDestroy(() => { ... }).
  3. Final Answer:

    import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); -> Option D
  4. Quick Check:

    Named import + callback function = import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); [OK]
Hint: Use named import from 'svelte' and call with callback [OK]
Common Mistakes:
  • Using default import instead of named import
  • Importing from wrong path like 'svelte/hooks'
  • Assigning hook to a variable instead of calling it
3. Given this Svelte code snippet, what will be logged to the console when the component updates?
import { beforeUpdate, afterUpdate } from 'svelte';

beforeUpdate(() => console.log('Before update'));
afterUpdate(() => console.log('After update'));

let count = 0;

function increment() {
  count += 1;
}
medium
A. After update only once after first render
B. Only Before update once when component mounts
C. Before update\nAfter update each time increment() is called
D. No logs because hooks are not called

Solution

  1. Step 1: Understand when hooks run

    beforeUpdate runs before every DOM update, afterUpdate runs after every DOM update.
  2. Step 2: Analyze increment effect

    Calling increment() changes count, triggering component update and both hooks logging messages.
  3. Final Answer:

    Before update\nAfter update each time increment() is called -> Option C
  4. Quick Check:

    Hooks run on every update = Before update\nAfter update each time increment() is called [OK]
Hint: Hooks run before and after every update triggered by state change [OK]
Common Mistakes:
  • Thinking hooks run only once on mount
  • Assuming logs happen without calling increment()
  • Confusing beforeUpdate and afterUpdate timing
4. What is wrong with this Svelte code using onDestroy?
import { onDestroy } from 'svelte';

onDestroy = () => {
  console.log('Cleanup');
};
medium
A. Assigning a function to onDestroy instead of calling it
B. Missing import statement for onDestroy
C. Using arrow function instead of regular function
D. onDestroy should be used inside onMount

Solution

  1. Step 1: Check how onDestroy is used

    The code assigns a function to onDestroy instead of calling it with a callback.
  2. Step 2: Correct usage

    onDestroy must be called like onDestroy(() => { ... }) to register cleanup.
  3. Final Answer:

    Assigning a function to onDestroy instead of calling it -> Option A
  4. Quick Check:

    Use onDestroy(callback), not assignment [OK]
Hint: Call onDestroy with a callback, don't assign it [OK]
Common Mistakes:
  • Assigning instead of calling the hook
  • Thinking arrow functions are disallowed
  • Believing onDestroy must be inside onMount
5. You want to log a message every time a Svelte component updates but only after the DOM has changed. Which hook should you use and why? Also, how would you ensure cleanup if needed?
hard
A. Use afterUpdate to log after DOM changes; use onDestroy for cleanup
B. Use beforeUpdate to log after DOM changes; no cleanup needed
C. Use onMount to log after DOM changes; cleanup inside afterUpdate
D. Use onDestroy to log after DOM changes; cleanup inside beforeUpdate

Solution

  1. Step 1: Identify hook for after DOM update

    afterUpdate runs after the DOM updates, perfect for logging post-change.
  2. Step 2: Determine cleanup hook

    onDestroy runs when component is removed, ideal for cleanup tasks.
  3. Final Answer:

    Use afterUpdate to log after DOM changes; use onDestroy for cleanup -> Option A
  4. Quick Check:

    Log after DOM update = afterUpdate; cleanup = onDestroy [OK]
Hint: Log in afterUpdate; cleanup in onDestroy [OK]
Common Mistakes:
  • Using beforeUpdate to log after DOM changes
  • Trying to cleanup inside afterUpdate
  • Confusing onMount with update hooks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard