Let me generalize that problem.
We should implement session state synchronization between client and backend.
What the best way to do that? It's a difficult question. It depends.
For example, if you try to protect something valuable when the remote users just try to access restricted areas it's pretty simple. Just redirect to sign in/signup page. But what if the one remote user logout and the second user try to log in at the same application at the same browser before reloading from backend? We quickly jump to the logic trap. So how to correctly manipulate with DOM tree accordingly to the remote session state?
Probably the best way to do that, just control transitions between routes.
In sapper, you should do that by exporting the preload function for every module.
So instead place logic into _layout.svelte (so easy but not sapper way in my opinion). We should create a general module route-guards.js
as an example.
Then we should import it into every module.
The rest of an answer:
// route-guards.js
export async function transitionControl(self, page, session) {
const result = await self.fetch('/is-logged-in'); // self for support server side rendering
const response = await result.json();
if (!response && page.path !== '/login') {
return self.redirect(302, '/login');
}
}
<!-- any module.svelte -->
<script context="module">
import { transitionControl } from "./route-guards";
export async function preload(page, session) {
await transitionControl(this, page, session);
// Do another what you want before page load
}
</script>
Please keep in mind that the sync states between two things never be easy as you want. OMG web development so difficult. Thanks, everyone for pay attention.