ItalyPaleAle / svelte-spa-router

Router for SPAs using Svelte 3
MIT License
1.55k stars 106 forks source link

Redirection from route pre-condition #295

Closed notramo closed 1 year ago

notramo commented 1 year ago

If the user enters any route, but the JWT token is missing, redirect to /login.

ItalyPaleAle commented 1 year ago

Yes this is possible. It depends on how you check if the JWT is present, but you can certainly do a redirect in a route pre-condition. Just use replace()!

notramo commented 1 year ago

@ItalyPaleAle, how to do it without copy-pasting a lot? Currently, all routes have to be wrapped, and the condition have to be specified. If the app only provides logged-in functionality, then it has to be defined for every single route. That's a lot of copy-pasting. It would make more sense to specify conditions for the router, that are applied to every route.

ItalyPaleAle commented 1 year ago

@notramo in this case, where the entire app requires auth, I would put the auth check outside of the Svelte code, in the “main” JS function, before you instantiate the Svelte App.

I’ve done this before many times. One example is here: https://github.com/ItalyPaleAle/calendar-next-demo/blob/master/src/main.js Note this code is VERY OLD so please don’t copy-paste what I did there :) But you can get the gist!

notramo commented 1 year ago

@ItalyPaleAle I'm currently doing this in App.svelte, with onMount(). The problem is that it only works on initial page load, but if the user changes the hash to a valid route after the app is loaded, it is displayed (and a load of errors are thrown, since the token is missing).

ItalyPaleAle commented 1 year ago

If the token is missing, that’s a separate problem. You will want to persist the token somewhere, for example in localStorage.

If the problem is that the token could expire in the meanwhile, yes that’s something that needs to be handled on each request.

The common pattern here is to bake the auth check into the fetch handler you use. If the server responds with 401, then you redirect the user to the auth page. This is not done in the router, but in the code that invokes the remote server. The reason for doing this is that generally apps do not make requests only when a new page is loaded. I don’t know your app, but it’s common for a page to make requests even without trigger a navigation. In this case, handling the check in the code that performs network requests is the way to make sure you’re not missing any situation.