I am trying to modify my fetch request for external API to include a custom header. After trying multiple things, I saw externalFetch in the documentation which seems to serve the purpose of modifying the request but the problem is it never gets called. What am I missing?
export async function externalFetch(request) {
request.headers['authorization'] = 'HMAC 12.33';
console.log('hook headers', request);
request = new Request(
request
);
return fetch(request);
}
You have to use the fetch function that sveltekit provices you through the load function in order for the externalFetch to trigger, here is an example from the sveltekit documentation:
<!-- src/routes/blog/[slug].svelte -->
<script context="module">
/** @type {import('@sveltejs/kit').Load} */
export async function load({ params, fetch, session, stuff }) {
const response = await fetch(`https://cms.example.com/article/${params.slug}.json`);
return {
status: response.status,
props: {
article: response.ok && (await response.json())
}
};
}
</script>