📖 Scenario: You are building a simple Svelte app that needs to authenticate users by sending an API token with requests. This is common when apps talk to servers that require a secret key to allow access.
🎯 Goal: Create a Svelte component that stores an API token, sets a configuration variable for the token header name, uses the token in a fetch request, and finally adds the token to the request headers to authenticate the API call.
📋 What You'll Learn
Create a variable to hold the API token string
Create a configuration variable for the header name
Use the token in a fetch request with the correct header
Add the header to the fetch options to complete the authentication
💡 Why This Matters
🌍 Real World
Many web apps need to authenticate API requests with tokens to access protected data or services.
💼 Career
Understanding how to send authentication headers in fetch requests is essential for frontend developers working with APIs.
Progress0 / 4 steps
1
Set up the API token variable
Create a variable called apiToken and set it to the string "12345abcde" inside the <script> tag.
Svelte
Hint
Use let apiToken = "12345abcde"; inside the script tag.
2
Add a configuration variable for the header name
Inside the <script> tag, create a variable called authHeader and set it to the string "Authorization".
Svelte
Hint
Use let authHeader = "Authorization"; to store the header name.
3
Use the token in a fetch request
Inside the <script> tag, create an async function called fetchData that calls fetch with the URL "https://api.example.com/data" and includes the Authorization header with the apiToken value.
Svelte
Hint
Use fetch with a headers object that sets [authHeader] to `Bearer ${apiToken}`.
4
Add a button to trigger the fetch with authentication
Add a <button> element with the text "Load Data" that calls the fetchData function when clicked inside the component markup.
Svelte
Hint
Use <button on:click={fetchData}>Load Data</button> to trigger the fetch.
Practice
(1/5)
1. What is the main purpose of API authentication in a Svelte app?
easy
A. To verify the identity of the user or app making the request
B. To speed up the API response time
C. To change the API data format
D. To style the API response
Solution
Step 1: Understand API authentication role
API authentication checks who is making the request to keep the app secure.
Step 2: Identify the correct purpose
Speed, data format, and styling are unrelated to authentication.
Final Answer:
To verify the identity of the user or app making the request -> Option A
Quick Check:
Authentication = Verify identity [OK]
Hint: Authentication means checking who you are [OK]
Common Mistakes:
Confusing authentication with performance optimization
Thinking authentication changes data format
Assuming authentication styles the response
2. Which of the following is the correct way to add a Bearer token in a fetch request header in Svelte?