I'm trying to do API calls in a SvelteKit page from the load function, but I don't want to proxy these calls with local endpoints because I want to keep the web server as light as possible.
What I want to do specifically is, when the call is made from the server, the API's URL should be different than when it's called from the client (e.g. "http://localhost:1234" vs. "https://example.com:1234", respectively).
But, more generally than this, is there a way to differentiate whether the current code is running on the server vs. the client?
SvelteKit is an opinionated full stack framework that ties the frontend and backend together delivering the best developer and user experience.
On the contrary, Sveltekit is a framework for building svelte apps of all sizes; it enables you to build more significant apps with a smaller footprint. It comes with a beautiful development experience, flexible filesystem-based routing, Server-Side Rendering(SSR), client-side hydration, and some other unique features.
Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.
Within the load
function there is the option to use the browser
flag after it's imported from $app/env
.
<script context="module">
import { browser } from '$app/env';
...
export async function load({ fetch }) {
if (!browser) {
// code here runs only on the server
}
return {
...
}
}
...
<script>
Following comes from SvelteKit's docs:
browser is true or false depending on whether the app is running in the browser or on the server
Disclaimer: what I'm writing is not the real answer to the title, but it is the specific answer to the described problem.
There's a targeted hook function (externalFetch
) that's build to address resources differently if client or server:
https://kit.svelte.dev/docs/hooks#externalfetch
/** @type {import('@sveltejs/kit').ExternalFetch} */
export async function externalFetch(request) {
if (request.url.startsWith('https://api.yourapp.com/')) {
// clone the original request, but change the URL
request = new Request(
request.url.replace('https://api.yourapp.com/', 'http://localhost:9999/'),
request
);
}
return fetch(request);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With