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

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 มิ.ย. 2024
  • Add auth to your Next.js app quickly: bit.ly/3QOe1Bh (paid sponsorship).
    NEW - React & Next.js Course: bytegrad.com/courses/professi...
    Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
    👉 Check out Kinde for auth and more bit.ly/3QOe1Bh
    👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
    👉 Professional JavaScript Course: bytegrad.com/courses/professi...
    👉 Professional CSS Course: bytegrad.com/courses/professi...
    👉 Web development roadmap 2024 & 2025: email.bytegrad.com
    👉 Email newsletter (BIG update soon): email.bytegrad.com
    👉 Discord: all my courses have a private Discord where I actively participate
    👉 Kinde: check out Kinde for auth and more bit.ly/3QOe1Bh
    ⏱️ Timestamps:
    00:00 Intro
    01:00 Add auth quickly
    03:15 Don't do auth in layout
    05:50 Page vs Middleware for auth
    08:01 Middleware benefit 1: better structure
    09:01 Middleware benefit 2: static rendering
    13:19 BIG RISK: Showing user info app-wide (e.g. header)
    15:40 Middleware benefit 3: better performance
    18:16 IMPORTANT: Auth check in Middleware or Page is not enough!
    21:27 Auth for server actions
    25:17 Summary: robust authentication in Next.js
    #webdevelopment #reactjs #nextjs

ความคิดเห็น • 67

  • @ByteGrad
    @ByteGrad  4 วันที่ผ่านมา +2

    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 19 วันที่ผ่านมา +5

    This is the first resource that's made next.js authentication clear.

  • @GameKornel
    @GameKornel 7 วันที่ผ่านมา +1

    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!

    • @r0mankon
      @r0mankon 6 วันที่ผ่านมา

      Exactly. You can group easily with templates.

  • @RishikeshDasappa
    @RishikeshDasappa 18 วันที่ผ่านมา +2

    Loving this new content. Making videos on what not to do is REALLY helpful in building good coding practices. Keep it up!

  • @JuanJuan-sq7hu
    @JuanJuan-sq7hu 20 วันที่ผ่านมา +3

    Thank you for making these beginner videos!

  • @jairseedorf
    @jairseedorf 19 วันที่ผ่านมา +2

    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.

  • @kashmirtechtv2948
    @kashmirtechtv2948 6 วันที่ผ่านมา +1

    need more such videos of next concepts ..have completely watched your fullstack next tutorial

  • @kashmirtechtv2948
    @kashmirtechtv2948 6 วันที่ผ่านมา

    the best channel to learn the concepts and avoid mistakes that we really face in the real world codebases ❤❤

  • @Herxh428
    @Herxh428 16 วันที่ผ่านมา +1

    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  16 วันที่ผ่านมา

      Thanks, appreciate it!

  • @jeremyptlt
    @jeremyptlt 7 วันที่ผ่านมา +2

    Excellent video, going into the details of things as always!

  • @eddiejaoude
    @eddiejaoude 11 วันที่ผ่านมา +1

    Great video! Thank you for the examples and different use cases

  • @rhkina
    @rhkina 19 วันที่ผ่านมา +1

    Great tutorial!!! Thank you so much! 🙏

  • @luisllaboj
    @luisllaboj 20 วันที่ผ่านมา

    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()

  • @learner8084
    @learner8084 19 วันที่ผ่านมา +2

    He is so good that while I'm watching the video, I will automatically remember to click like... because the video is so good.

  • @shimi6165
    @shimi6165 13 วันที่ผ่านมา

    we can use middleware for the first fence and how about using auth HOC for reusable components as second fence ?

  • @tarikogic9313
    @tarikogic9313 19 วันที่ผ่านมา +2

    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?

  • @joepetrillo6185
    @joepetrillo6185 19 วันที่ผ่านมา +2

    THIS IS EXACTLY THE VIDEO I NEEDED

  • @art8419
    @art8419 19 วันที่ผ่านมา

    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)?

  • @gerkim3046
    @gerkim3046 20 วันที่ผ่านมา +3

    This guy is a genius

  • @vishalmewada5817
    @vishalmewada5817 12 วันที่ผ่านมา

    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 .

  • @r3nd593
    @r3nd593 16 วันที่ผ่านมา

    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

  • @twenty9str498
    @twenty9str498 19 วันที่ผ่านมา +7

    what about authorization??? doing it in layout is the only way.

    • @joaoarthurbandeira
      @joaoarthurbandeira 15 วันที่ผ่านมา

      Hey, curious, what would be the difference between both and why would it be the only way? Just trying to learn hahah

    • @mDHARYL
      @mDHARYL 13 วันที่ผ่านมา

      ​@@joaoarthurbandeira I think we can u session hook at client.

    • @joshuadeguzman2911
      @joshuadeguzman2911 12 วันที่ผ่านมา

      What do you mean? You can redirect in middleware, though.

    • @joshuadeguzman2911
      @joshuadeguzman2911 12 วันที่ผ่านมา

      ​@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.

  • @cangorkemgunes
    @cangorkemgunes 20 วันที่ผ่านมา

    Hi, do you have a chance to make a video about Authjs v5? I would like to learn from you.

  • @Ismail-hd4yz
    @Ismail-hd4yz 19 วันที่ผ่านมา

    What if i am using Nodemailer Provider. Middleware does not work there

  • @juviess
    @juviess 18 วันที่ผ่านมา +1

    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 12 วันที่ผ่านมา

      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

  • @ossama90s47
    @ossama90s47 20 วันที่ผ่านมา +1

    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 .

  • @harshdasila6680
    @harshdasila6680 20 วันที่ผ่านมา +1

    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  20 วันที่ผ่านมา

      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 20 วันที่ผ่านมา

      @@ByteGrad can you make a video on this and how to authenticate them using cookies? Or other that kinde auth

  • @404-not-found-service
    @404-not-found-service 15 วันที่ผ่านมา +1

    thanks your video

  • @kevinluna5786
    @kevinluna5786 20 วันที่ผ่านมา +1

    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 20 วันที่ผ่านมา

      I have a question regarding the using in Layout. Does it cause the entire page to be statically rendered?

    • @ByteGrad
      @ByteGrad  20 วันที่ผ่านมา

      It will make the whole app dynamically rendered, in addition to not properly protecting the pages

  • @joepetrillo6185
    @joepetrillo6185 19 วันที่ผ่านมา

    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  19 วันที่ผ่านมา

      Dynamic rendering means there won’t be server-side caching, but client-side cache may still work

    • @joepetrillo6185
      @joepetrillo6185 19 วันที่ผ่านมา

      @@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?

  • @frontend_ko
    @frontend_ko 20 วันที่ผ่านมา

    middleware has caching. how can i validate every new request?

  • @imkir4n
    @imkir4n 20 วันที่ผ่านมา +1

    8:00 HOC will save the duplication right?

    • @ByteGrad
      @ByteGrad  20 วันที่ผ่านมา +1

      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

  • @sifact1391
    @sifact1391 11 วันที่ผ่านมา

    Good job

  • @trxsson
    @trxsson 20 วันที่ผ่านมา

    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  19 วันที่ผ่านมา

      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 17 วันที่ผ่านมา

      @@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 12 วันที่ผ่านมา

      @@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.

  • @alexnelson2119
    @alexnelson2119 19 วันที่ผ่านมา +1

    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  19 วันที่ผ่านมา +1

      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! :)

  • @DiiiaZoTe
    @DiiiaZoTe 19 วันที่ผ่านมา +2

    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.

  • @bgarcesch
    @bgarcesch 16 วันที่ผ่านมา

    Middleware does not support NodeJS, only edge. No session auth with db there.

  • @vinoopb
    @vinoopb 20 วันที่ผ่านมา +1

    What theme are you using for VS Code?

    • @OpenDeepLearning
      @OpenDeepLearning 20 วันที่ผ่านมา

      Interested also

    • @bellasvideo5620
      @bellasvideo5620 20 วันที่ผ่านมา

      @@OpenDeepLearning INDMKB

    • @luisllaboj
      @luisllaboj 20 วันที่ผ่านมา +1

      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 20 วันที่ผ่านมา

      Mine seems to be the same as his: "One Dark Pro Monokai Darker".

    • @vinoopb
      @vinoopb 20 วันที่ผ่านมา +1

      @@usinakenes thanks, that seems to be the one!

  • @didarnawzad
    @didarnawzad 12 วันที่ผ่านมา

    U are the best ❤

  • @petrtcoi9398
    @petrtcoi9398 19 วันที่ผ่านมา +1

    Great🎉

  • @user-ef5cl4rq3w
    @user-ef5cl4rq3w 13 วันที่ผ่านมา

    your very smart