So ive been able to get this to work before but im getting this error when trying to access an API while hiding the key
i was hoping to run everything in this one svelte component to make life easier
<script>
import 'dotenv/config';
const API_KEY = process.env.API_KEY;
// Fetch the data when the component is created
async function fetchData() {
const res = await fetch(`https://api.sportmonks.com/v3/football/leagues?api_token=${API_KEY}`);
const data = await res.json();
return data.data;
}
let leagues = [];
async function load() {
leagues = await fetchData();
}
// Initialize the data when the component is created
$: {
load();
}
</script>
{#each leagues as league}
<div>{league.name}</div>
{/each}
CodePudding user response:
You can't use a hidden key inside a *.svelte file, code running in frontend components is always public.
When you're using SvelteKit you can use $env/static/private or $env/dynamic/private inside page.server.js
& server.js
files inside the src/routes/ folder.
These files run on (as the name implies) on the server and have access to private environment variables.
import { API_KEY } from '$env/static/private';
Then make the api call on the server and return the results a page data/props.