Тёмный

Better Protected Route Redirects 

Huntabyte
Подписаться 24 тыс.
Просмотров 26 тыс.
50% 1

Not all redirections are created equal, let's learn how to improve how we redirect our users when they attempt to access protected resources without being authenticated.
If you find my content useful and want to support the channel, consider contributing a coffee ☕: hbyt.us/coffee
📁 Final Source Code: github.com/huntabyte/better-r...
🚀 Become a channel member: hbyt.us/join
💬 Discord: hbyt.us/discord
🐦 Twitter: hbyt.us/twitter
🖥️ Setup Stuff: hbyt.us/gear
📃 Topics Covered:
- SvelteKit Login
- SvelteKit Form Actions
- SvelteKit Redirects
- SvelteKit Protected Routes
- SvelteKit Load Functions
- SvelteKit Auth Guards

Опубликовано:

 

27 мар 2023

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 103   
@luminox1
@luminox1 Год назад
It's the little things that makes the biggest differences when it comes to user experience.
@Huntabyte
@Huntabyte Год назад
💯. Thanks for the comment my guy!
@ynokenty
@ynokenty Год назад
Good one, thanks for bringing this up! One thing that's missing here is that you would want to urlencode the redirectTo parameter before appending it to your url because any additional search params will get lost if you had 2+ of them on your initial route.
@Khari99
@Khari99 Год назад
Thanks for all the hard work! Its little things like this I never would have thought of for my application that makes things much more polished
@Huntabyte
@Huntabyte Год назад
You're very welcome
@axbe_
@axbe_ Год назад
Very good reminder to use the most basic state management: URL!
@vadimtea
@vadimtea Год назад
Thank you, I was just looking into it the other day. Your implementation seems easy and makes a lot of sense
@Huntabyte
@Huntabyte Год назад
Glad it was helpful!
@Yoggan0
@Yoggan0 Год назад
I liked this video so much that I liked it twice without noticing! Keep it up!
@bjul
@bjul Год назад
Great stuff! Appreciate this format.
@Huntabyte
@Huntabyte Год назад
Thank you! More to come!
@willemdevries9890
@willemdevries9890 Год назад
Great video as always Hunter! Thanks for the tip
@Huntabyte
@Huntabyte Год назад
Thank you and you're very welcome!
@KevinMacKenzie61
@KevinMacKenzie61 Год назад
Perfect timing. Just today I was thinking I need to do this and voila!
@Huntabyte
@Huntabyte Год назад
I read your mind!
@KevinMacKenzie61
@KevinMacKenzie61 Год назад
@@Huntabyte I was thinking that, but then I figured you shot the video yesterday. So you have made skills if you can read my mind before I have even had the thought.
@StarkTech47
@StarkTech47 2 месяца назад
Great video !!! I have noted something with the form, which is when the actions is default, it works great but when the actions is login for instance, the search in the event is changed to the action pass in the form so "?/login".
@estebantrillo3050
@estebantrillo3050 29 дней назад
You can add something like this to the formAction ` ` That would append the redirectTo to the URL without any issues
@asatorftw
@asatorftw Год назад
Great content Hunter! thanks
@Huntabyte
@Huntabyte Год назад
Thanks, and you're welcome!
@mcdba41
@mcdba41 Год назад
Great idea ! Very useful Add in project via hooks const protectedRoute: Handle = async ({ event, resolve }) => { if (event.route.id?.startsWith("/(protected)")) { if (!event.locals.user) { const redirectTo = event.url.pathname + event.url.search; throw redirect(303, `/login?redirectTo=${redirectTo}`); } } return await resolve(event); }; export const handle = sequence(auth, protectedRoute);
@Huntabyte
@Huntabyte Год назад
Very good idea! Only problem is you lose the ability to define specific messages for each redirect if you wanted!
@jazzy4535
@jazzy4535 Год назад
Great video. I'm not sure if this is mentioned in the video but this only works with default action as far as I can tell, because named actions replace the search params. For now I have added redirectTo to the form in a hidden field but an alternative solution is welcome.
@Huntabyte
@Huntabyte Год назад
You should be able to add additional query params to named actions. For example, if you had an action named `createItem`, you could do `?/createItem&redirectTo=whateveryouwant`. I haven't tried this specifically just yet, but I would think that would work.
@jazzy4535
@jazzy4535 Год назад
@@Huntabyte ah, of course. Thank you, will try it out
@yokiano5646
@yokiano5646 Год назад
It's funny how it looks exactly the same like an app I created just now (we both used an untouched pico.css duh...), and I needed to solve that exact aspect that you are talking about, so cheers, nice tips.
@Huntabyte
@Huntabyte Год назад
Thank you!
@XiaZ
@XiaZ 4 месяца назад
6:40 You can skip the `let message: string` declaration because Svelte's reactive statements will inject a let declaration on your behalf if said statement consists entirely of an assignment to an undeclared variable.
@hiryuimajin
@hiryuimajin Год назад
Whenever I am developing I highly consider UX even if it beats the UI haha. Remember the UI designer aint gonna be the one who's going to be looking at the app all day. But it's a bliss when you work with a UI/UX designer, the consideration they put on the designs are tremendously helpful to developers.
@thedelanyo
@thedelanyo Год назад
This is handy. Thanks Sir
@Huntabyte
@Huntabyte Год назад
Glad you think so! You're welcome!
@joshuaruf9807
@joshuaruf9807 9 месяцев назад
Great video as always! Out of curiosity, would the redirect link and message be better suited to a store?
@AndyIsHereBoi
@AndyIsHereBoi Год назад
this should have way more views
@7heMech
@7heMech Год назад
Glad I subscribed.
@Huntabyte
@Huntabyte Год назад
Thank you! I am glad you did as well!
@thienhuynh7962
@thienhuynh7962 Год назад
A bit irrelevant a question but can you explain form validation on client side with use:enhance and server side with form actions (both using zod for validation)? In some tutorials I see people use one of the two validation methods instead of both. But when I ask on stackoverflow it is suggested that I do validation on both server and client. Btw great video, really help me with my project.
@Huntabyte
@Huntabyte Год назад
Yeah! Check my recent video on forms out, that should answer your question! You should ALWAYS at a bare minimum validate on the server, but of course client is a nice UX touch.
@AB-gx5zj
@AB-gx5zj Год назад
Nice explainer!
@Huntabyte
@Huntabyte Год назад
Thanks!
@enumerodev
@enumerodev 6 месяцев назад
Hey, thanks for this great video! Regarding routes; would you know if its possible to create fully dynamic routes using sveltekit? meaning the routes would come from an api and you basically would avoid the folder structure?
@dheerajs2838
@dheerajs2838 Год назад
always impressive content
@Huntabyte
@Huntabyte Год назад
Thanks for taking the time to comment on so many of my videos, I appreciate you!
@RenCode
@RenCode Год назад
🔥 🔥
@bobbradleybell
@bobbradleybell Год назад
Nice. I will do this in my app today hehe. Btw, are you using any special software for zoom in/out effect in your vídeos? I have seen Screen Studio, which is fantastic but only available for MacOs
@Huntabyte
@Huntabyte Год назад
I do all the zooming in post production with premier pro!
@JoyofCodeDev
@JoyofCodeDev Год назад
🔥
@-ion
@-ion Год назад
Shouldn't the query parameters be escaped with encodeURIComponent?
@Mankepanke
@Mankepanke Год назад
Yes
@gorbulevsv
@gorbulevsv Год назад
It's a cool!
@xdega
@xdega 4 месяца назад
The concept is good, but not sure I like the idea of passing a querystring param with something so obvious like "redirectTo"... wondering if it would make more sense to encapsulate this in app state, which would be much harder to inject to. Just a thought. But thanks for sharing.
@levicoderman
@levicoderman 11 месяцев назад
Is it possible to use cookies instead of the url params for redirects?
@Huntabyte
@Huntabyte 11 месяцев назад
Certainly! You’d just have to grab the cookie contents, convert it to JSON, and return it via the page data!
@blucky_yt
@blucky_yt 9 месяцев назад
I feel like the redirect message in the url is a bit too open, cause anyone can construct a link with instructions to go on a different website for malicious purposes and it would just be displayed on the webpage, I feel like that should be passed in a way that could only be sent from the server, like headers
@lasaucissemasquee4421
@lasaucissemasquee4421 Год назад
Thanks for the video. I'm not a huge fan of passing the message as a query param because it would allow anyone to forge what is gonna be displayed on the page itself. Could we do it differently ?
@minnow1337
@minnow1337 11 месяцев назад
I thought the same. Maybe you could write your own custom error hook that allows you to pass additional parameters in the response and persist them through client side routing or localstorage. Or maybe the up and coming view transitions api will help. The easiest and maybe most secure fix though might just be to cryptographically sign the redirect url on the server and append the token to it, then validate that token against the redirect url in the page server load.
@pukarsharma8075
@pukarsharma8075 Год назад
I'm using the same approach but for server message, instead of adding it to search params, I'm using a library: `sveltekit-flash-message`
@Huntabyte
@Huntabyte Год назад
Also a great library made by the creator of superforms :)
@stepskop8670
@stepskop8670 8 месяцев назад
Content from URL passed directly to document? That smells like some juicy XSS
@marcoio8742
@marcoio8742 Год назад
Nice concept and I think it's important to keep in mind. However, I see a flaw with the design. I prefer also to hide particular UI elements when a user is not logged in. This is s simple example of course, but I would say that showing the account link to a non authenticated user id bad design
@Huntabyte
@Huntabyte Год назад
Indeed it is, this design is for demonstration purposes.
@Jay-wx6hv
@Jay-wx6hv Год назад
How exactly would you implement this? If a logged out user can’t see the url they want to go back to … how will they get back to that url?
@omomer3506
@omomer3506 Год назад
So events is a session or local storage? Didnt have a use case yet so didn't reas the docs
@Huntabyte
@Huntabyte Год назад
Event is the RequestEvent. Locals is a custom object set by the `handle` hook that can be access from other server-side functions. I have a video on hooks if you want to learn more.
@omomer3506
@omomer3506 Год назад
@Huntabyte nice thanks alot, all your vidz are informative
@mpiorowski
@mpiorowski Год назад
Amazing help and work :) Great stuff. One suggestion, because Your videos are like a perfect little tutorial / docs, maybe name them a little bit more informative like `Redirect to Protected Route after Auth` ? Later it will be very easy to find what You need :)
@Huntabyte
@Huntabyte Год назад
Thank you!
@matthewpaquette
@matthewpaquette 10 месяцев назад
This video is exactly what I needed. How did you do that??
@matthewpaquette
@matthewpaquette 10 месяцев назад
My form action is overriding my url params. ex. "/login?log_in" Any thoughts on a solution?
@matthewpaquette
@matthewpaquette 10 месяцев назад
my solution was to put the redirectto into the forms action="?/login&{data.fromUrl}"
@maskman4821
@maskman4821 Год назад
This is a valuable lesson, very useful, thank you Hunter, btw can you make a updated Sveltekit + Supabase auth + route guard turorial, Supabase has changed auth api/functions/expressions a lot these days, and also if possible make a chat app with Sveltekit + Supabase realtime, I think people want to have tutorial in this topic 🙏😘🤗🤓😎👍
@Huntabyte
@Huntabyte Год назад
Already in the plans :)
@maulanaiman4448
@maulanaiman4448 Год назад
the github link for the source code is not found..
@Huntabyte
@Huntabyte Год назад
Fixed!
@jmrumble
@jmrumble Год назад
I see a potential bug. Try going to /account?update=true&message=bleh … which message will win? Will the message part of the query string be included on the redirect back to account?
@pmj_studio4065
@pmj_studio4065 Год назад
Yeah I think you would get redirected first to /login?redirectTo=/account?update=true&message=bleh, and then to /account?update=true - to make that work correctly you need to escape redirectTo with encodeURIComponent.
Год назад
Nice, but... what's happens with a named action in login server file ? On my side, search params are "overwrite" by action's name, no ?
@pmj_studio4065
@pmj_studio4065 Год назад
I think in that case you can still put the redirect URL in the search params. Or in a hidden form field if you can't. However, I'm not sure if say POST actions should be automatically replayed after login 🤔
Год назад
@@pmj_studio4065 I succeeded by adding the parameter after the action name in the action attribute, like this: action="?/handleLogin&redirectTo=/toto"
@Huntabyte
@Huntabyte Год назад
Yeah it could be passed as a second param to the `action` if you wanted! I do this quite often.
@stokkmo
@stokkmo Год назад
@@Huntabyte How do I pass this as a second param to the action?
@stokkmo
@stokkmo Год назад
@@Huntabyte Further to my last I did manage to get this working on a named action by getting the search param from the page store and then setting it to the action parameter inside the form enhance function, but not sure if there is a way to do it without using enhance?
@ScriptRaccoon
@ScriptRaccoon Год назад
Very cool tip! This is how a convenient login process looks like. It is cool that it is so easy to implement with SvelteKit. Just a minor nitpick: it is a bit "ugly" that the message is passed as a URL parameter. It would be nice to have this as a page parameter and sent it somehow during the redirect, just so that it is not visible in the URL. Is this possible?
@Huntabyte
@Huntabyte Год назад
Hmm, I know it's possible to send via a request body but with the redirect method I'm not sure exactly how that would work. I will have to explore this a bit further
@raenastra
@raenastra Год назад
Haven't looked into this much, but would it be possible with a store?
@cholasimmons
@cholasimmons Год назад
UX designers don't get enough credit for all the migraines they save humanity from 😎
@Huntabyte
@Huntabyte Год назад
Facts 😂
@chazzwhu
@chazzwhu Год назад
Would you put this in a hook or layout to prevent re-writing for every protected page?
@MagicGamesRayted
@MagicGamesRayted Год назад
5:07
@baixartv
@baixartv Год назад
I've watched your other video about protected routes and I think this way of protecting is not secure? Things have changed?
@Huntabyte
@Huntabyte Год назад
This is in a +page.server not a +layout.server, therefore it is secure 👍
@stefandevo
@stefandevo Год назад
@@Huntabyte would mean you have to check this in every page then? Hooks the best place to check, no?
@jean_luc_retard
@jean_luc_retard 9 месяцев назад
This doesn't work with named actions
@jean_luc_retard
@jean_luc_retard 9 месяцев назад
Solution: Assuming your named action is ?/login Login
@mohabedr5030
@mohabedr5030 Месяц назад
clickbait title, we all know this information.
@Thomas-pg1xi
@Thomas-pg1xi Год назад
I have a suggestion to make the message url safe use: `/login?redirectTo=${fromUrl}&message=${encodeURIComponent(message)}`
@SebastianSastre
@SebastianSastre Год назад
But why using the load at all? Why wouldn't be better to do it in a hooks.server.ts handler?
@Huntabyte
@Huntabyte Год назад
I hate to say it, but it depends. They both accomplish the same thing, this is just a simpler way to add granular control on a per-route basis. For example, on form actions for unauthenticate users I don't want to throw a redirect, I'd want to return an error. There are ways to accomplish this by accessing the request method via the hooks though if you prefer that.
Далее
Pagination with SvelteKit
9:33
Просмотров 18 тыс.
Protect SvelteKit Routes with Hooks
21:10
Просмотров 55 тыс.
вернуть Врискаса 📗 | WICSUR #shorts
00:54
БИМ БАМ БУМ💥
00:14
Просмотров 4 млн
Svelte 5's Secret Weapon: Classes + Context
18:14
Просмотров 14 тыс.
The Anti Component Library
10:35
Просмотров 46 тыс.
Auth Does NOT Have To Be Hard
17:13
Просмотров 97 тыс.
Why Your Load Functions are Slow
8:24
Просмотров 20 тыс.
The Svelte 5 Guide: Runes And Universal Reactivity
21:41
Practical Svelte 5 - Shopping Cart
25:10
Просмотров 12 тыс.
Svelte makes Drag And Drop API easy!
15:08
Просмотров 19 тыс.
Oh, Auth Doesn't Have to Suck?
7:16
Просмотров 57 тыс.
вернуть Врискаса 📗 | WICSUR #shorts
00:54