sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.71k stars 1.94k forks source link

docs: Protected Routes: Best Practice? #7267

Open MentalGear opened 2 years ago

MentalGear commented 2 years ago

Describe the problem

It's a common scenario to have protected routes. It would be great if the docs would outline the best practice for doing this in sveltekit.

Describe the proposed solution

I would think that the hooks.server.js is the best place to check the current path, and act if a user is on a route and (for example) not authenticated.

Alternatives considered

Adding a server.js file per route, but this won't handle any subroutes. Ex: /api/server.js <- redirect request /api/secrets <- still accessible

Importance

would make my life easier

Additional Information

No response

CaptainCodeman commented 2 years ago

I don't think there can ever be any single best-practice as so much will depend on each applications approach to auth. So it would be difficult and maybe misguided to try and make this part of the framework docs.

Is authentication done on the client or the server? Where is the auth state set? Does auth filter what data is displayed or limit access to routes? Do you want to display a permission denied message if not authorized? Do you want to redirect to a sign-in route if not authorized? Do you want to display a sign-in form on the current route if not authorized?

... and so on.

So it's more likely to be a a collection of recipes (and best-practices around things like handling cookies should then apply to those recipes).

MentalGear commented 2 years ago

Hey Simon, thanks for your opinion. Though your questions are legit, I disagree with the assessment that it's too complex / specific to have it in the guide.

A good approach / example is always a simple one to showcase common scenarios, which protected routes definitely is. So the most basic way should be shown as an example, i.e. a simple redirect, like David's method, which should also work client-side.

https://github.com/supabase/auth-helpers/issues/312#issuecomment-1280337849

tcurdt commented 1 year ago

The linked comment says that there "is no a clean way to solve auth for multiple routes currently" which feels a bit 😳 I really feels like this deserves some guidance.

It sure might be a collection of best practises but I agree that it is very much missing from the docs.