Performance: API authentication patterns
This affects page load speed and interaction responsiveness by controlling how authentication data is fetched and stored.
import { onMount } from 'svelte'; let user; onMount(async () => { const response = await fetch('/api/auth', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); user = await response.json(); }); // Using async/await allows non-blocking rendering and faster interaction
import { onMount } from 'svelte'; let user; onMount(() => { const xhr = new XMLHttpRequest(); xhr.open('POST', '/api/auth', false); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ username, password })); user = JSON.parse(xhr.responseText); }); // Synchronous XMLHttpRequest blocks rendering
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous XHR blocking rendering | Minimal | 0 | Blocks paint until fetch completes | [X] Bad |
| Async fetch with await | Minimal | 0 | Non-blocking paint, faster interaction | [OK] Good |
| Access token from localStorage on every request | Minimal | 0 | Small main thread blocks per request | [!] Bad |
| Access token from in-memory reactive store | Minimal | 0 | No blocking, smooth interaction | [OK] Good |
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Basic ' + btoa('user:pass')
}
});
const data = await response.json();
console.log(data.message);
Assuming the API returns {"message": "Success"} on correct auth.fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer token123'
}
})
.then(response => response.json())
.then(data => console.log(data));Pass the test and this pattern moves unknown