sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.53k stars 4.12k forks source link

Can't access local storage, session storage or cookies in load function #9942

Open s1nistr4 opened 9 months ago

s1nistr4 commented 9 months ago

Describe the bug

I have a project made in Svelte with sveltekit and adapter-static. There is a login jwt stored as a Cookie, I would like to change parts of the page if the token is present and valid.

Afaik there is no way to do this and if there is it's not documented.

Document.cookie js not accessible in +page.js in a load function nor is localstorage or sessionstorage so you have to do it in onMount, but the issue with that is there's a noticible delay from where it switches out the element

Reproduction

.

Logs

No response

System Info

Debian 13
Node 20.2.0
Memory 6GB

Severity

blocking all usage of svelte

adiguba commented 9 months ago

Hello,

You can use document.cookie, window.localStorage, window.sessionStore or any client-side info on +page.js load(), but you have to do this in an if (browser) since the function is also executed on the server (or during prerendering in the case of adapter-static).

But you will have a delay, as your HTML is prerendered and cannot be served with the correct data.

To avoid this "delay", you must go through SSR, and process the cookie in +page.server.js

s1nistr4 commented 9 months ago

Hello,

You can use document.cookie, window.localStorage, window.sessionStore or any client-side info on +page.js load(), but you have to do this in an if (browser) since the function is also executed on the server (or during prerendering in the case of adapter-static).

But you will have a delay, as your HTML is prerendered and cannot be served with the correct data.

To avoid this "delay", you must go through SSR, and process the cookie in +page.server.js

There's no way to do this then? This is pretty easy in React and us essential for making any SPA web app

Having a page delay in general is unavoidable for authenticating, the issue is that is displays the old element, unrenders it and ahows the new authenticated element.

adiguba commented 9 months ago

I think it's the same in React : you cannot prerender statically a page that requires authentication.

Or React does not prerender the page, but build it only on client-side after auths was verified.

So just add this to your +page.js do disable prerender :

// Disable prerendering the page 
export const prerender = false;
// Disable SSR (for Dev mode in your case)
export const ssr = false; //