Svelte

Make event available to page load() function

#3503

Development PRs

Issue

Solved
J
jp-simons
Jan 22, 2022, 3:56 AM

Describe the problem

One common scenario in SSR rendered apps is that the initial render makes some async API calls, then later on when the user is interacting with the page, calls are made to that same API directly from the browser. For the server initiated API calls, it can simply forward on the end user's auth cookies. This is generally a good pattern as it makes your frontend service a dumb and unprivileged middleman.

Say we have a load function like this in one of our route components:

export async function load({ fetch }) {
    let response = await fetch('https://api.example.com/mylatest', {
      credentials: 'include',
      headers: {
        cookie: 'jwt_token=???',
      },
    });
}

There doesn't seem to be a way to get at the end user's incoming request. This isn't specific to fetch or cookies, more generally we need the full detail of the request to service it properly. Maybe we look at the IP and do something different based on a coarse geolocation. Maybe we look at cookies, not just for forwarded authentication but even just for display preferences. Maybe we look at user-agent and fetch a smaller dataset if it's a phone than if it's a desktop. OK these examples are a bit contrived, it is 99.9% about forward auth.

So I think what SvelteKit wants you to do is use hooks to examine the low-level details of the request and turn it into higher level details that go in locals. So I can use handle() and put stuff in event.locals, but unless I'm missing something, there's no way to get that from load(), you can only get that from a data endpoint.

One workaround that is serviceable is to put whatever you need in session. But then it leaks out to the client (clearly visible with cmd-U show source), when it's actually only needed server-side.

So I'd propose simply plumbing locals through into the load() functions.

Describe the proposed solution

See above.

Alternatives considered

See above. Edit: See below, maybe just update externalFetch?

Importance

would make my life easier

Additional Information

No response

👍 3

Info

Closed at Feb 3, 2022, 3:16 PM
Assignees None
Labels None
Milestone None

Pro tip: You can prefix GitHub URLs of issues, PRs or discussions with svcl.dev/ to view them on this page! Also try it on a GitHub release ;)