Next.js Authentication - Avoid these 4 mistakes (Don't do auth in layout!)

  Рет қаралды 49,675

ByteGrad

ByteGrad

Күн бұрын

Пікірлер: 87
@ByteGrad
@ByteGrad 6 ай бұрын
Hi, my latest course is out now (Professional React & Next.js): bytegrad.com/courses/professional-react-nextjs -- I'm very proud of this course, my best work! I'm also a brand ambassador for Kinde (paid sponsorship). Check out Kinde for authentication and more bit.ly/3QOe1Bh
@digitalapplied
@digitalapplied 7 ай бұрын
This is the first resource that's made next.js authentication clear.
@jennifers.6396
@jennifers.6396 3 ай бұрын
I was grumbling for the first few chapters here because I could not use middleware with my database adapter. But you explained that as well. Very complete video. Love that you explain what happens and don't just show what one has to do. Thanks!
@jairseedorf
@jairseedorf 7 ай бұрын
I actually found layout auth to work better than middleware if your api already has built in auth. Middleware slows down navigation by alot and makes the user experience worst. So if it's a dashboard app just do auth on the layout with force-dynamic. if its an app that needs to authorize itself, middleware can be used.
@syz3981
@syz3981 Ай бұрын
i dont understand not doing auth in the layout? if you land on any route and it runs you should get redirected, you dont even have the chance to navigate to another route?
@dokkenrox
@dokkenrox 2 ай бұрын
If you can't make a request to a database in your middleware because of the edge runtime, one solution is to create a route handler that makes the database request instead. You can then make a request to that route handler inside your middleware. Route handlers can run on the nodejs runtime so it should work for your database client. One caveat is that you must use fetch to make the http request inside your middleware since http clients like Axios also don't work on the edge runtime. This solution adds some complexity and maybe a little latency but it's the only thing I've found that works so far.
@RishikeshDasappa
@RishikeshDasappa 7 ай бұрын
Loving this new content. Making videos on what not to do is REALLY helpful in building good coding practices. Keep it up!
@Herxh428
@Herxh428 7 ай бұрын
Bytegrad brother i am so lucky to find out about your next js course it is #1 resource on nextjs and the coding standard you follow is top notch along with your teaching style . Anyone willing to take his course don't hesitate even a bit its The best next js course you will find in internet ❤️❤️
@ByteGrad
@ByteGrad 7 ай бұрын
Thanks, appreciate it!
@ransomecode
@ransomecode 4 ай бұрын
Middlewares only work in edge environments, but I don't want to host my site on edge because it only contains region specific content. What are my options then? Templates?
@daytatech-youtube
@daytatech-youtube 3 ай бұрын
i wondered this too, if you are self hosting, is the database still unaccessable?
@ngaji_it
@ngaji_it 2 ай бұрын
​@@daytatech-youtube you can use server action or server component
@dokkenrox
@dokkenrox 2 ай бұрын
You can use a route handler. See my comment about it above.
@jake5335
@jake5335 Ай бұрын
Great video, most helpful I've seen so far. Thanks man
@r3nd593
@r3nd593 7 ай бұрын
navigation using next Link with prefetch set to true which is the default setup doesn't run the middleware on every navigation, prefetch is not available in development and you don't see it not work but when you deploy your app to production issues will appear
@krizh289
@krizh289 2 ай бұрын
Actually learned useful information...worth watching
@kashmirtechtv2948
@kashmirtechtv2948 7 ай бұрын
need more such videos of next concepts ..have completely watched your fullstack next tutorial
@kashmirtechtv2948
@kashmirtechtv2948 7 ай бұрын
the best channel to learn the concepts and avoid mistakes that we really face in the real world codebases ❤❤
@tarikogic9313
@tarikogic9313 7 ай бұрын
I had a problem with checking session in a server action using next-auth. It was because next-auth used cookies. It was the story about static and dynamic stuff you just explained. Everything was fine in development, but the production failed. So I removed it from server actions. Do you know how to solve this?
@josecentenodev
@josecentenodev 5 ай бұрын
Hi ByteGrad, This is the perfect video I needed! It contains the answers to all the questions I was facing. Thank you so much!
@alexnelson2119
@alexnelson2119 7 ай бұрын
Would a third option be to put your session check into a template.ts file? Works similarly to layout.ts but every time you navigate to a new route, a new instance of the component is mounted. Full disclosure, I haven’t tried it so I’m not actually sure if it works. 😅
@ByteGrad
@ByteGrad 7 ай бұрын
Yeah could be, but it’s still a bit too obscure for me to definitely recommend
@GameKornel
@GameKornel 7 ай бұрын
We are doing it in our app and it works flawlessly! We just have (authenticatedRoutes) group route in Next and put Tempalte.ts file in there! :)
@bibblebabl
@bibblebabl 7 ай бұрын
Middleware is great if you just want to check if there is any auth data at all. But what about roles? How do we check them in middleware?
@TechDiffuse
@TechDiffuse 7 ай бұрын
I make my Auth with firebase and once it's authenticated I store my own user from the database in a cookie. There is the role encoded which I can get in the middleware
@codewithegai
@codewithegai 2 ай бұрын
He has a video on RBAC
@jeremyptlt
@jeremyptlt 7 ай бұрын
Excellent video, going into the details of things as always!
@eddiejaoude
@eddiejaoude 7 ай бұрын
Great video! Thank you for the examples and different use cases
@learner8084
@learner8084 7 ай бұрын
He is so good that while I'm watching the video, I will automatically remember to click like... because the video is so good.
@codewithegai
@codewithegai 2 ай бұрын
Same here
@anmaxin325
@anmaxin325 18 күн бұрын
learnt a lot! thanks!
@harshdasila6680
@harshdasila6680 7 ай бұрын
Hey you were telling that we are exposing a API endpoint in case of server actions. Then why can't we hit the api (server action) using something like postman? I think we just need to protect the frontend were the server action is used!!
@ByteGrad
@ByteGrad 7 ай бұрын
Because Next.js has some additional protection in place. But still a best practice to add auth to them imo, also because you could accidentally use them on a public route (i.e. a route not covered by middleware or page auth check)
@harshdasila6680
@harshdasila6680 7 ай бұрын
@@ByteGrad can you make a video on this and how to authenticate them using cookies? Or other that kinde auth
@gerkim62
@gerkim62 7 ай бұрын
This guy is a genius
@윤지만-w4m
@윤지만-w4m 6 ай бұрын
Here, some people suggest layout or template, but currently next.js does not work properly in parallel routes. And is it correct to determine whether the user is logged in after entering a secure page? Since the secure page is already using the secure API, 401 and 403 will occur in that API. I think it is right to block users before they access the page.
@JuanJuan-sq7hu
@JuanJuan-sq7hu 7 ай бұрын
Thank you for making these beginner videos!
@shimi6165
@shimi6165 7 ай бұрын
we can use middleware for the first fence and how about using auth HOC for reusable components as second fence ?
@joepetrillo6185
@joepetrillo6185 7 ай бұрын
THIS IS EXACTLY THE VIDEO I NEEDED
@DickyFirmansyah-u9o
@DickyFirmansyah-u9o 5 ай бұрын
so i have setup my middleware and redirect to login page if its not logged in and after login i setup an encodedOriginUrl to go back to that requested page, but can i check if theres a page exist or not in my apps inside middleware? so the user should not go to login page and after login they found that the page is not found, so i just want the user just directly redirect to not found page and not login page if the page doesnt exist in my apps
@kevinluna5786
@kevinluna5786 7 ай бұрын
I use Layout because in all the pages that we create there is like a 95% chances that we'll use an API that is already verifyng the authentification. But it's a nice idea to use middleware, I'll try it in my next project!
@hungify
@hungify 7 ай бұрын
I have a question regarding the using in Layout. Does it cause the entire page to be statically rendered?
@ByteGrad
@ByteGrad 7 ай бұрын
It will make the whole app dynamically rendered, in addition to not properly protecting the pages
@imkir4n
@imkir4n 7 ай бұрын
8:00 HOC will save the duplication right?
@ByteGrad
@ByteGrad 7 ай бұрын
Yes, but realistically you will also have more fine-grained access control (e.g. based on admin role), so it becomes messy that way with HOC’s or utility functions imo. But for a simple app that’s fine I think
@vishalmewada5817
@vishalmewada5817 7 ай бұрын
I have a doubt , does middleware .ts file work in a static build , because this logic work on server side and when we make a build everything on the client side ? I would be very happy if someone would answer on this , because my middleware.ts file is not working on static build and I want to know how it can work .
@DiiiaZoTe
@DiiiaZoTe 7 ай бұрын
One thing that needs to be mentioned is that the middleware uses the edge runtime. So unless you use a database that is edge compatible, you will not be able to use database sessions for your auth and will need to rely on JWTs. So if you use database sessions, page is probably a better option in my opinion.
@Ismail-hd4yz
@Ismail-hd4yz 7 ай бұрын
What if i am using Nodemailer Provider. Middleware does not work there
@joepetrillo6185
@joepetrillo6185 7 ай бұрын
How does caching work when doing the check on the page level? Every time the component is on the page, will the auth check be run?
@ByteGrad
@ByteGrad 7 ай бұрын
Dynamic rendering means there won’t be server-side caching, but client-side cache may still work
@joepetrillo6185
@joepetrillo6185 7 ай бұрын
@@ByteGrad so this is ok to have on the client side because we can assume they are still authenticated until some logout event or jwt cookie is destroyed right? When that happens I assume kinde clears out the client side cache using revalidatePath or something?
@art8419
@art8419 7 ай бұрын
In my middleware im returning a NextResponse.next request with some custom headers that I utilize in my pages, where should I put kinde's return withAuth(request)?
@sdsim1
@sdsim1 6 ай бұрын
Awesome work! 👏👏
@GameKornel
@GameKornel 7 ай бұрын
Remember about Next's Template file! It's common to do something like (authenticatedRoutes) routing in Next and instead of checking and remembering about every file/route that needs to be authenticated - you can use Template instead of Layout which will run every time!
@rokonzamann
@rokonzamann 7 ай бұрын
Exactly. You can group easily with templates.
@윤지만-w4m
@윤지만-w4m 6 ай бұрын
This is generally true, but problems may occur if parallel routes are used. (bug)
@vinoobharadwaj
@vinoobharadwaj 7 ай бұрын
What theme are you using for VS Code?
@bellasvideo5620
@bellasvideo5620 7 ай бұрын
@@OpenDeepLearning INDMKB
@luisllaboj
@luisllaboj 7 ай бұрын
I would say is Atom dark pro or one dark pro but a Darker version. Honestly I forget the exact names but u can maybe find them looking by those names lol hope he can confirm or correct me anyway ;)
@usinakenes
@usinakenes 7 ай бұрын
Mine seems to be the same as his: "One Dark Pro Monokai Darker".
@vinoobharadwaj
@vinoobharadwaj 7 ай бұрын
@@usinakenes thanks, that seems to be the one!
@luisllaboj
@luisllaboj 7 ай бұрын
Do you know if Clerk makes the whole app dynamic by using a wrapper in the main layout even if I don’t explicitly use the utility functions that retrieve the session? Like const {…} = await auth()
@frontend_ko
@frontend_ko 7 ай бұрын
middleware has caching. how can i validate every new request?
@bgarcesch
@bgarcesch 7 ай бұрын
Middleware does not support NodeJS, only edge. No session auth with db there.
@hm.till97
@hm.till97 7 ай бұрын
So if I want to display simple login / logout buttons across my blog in the upper corner of the screen using layout my entire app will just be dynamically rendered?
@ByteGrad
@ByteGrad 7 ай бұрын
Not if you use a client-side way of checking if the user is authenticated (e.g. the Kinde hook I showed - useKindeBrowserClient gives you access to the user)
@waltervanwoudenberg6876
@waltervanwoudenberg6876 7 ай бұрын
@@ByteGradhow would you do that without an auth library if you follow the nextjs docs they always use cookies in their examples which forces dynamic rendering
@ItsAvyy
@ItsAvyy 7 ай бұрын
@@waltervanwoudenberg6876 At that point you're reading the cookies on the client in normal JavaScript so you don't have to worry about the server at all.
@cangorkemgunes
@cangorkemgunes 7 ай бұрын
Hi, do you have a chance to make a video about Authjs v5? I would like to learn from you.
@joshlloyd9698
@joshlloyd9698 6 ай бұрын
Thanks for this, great video
@MadRad1000
@MadRad1000 4 ай бұрын
Excellent - thank you
@twenty9str498
@twenty9str498 7 ай бұрын
what about authorization??? doing it in layout is the only way.
@joaoarthurbandeira
@joaoarthurbandeira 7 ай бұрын
Hey, curious, what would be the difference between both and why would it be the only way? Just trying to learn hahah
@mDHARYL
@mDHARYL 7 ай бұрын
​@@joaoarthurbandeira I think we can u session hook at client.
@joshuadeguzman2911
@joshuadeguzman2911 7 ай бұрын
What do you mean? You can redirect in middleware, though.
@joshuadeguzman2911
@joshuadeguzman2911 7 ай бұрын
​@joaoarthurbandeira doing authentication is like you are appraising whether the user/item is legit/registered or not. Authorization is simply validating whether the user or guest is validated to enter in this room/route.
@simonedwards7101
@simonedwards7101 6 ай бұрын
​​@@joshuadeguzman2911a better analogy would be authentication lets you in the building. Authorisation lets you know what you can do once you're in, use the stairs or use the lift, allowed on floors 1 and 2 or 1,2,3,4,5.
@rhkina
@rhkina 7 ай бұрын
Great tutorial!!! Thank you so much! 🙏
@ossama90s47
@ossama90s47 7 ай бұрын
Hey brand! Considering the complexity of the Next.js middleware issue in production with Docker, I think it would be incredibly valuable if you could create a video tutorial or walkthrough addressing this specific challenge and issues of middleware with docker .
@404-not-found-service
@404-not-found-service 7 ай бұрын
thanks your video
@ransomecode
@ransomecode 4 ай бұрын
I do auth in next.config.mjs, in the redirect() function 💀
@didarnawzad
@didarnawzad 7 ай бұрын
U are the best ❤
@sifact1391
@sifact1391 7 ай бұрын
Good job
@petrtcoi9398
@petrtcoi9398 7 ай бұрын
Great🎉
@LavanieMitchell
@LavanieMitchell 7 ай бұрын
your very smart
Authentication Flow in Next.js (Complete Tutorial)
30:37
Cosden Solutions
Рет қаралды 31 М.
My scorpion was taken away from me 😢
00:55
TyphoonFast 5
Рет қаралды 2,7 МЛН
Support each other🤝
00:31
ISSEI / いっせい
Рет қаралды 81 МЛН
Why I don't use React-Query and tRPC in Next.js
18:58
ByteGrad
Рет қаралды 100 М.
Multi-Tenant SaaS Architecture (Next.js Auth)
22:57
ByteGrad
Рет қаралды 30 М.
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 296 М.
The Secret Language Scaling WhatsApp and Discord
28:32
Theo - t3․gg
Рет қаралды 178 М.
My scorpion was taken away from me 😢
00:55
TyphoonFast 5
Рет қаралды 2,7 МЛН