Next-Auth Login Authentication Tutorial with Next.js App Directory

Поділитися
Вставка
  • Опубліковано 1 сер 2024
  • Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
    In this Next-Auth login authentication tutorial with Next.js app directory, you will learn how to protect all of your pages with credentials or an OAuth login from providers like GitHub. Learn how to protect any page in your app.
    *Get CodiumAI for FREE:* marketplace.visualstudio.com/... or visit: www.codium.ai/
    💖 Support me on Patreon ➜ / davegray
    ⭐ Become a full-stack web dev with Zero To Mastery Courses:
    - Complete Next.js Developer: bit.ly/CompNextJSDev
    - Advanced React: bit.ly/AdvReactDev
    - Junior to Senior Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
    🚩 Subscribe ➜ bit.ly/3nGHmNn
    📬 Course Updates ➜ courses.davegray.codes/
    ❓ Questions - Please post them to my Discord ➜ / discord
    ☕ Buy Me A Coffee ➜ www.buymeacoffee.com/davegray
    👇 Follow Me On Social Media:
    Github: github.com/gitdagray
    Twitter: / yesdavidgray
    LinkedIn: / davidagray
    🔗 Source Code: github.com/gitdagray/next-aut...
    Next-Auth Login Authentication Tutorial with Next.js App Directory
    (00:00) Intro
    (00:05) Welcome
    (00:28) CodiumAI
    (01:39) Create Next.js Project & Dependencies
    (02:21) NextAuth.js Introduction
    (04:20) Auth Route Handler
    (05:49) NextAuth options
    (10:13) NEXTAUTH_SECRET
    (11:52) Setting up GitHub OAuth
    (16:09) Configuring Providers in options
    (23:08) Send a GET request to /api/auth/providers
    (25:06) App Behavior for 3 different server pages
    (26:27) Apply NextAuth with Middleware
    (29:10) 3 Different Protection Approaches
    (31:14) NextAuth with Client Components
    (37:35) Next.js Images from an OAuth Provider
    (39:26) Wrap-up
    📚 Tutorial References:
    🔗 NextAuth.js Official Site: next-auth.js.org/
    🔗 Next.js Official Site: nextjs.org/
    🔗 ES7 React Snippets Extension: marketplace.visualstudio.com/...
    Was this Next-Auth tutorial using the Next.js 13 App Directory helpful? If so, please share. Let me know your thoughts in the comments.
    #nextjs #next #auth

КОМЕНТАРІ • 315

  • @alessandrosalzo8280
    @alessandrosalzo8280 Місяць тому +3

    For those having problems with the App Router and middleware, I moved the middleware file inside the app folder, and worked

  • @GuiKT88
    @GuiKT88 6 місяців тому +2

    Hallelujah, thanks to let the people know what dependencies and versions you are using it, it helps so much man!

  • @hamzahahmad1670
    @hamzahahmad1670 11 місяців тому +25

    It's a bit late to comment, but congratulations Dave on getting sponsors for your videos (this is the first one I've come across)
    There are plenty of amazing tutorial creators on UA-cam, but the amount of effort you put in your videos to explain each and every line of code, right down to mentioning the key binds you use, is just remarkable. Thank you for all your effort and I hope you gain even more success

  • @vishwanathsinha
    @vishwanathsinha 11 місяців тому +1

    Thank you Dave. This was very helpful. You made things crystal clear to understand and implement the next-auth with next 13.2 + version. Also when to use server and client component. Overall you made it very simple.

  • @alexanderhenting
    @alexanderhenting 8 місяців тому +2

    Hey Dave, after migrating from the pages router this tut helped me a lot on getting clear. There are a lot of tutorials out there and huge codebases with complex integrations and a lot of copy paste code, sometimes a bit hard to stay focused on the essentials.
    Greeting from Austria

  • @andrewahlstrom8359
    @andrewahlstrom8359 2 місяці тому

    Thank you Dave. I was having so much trouble trying to figure out how this was supposed to work. But after watching your video, the pattern became stupid simple. subscribed and looking forward to your content.

  • @Leesdjo
    @Leesdjo Рік тому +9

    Thank you Dave. You have the heart to teach and help people who are trying their best to learn how to code .

  • @Selimdede-jr2bv
    @Selimdede-jr2bv Рік тому +1

    Hey dave when i started this job i used to watch your videos now i got my first job as a developer thanks man!

  • @jior6
    @jior6 11 місяців тому +1

    You make the best tutorials man, seriously thank you so much.

  • @nademkhan931
    @nademkhan931 11 місяців тому

    A very nice nuanced explanaton of Next-Auth. Yes please, I would like to see follow on tutorials on role-based access as you mention at the end

  • @zilvinas5130
    @zilvinas5130 6 місяців тому

    Damn, this tutorial is god tier comparing to other ones I found that tackle this topic. Detail all in the right places!

  • @Evil_E_ye
    @Evil_E_ye Рік тому

    I was making my website today and you uploaded this today saved many hours of work❤❤

  • @judevector
    @judevector 10 місяців тому

    This is a very packed information and I really understand every bit of it ,I was in another tutorial before the guy was explaining it but it was very hard to get . Immediately I came here it just clicked ❤

  • @adimardev1550
    @adimardev1550 10 місяців тому

    i love your voice Dave. keep up the Good Work! We Cant Thank You More Than We Say 🙏

  • @PaarsahSoroury
    @PaarsahSoroury Рік тому

    Thank you dear Dave, for always inspiring me to put my best foot forward, even when I don't feel like I belong.
    I hope the best for you in your life.
    Warm Regards.

  • @DanielMolnar_Tuzla
    @DanielMolnar_Tuzla Рік тому

    This is long awaited video. Thank you Dave, you helped me so much

  • @Rikimkigsck
    @Rikimkigsck Рік тому

    Thank you so much for explaining everything beautifully Dave.

  • @mimos6198
    @mimos6198 Рік тому

    Great explanation and unique content. I am waiting for more videos about Next.js, and problems faced by many beginners and solve these problems. Thank you for making this effort to explain the code

  • @joemathan6101
    @joemathan6101 Рік тому +8

    Thanks Dave. Crystal clear step by step instructions on next auth. Now we have a deep understanding of how to configure and setup next auth in our projects. One suggestion a quick diagram of how the auth flow should be even more awesome!! Thank you for delivering quality content for us. Learning a lot from your videos.😊

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому +6

      Thank you and good suggestion - while this default setup is very straightforward, I think some customized solutions may need further explanation in the future. The default setup uses a session cookie with an encrypted JWT (JWE). This is important because Next.js is hosted in a serverless deployment so the auth info is really in the JWE and is verified by a NextAuth server function (running in a serverless environment). Serverless is a confusing word. It means it is one big lambda function outsourced to AWS behind the scenes. The auth persists due to the cookie staying in the client. The serverless environment may go to sleep when inactive.

    • @nademkhan931
      @nademkhan931 11 місяців тому

      Thank you for that explanation, indeed 'serverless' was confusing to me before reading this

  • @user-gd4nv8wp2f
    @user-gd4nv8wp2f 5 місяців тому

    One of the best next-auth tutorials that actually covers the app router. Disappointing that the next-auth docs don't cover this and are instead using the older page router.

  • @gurdittsingh6638
    @gurdittsingh6638 4 місяці тому

    This tutorial is so good! I was feeling so confused by next-auth and next.js, you made it seem so simple 😃

  • @XCodeWhisperer
    @XCodeWhisperer Рік тому

    A very informative video. Thank you very much. Your code is perfect and very easy to read. And I would be glad to see more about role-based user authorization.

  • @RezHimself
    @RezHimself Рік тому

    Another amazing toturial, to be honest I've been waiting for this video 👌👌👌

  • @lan2media792
    @lan2media792 11 днів тому

    Thank you Dave. This was very helpful

  • @andrescampos8333
    @andrescampos8333 Рік тому

    Phenomenal, best tutorial I've run across, thank you.

  • @spiderwebbs02
    @spiderwebbs02 Рік тому

    Your tutorials are the best Dave. I got a job because of you. I thoroughly improved my projects because of your tutorials.

  • @pablotexeira7579
    @pablotexeira7579 Рік тому

    great job as always, thank you. you've been of great help once again!!!!

  • @huutamnguyen2529
    @huutamnguyen2529 9 місяців тому

    An easy tutorial to understand. Thank you so much!👍

  • @YoshiGO71
    @YoshiGO71 Місяць тому

    Thank you Dave for your helpful content .

  • @karendoran3692
    @karendoran3692 Рік тому

    Very beautifully explained as usual. I would love to see more next auth tutorials!

  • @niallmoore8240
    @niallmoore8240 11 місяців тому

    awesome work, thank you Dave!

  • @k303k
    @k303k 7 місяців тому

    Thanks a lot for this tutorial Dave!

  • @himanshutiwari9616
    @himanshutiwari9616 2 місяці тому

    Very beautifully explained dave.
    love from India❤

  • @SkippyTheCanadianKangaroo
    @SkippyTheCanadianKangaroo Рік тому

    Thanks Dave for this video! It has actually helped me GET the right data for the Credentials login. But im having a little difficulty getting users to sign in with Username,Password. But with this video i was actually able to get a step forward! THANK YOU!

  • @abhijeetray9097
    @abhijeetray9097 Рік тому

    Thanks Dave, it was really insightful

  • @Den-yg4wz
    @Den-yg4wz Рік тому

    Thanks Dave! It was very useful example, but very simple. 😉 Please, continue about NextAuth, cause you don't touch following themes: 1. Initial form for auth (how client can pass auth first time with credentials) 2. Working with DB, 3. How can clients change their credentials (email, pass, etc) at any time. 4. How can developer make own auth pages with another design? So we are waiting for next! Good luck, Dave! 💪😀)

  • @fulltimefrontend
    @fulltimefrontend 2 місяці тому

    This video was of great help, we are currently extrapolating to ditch Supabase auth for nextAuth

  • @fiendsgaming7589
    @fiendsgaming7589 Рік тому

    Thank you Dave Gray! You're life saver!

  • @AlirezaGarshasbi-kr1on
    @AlirezaGarshasbi-kr1on 7 місяців тому

    this tutorial is absolutely perfect.

  • @afsanazamannipa7711
    @afsanazamannipa7711 7 місяців тому

    Elaborated Explanation. Great. Thanks

  • @kaputokalandanya5915
    @kaputokalandanya5915 Рік тому

    I was literally just looking for this, thank you!

  • @knload
    @knload Рік тому +2

    I'd love to see the role based user authorization video. Thanks for the video, nicely done. 👍

  • @owenhochwald506
    @owenhochwald506 5 місяців тому

    Thanks you explained very clearly and now i understand!

  • @jonathan_luz
    @jonathan_luz 5 місяців тому

    The best content about this subject

  • @GeorgeDonnelly
    @GeorgeDonnelly 9 місяців тому

    This is an awesome tutorial, thank you!

  • @snivels
    @snivels Рік тому

    The reason your videos are a cut above the rest is because you explain the 'why'. When you get an error you explain why you are getting the error and then you show how to fix it. When you paste a line of code, like the import of default from nextauth in the middleware file, you explain exactly what it's doing and also show how it works.
    Keep up the excellent work, you are appreciated!

  • @jordanryanethanowona2974
    @jordanryanethanowona2974 Рік тому +1

    DAVE YOU ARE CLEARLY THE GOAT FOR ME. THANX A LOT

  • @sahaneakanayaka3394
    @sahaneakanayaka3394 Рік тому +1

    OMG! Thank you so much Dave ❤❤🙏🙏. Love your tutorials...

  • @replicant9611
    @replicant9611 10 місяців тому

    Great tutorial, thank you!

  • @chandramani6682
    @chandramani6682 Рік тому

    Nice job Dave 😊

  • @PENGGAO-fi5is
    @PENGGAO-fi5is Рік тому

    Thank you Dave, nothing to say, brilliant.

  • @ashishsharma__
    @ashishsharma__ Рік тому

    Thank you so much dave 😊

  • @user-gn7qi5xv4j
    @user-gn7qi5xv4j 11 місяців тому

    I just completed short while ago... Nice tutorial with well explanation... Thanks a lot... 🥰

  • @vittoriomorellini1939
    @vittoriomorellini1939 Рік тому

    Great video and great explanation of Nextauth . Amazing tool to manage authentication. Thanks Dave

  • @user-dt6ze6qm3f
    @user-dt6ze6qm3f Рік тому

    Hi Dave, this was an incredibly helpful video, I've now successfully set up Next Auth in my Next JS project with an AWS Cognito provider. Thanks for explaning everything so clearly and not glossing over the small details. I'll definitely check out your other videos on Next JS.

    • @anonihme5142
      @anonihme5142 11 місяців тому

      if I may ask how did you find the cognito issuer? all the tutorials i've found for it used a cognito domain and amazon has revamped their whole UI making it really obnoxious

    • @anonihme5142
      @anonihme5142 11 місяців тому

      nevermind, finally got there^^

    • @user-dt6ze6qm3f
      @user-dt6ze6qm3f 11 місяців тому

      ​@@anonihme5142 sorry I didn't see your comment earlier, glad to see you got there! I followed this video to understand more about setting up the Cognito app client. I'd love to get Cognito working with the credentials provider as opposed to using their hosted UI, but that's on a future to-do list! ua-cam.com/video/U4hEflgix9c/v-deo.html

    • @anonihme5142
      @anonihme5142 11 місяців тому

      @@user-dt6ze6qm3f cheers. Sadly the vid ends before he tries to log back in and sees that the next -auth logout function doesn't clear cookies on the cognito server, so the user is logged back in without being asked for his credentials, which is a major security risk. It amazes me that there's no simple way to do that. But then again, i'm a total noob, so simple for me is a very low bar. I shall persist and remain calm! thanks for the reply, best of luck

  • @Reyescult
    @Reyescult Рік тому

    Thank you, this has been very helpful. It would be great to have more coverage around OAUTH configuration (scope, userinfo, etc.) and sign-out from the identity provider. Anyway, thanks for the great content!

  • @maherworld1
    @maherworld1 Рік тому

    Dude you are the best. much love

  • @olagundoyeemmanuel
    @olagundoyeemmanuel 11 місяців тому

    Thank you so much Dave

  • @onizuka_js1484
    @onizuka_js1484 Рік тому

    Thank you for this amazing video! Super well explained, I just subscribed to your channel 🤩

  • @EricOnYouTube
    @EricOnYouTube Рік тому

    Yes, role based auth would be fantastic. Thanks! :)

  • @kenthefley2226
    @kenthefley2226 Рік тому +34

    This is a very informative and useful video. It would be awesome if you could expand on this by connecting a database to store users along with a credentials signup. Users should also be able to reset their password. An explanation of that is hard to come by and something most of us will need.

  • @markdenvermanuel8493
    @markdenvermanuel8493 Рік тому

    Thank you much, Dave! I have been following and watching your Next series from the moment it was still in experimental phase and up to now that is already stable. Please create a video with signup that has a database and also the role based auth. Thank you and more power!

  • @Mayank_Bisht_MB
    @Mayank_Bisht_MB 9 місяців тому +17

    everyone who face middleware issue. first clear your cookie in console.

    • @SomeRandomDev-dx2te
      @SomeRandomDev-dx2te 2 місяці тому

      This is a very strange behaviour from nextjs. Thanks for providing a solution.

  • @PySQLytics
    @PySQLytics Рік тому

    Thank you Dave!

  • @tabdig
    @tabdig Рік тому

    Very great video, helps a lot

  • @rockNbrain
    @rockNbrain Рік тому

    Great job Dave ... well explained , tks a lot 🎉

  • @desertpillar5286
    @desertpillar5286 11 місяців тому +1

    Great stuff! This was the first tutorial that actually showed the basics of how to get it working and showed where the actual routes for the automatic pages lived. One thing I'm still a bit confused about is as why there's no default signup as well in Next-Auth as that seems to be an extremely common pattern. For any type of SaaS application, how would you relate the models to the correct user/org unless you have the user in your db? So showing a more advanced (but still basic) flow like signup => verify email => verified signed in, and signin => change password would be appreciated. Also perhaps how to make your own signin page call the right endpoints in nextauth. Thanks again for saving me a lot of time!

    • @desertpillar5286
      @desertpillar5286 9 місяців тому

      I found the answer. It’s called Clerk. Use it and never look back!

  • @codewithedraak
    @codewithedraak 8 місяців тому

    You are gem
    thanks

  • @heguer87
    @heguer87 Рік тому

    Once again. Thank you so much for your mater classes!! Your genius man. You know your stuff and know how to teach it! I will buy you a couple coffees lol

  • @ZaibGsm
    @ZaibGsm Місяць тому

    good easy to understand.

  • @vanhungnguyen7543
    @vanhungnguyen7543 10 місяців тому

    Thank you so much to explaining

  • @giannifed
    @giannifed Рік тому

    Thank you Dave, amazing tutorial.

  • @joshbleijenberg4000
    @joshbleijenberg4000 2 місяці тому

    great video!

  • @sadeghmahboobifar7521
    @sadeghmahboobifar7521 Рік тому

    YOU ARE GRATE DAVE, any time that I have any problems on coding , you will make a video about my problem, Thank you my friend

  • @collinsk8754
    @collinsk8754 7 місяців тому

    Excellent ! 👏👏

  • @sarowarhosen003
    @sarowarhosen003 9 місяців тому

    Very informative lesson thank you sir

  • @GabrielMartinez-ez9ue
    @GabrielMartinez-ez9ue Рік тому +2

    Nice one...! One important point that maybe you can address in later videos is how to use user roles. To be able to pass roles to the session, you need to include them in the token, which is then read by the session.

  • @khalilbenmeziane8836
    @khalilbenmeziane8836 Рік тому

    Thank you Dave

  • @siddiqahmed3274
    @siddiqahmed3274 Рік тому

    That's a very comprehensive tutorial about next-auth. Thank you sir. and yes an advanced auth series (like react one) is very much appreciated. It is just a request to use sql based database this time for auth as we have covered mongodb in react.

  • @AliAmeer
    @AliAmeer Рік тому

    Lots of thanks to you ❤

  • @samuelbigelow3480
    @samuelbigelow3480 11 місяців тому

    This is super helpful, thank you! I do want to call out that you said you would never want to use a server component within a client component, but the application is doing that when you're talking about providers. The AuthProvider component is a client component and it the client/page.tsx component is a server component rendered inside of that

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  11 місяців тому

      You're welcome! I appreciate the call out because this shows I likely didn't explain myself clearly on this specific issue. "use client" creates a boundary between server and client components and all other components imported in the client component including children will be rendered as client components according to the Next.js docs: nextjs.org/docs/app/building-your-application/rendering/client-components ..so to follow this up, I searched the NextAuth docs for an exception with the SessionProvider used inside the AuthProvider we create in this tutorial. I did not find where those docs dive into how NextAuth works around this.. but if you add a console.log(user) to the UserCard component, build the project with npm build, and then run it with npm start, you will see that after logging in and visiting the home and server routes, the console.log shows on the server terminal - confirming they are still server components. If you visit the client route, the console.log will show in the browser console. Further, the build report after running npm build will also indicate those pages are SSR and not client components. I hope this helps clarify what I meant.
      This would actually make a good blog post / explainer topic - but the client component uses the useSession hook which uses the context. The server components instead use getServerSession which doesn't require the context. More clarification on using Context Providers with Server Components here: nextjs.org/docs/app/building-your-application/rendering/composition-patterns#using-context-providers

  • @vstrelianyi
    @vstrelianyi 10 місяців тому

    great video
    thx

  • @Nanashi-rq7lk
    @Nanashi-rq7lk 11 місяців тому

    Useful tutorial for me

  • @neveriodev350
    @neveriodev350 Рік тому

    Thanks Sir Dave!

  • @moosaabdullah6437
    @moosaabdullah6437 8 місяців тому

    this is gold

  • @vigenhovhannisian954
    @vigenhovhannisian954 8 місяців тому

    Thanks a lot

  • @IndianCoders
    @IndianCoders Рік тому

    Nice One Dave!!

  • @monowersadaf
    @monowersadaf 9 місяців тому

    thanks man

  • @Bah-wf5cf
    @Bah-wf5cf Рік тому

    great work man

  • @muhyadinmohamed6244
    @muhyadinmohamed6244 5 місяців тому

    amazing video

  • @newmanadesan9964
    @newmanadesan9964 11 місяців тому

    Thank you

  • @adejoh6650
    @adejoh6650 Рік тому

    Thanks Dave❤!!

  • @damiantriebl1747
    @damiantriebl1747 Рік тому

    awesome!, good tutorial, the advanced playlist is coming soon???

  • @codewithedraak
    @codewithedraak 8 місяців тому

    I have question Dave
    Can i use next auth for login when i am using Next 14 actions ?
    I made a form and give action to it and make login user , i am stuck at setting session
    what am i doing wrong please let me know

  • @francisboudreau7524
    @francisboudreau7524 Рік тому +1

    Hi Dave, love your Tutorials, they are great... I was wondering if you planned on making one with nextjs 13 and azure/msal or using apollo (I'm currently building a site that will be using azure/msal login and token, with apollo and graphql, but there is not a lot of help explained for human like you do since Next JS 13.4) cheers :)

  • @MrAtomUniverse
    @MrAtomUniverse 11 місяців тому

    I tried to do the client method on my header which is a seperate use client file , i'm getting Error: [next-auth]: `useSession` must be wrapped in a , or am i suppose to not do this to header ? Shouldn't i be wrapping this whole session thing on a layout file ?

  • @user-fi2um1go4c
    @user-fi2um1go4c 7 місяців тому +1

    Thanks for the content but what about editing the user informations on his profile page ? with that stack it's a pain

  • @pellorocce4338
    @pellorocce4338 9 місяців тому

    Thank you Dave nice tutorial and it is good that you mention your practice about client and server components, will work like you said because it made perfect sense to me, have a nice day!

  • @shayanhdry6224
    @shayanhdry6224 8 місяців тому

    Hello Dave Yet another awesome Tutorial thank you , here instead of using session callback for getting picture you used getserversession ?

  • @cwdev2545
    @cwdev2545 Рік тому

    thank you