0
0
Svelteframework~10 mins

API authentication patterns in Svelte - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a Bearer token to the fetch request headers.

Svelte
const response = await fetch('/api/data', {
  headers: {
    'Authorization': '[1]'
  }
});
Drag options to blanks, or click blank then click option'
A'Bearer myToken123'
B'Token myToken123'
C'Basic myToken123'
D'ApiKey myToken123'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Basic' instead of 'Bearer' for token authentication.
2fill in blank
medium

Complete the code to store the JWT token in localStorage after login.

Svelte
function handleLogin(token) {
  [1].setItem('jwt', token);
}
Drag options to blanks, or click blank then click option'
AsessionStorage
BlocalStorage
Cstorage
DcookieStorage
Attempts:
3 left
💡 Hint
Common Mistakes
Using sessionStorage which clears on tab close.
3fill in blank
hard

Fix the error in the Svelte fetch call to include the token from a reactive variable.

Svelte
let token = '';

async function fetchData() {
  const res = await fetch('/api/secure', {
    headers: {
      'Authorization': '[1]'
    }
  });
  return await res.json();
}
Drag options to blanks, or click blank then click option'
A'Bearer ${token}'
B'Bearer token'
C`Bearer ${token}`
DBearer + token
Attempts:
3 left
💡 Hint
Common Mistakes
Using single quotes which do not interpolate variables.
4fill in blank
hard

Fill both blanks to create a Svelte store that holds the auth token and a function to clear it.

Svelte
import { writable } from 'svelte/store';

export const authToken = writable([1]);

export function clearToken() {
  authToken.[2]('');
}
Drag options to blanks, or click blank then click option'
A''
Bset
Cupdate
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using update instead of set to replace the token value.
5fill in blank
hard

Fill all three blanks to create an authenticated fetch function that adds an Authorization header with the token to fetch calls.

Svelte
import { get } from 'svelte/store';
import { authToken } from './stores';

export async function authFetch(url, options = {}) {
  const token = get([1]);
  options.headers = {
    ...options.headers,
    'Authorization': [2]
  };
  return fetch(url, options);
}

// Usage: authFetch('/api/data', { method: [3] })
Drag options to blanks, or click blank then click option'
AauthToken
B`Bearer ${token}`
C'GET'
D'POST'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to spread existing headers in options.headers.