Next-Auth V5 Tutorial (OAuth, Email, Server Actions, Server-Side Auth, Client-Side Auth, Roles)

Sdílet
Vložit
  • čas přidán 27. 06. 2024
  • Learn authentication with Next-auth/Auth.js 5.0 for Next.js in this one tutorial. You will learn:
    -How to set up Next-auth 5 in a Next.js project (auth.ts, middleware, Prisma)
    -How to implement Google and GitHub login via OAuth2
    -How to create email magic links with Resend
    -How to add an admin role
    -How to protect server components, client components (via useSession), server actions, and API route handlers
    -The difference between server-side and client-side session retrieval
    -The pros and cons of session vs JWT authentication
    -How to achieve static caching on pages that contain auth
    -How to make your Prisma client work on the Edge runtime (middleware)
    -How to cache your session requests between server components
    -How to update user data from the frontend
    -And more
    Project files:
    Starting code: github.com/codinginflow/next-...
    schema.prisma: github.com/codinginflow/next-...
    ⭐ Get my full-stack Next.js with Express & TypeScript course: codinginflow.com/nextjs
    ✅ Get my free React Best Practices course: www.codinginflow.com/reactbes...
    💌 Join my newsletter for regular web dev tips: codinginflow.com/newsletter
    💬 Join our developer community on Discord: codinginflow.com/discord
    📣 Follow Coding in Flow on social media:
    Twitter: / codinginflow
    Instagram: / codinginflow
    TikTok: / codinginflow
    Facebook: / codinginflow
    Timestamps:
    0:00 - What we will cover
    3:37 - Project setup + Vercel Postgres database
    9:51 - Next-auth setup + Prisma adapter
    25:53 - Google & GitHub login (OAuth2)
    40:46 - Authentication in server components
    55:31 - Protecting pages
    1:00:35 - Authentication in server actions (& API route handlers), updating user data
    1:05:09 - Admin role & TypeScript module augmentation (next-auth.d.ts)
    1:13:51 - Deduplicating auth requests with React cache
    1:17:23 - Client-side authentication (SessionProvider, useSession), vs Partial Prerendering
    1:29:05 - Session callback (adding more data to user object)
    1:34:56 - Email magic links (Resend)
    1:40:36 - Deployment (Vercel)

Komentáře • 138

  • @bhargavkumar
    @bhargavkumar Před 2 měsíci +17

    Your channel is like one stop solution for everything Next.js💖💖

  • @user-gz9mq9wb9x
    @user-gz9mq9wb9x Před 8 hodinami

    I love the Open Sourece Project videos please continue the videos

  • @tabishnaqvi5748
    @tabishnaqvi5748 Před 28 dny

    i really like how you not only explained it all extremely well, but also emphasised on the optimisation techniques

  • @Leesdjo
    @Leesdjo Před 2 měsíci

    The best channel I ever had. I appreciate you for the special work you are doing. Thank you.

  • @dm-bn4nq
    @dm-bn4nq Před 2 měsíci

    This is why i love this channel. Thank you so much for your work, you deserve more subscription

  • @zyncc
    @zyncc Před 2 měsíci

    You literally read my mind!! I really needed this tutorial and you are the best person for this

  • @mnhtada12
    @mnhtada12 Před 2 měsíci +2

    You know I was stuck in next auth , and I was hoping you to make a video about it , now u did it 😍😍😍
    Thank you sooo much u deserve more support 👏🌹

  • @davidmuturi2078
    @davidmuturi2078 Před 2 měsíci

    Yeeeeahhh , I really needed this, I've been stuck trying to update a project from v4 for 2 weeks

    • @JGriffin1410
      @JGriffin1410 Před 16 dny

      I'm in the same situation, though i can't pass adapter to prisma client

  • @2pacrapempire866
    @2pacrapempire866 Před 2 měsíci

    Bigman, this is incredible. Thank you for this. Learnt a lot.

  • @abdelrahmanmagdy3706
    @abdelrahmanmagdy3706 Před 2 měsíci

    You are always the best .. appreciate your time and efforts making these great videos ❤

  • @henryokeke1858
    @henryokeke1858 Před 25 dny

    I kept having wow moments while watching this tutorial. Remarkable resource. Keep it up and Thank you

  • @BlueHat1
    @BlueHat1 Před měsícem +1

    What an incredible tutorial!

  • @thewiseowlclub8602
    @thewiseowlclub8602 Před měsícem

    best video on Next Auth BY FAR 🔥 well done bro

  • @fixesdev
    @fixesdev Před 17 dny

    Thank you for your video! keep the good work coming

  • @senselessplays
    @senselessplays Před 2 měsíci +6

    Project with Next js, mongoDB with or without prisma,next auth,files upload using uploadthing ,and so on ❤

  • @user-lq1cs
    @user-lq1cs Před měsícem

    thankyou for this really helpful tutorial for my journey to master next js! 34:41 caught me off guard 😂😂😂

  • @SamyIsaac-md8go
    @SamyIsaac-md8go Před měsícem

    really appreciate your work , great tutorial😍😍

  • @markus_dev_cwb
    @markus_dev_cwb Před 2 měsíci

    Amazing tutorial! Tks to share.

  • @jeanmax1me
    @jeanmax1me Před 2 měsíci +1

    Great I was looking to use Next Auth in my new project maybe

  • @sajadmalik9097
    @sajadmalik9097 Před 18 dny

    There are a lots of videos showing how to use Next-Auth in nextjs. I really find it hard to search for a videos which will tell you how to use NextAuth with a seperate backend. Please make a video on that it will be really cool.

    • @codinginflow
      @codinginflow  Před 18 dny

      I don't think next-auth is meant to be used with a different backend

  • @ugurdev
    @ugurdev Před 2 měsíci

    Good one, thanks.

  • @rifky8966
    @rifky8966 Před měsícem

    The video tutorials are great because they are structured based on the official documentation.
    In the future, if you are willing, can you create a next-auth-v5 that connects to the dashboard to do CRUD?
    Thanks in advance🙌

  • @adarshrathi8265
    @adarshrathi8265 Před 26 dny +1

    Excellent

  • @yousefsaeed732
    @yousefsaeed732 Před 2 měsíci

    My legend ❤️❤

  • @dan327
    @dan327 Před 2 měsíci +1

    Would love to see a Next.js project which utilizes BLOB storage, maybe like a simple video/audio sharing platform!

  • @perspectivelevel7969
    @perspectivelevel7969 Před 26 dny

    First of all, excellent video and excellent explanation, very clarifying... I consult, I am currently using drizzle with pg which does not allow me to use the middleware due to the edge runtime, is it possible to use the node runtime to be able to deploy the proyect and db on local or private vps? thank you

  • @xxxkadal2162
    @xxxkadal2162 Před 2 měsíci

    Great tutorials! anyway is there a plan for you to make an tutorial about making a dashboard page that use many library like 'Highchart' for displaying analytical data?

  • @Alex.Shalda
    @Alex.Shalda Před měsícem

    awesome!

  • @anonymous12478
    @anonymous12478 Před 2 měsíci

    Thanks

  • @MrPivario
    @MrPivario Před měsícem

    Thank you for the great content , i got problems with next auth and keycloack , could you please do a video in this context?

  • @ElohimCode
    @ElohimCode Před 2 měsíci

    Thanks for this tutorial, although I've been looking for a hands on refreshtoken. If perhaps you can do a part 2 on this feature.

  • @martintembo2355
    @martintembo2355 Před 21 dnem

    Great video!
    What's the best approach when nestJS/ExpressJS or any other separate server with NextJS?
    I want to maintain the same authentication architecture.

  • @zeeeeeman
    @zeeeeeman Před 9 dny

    hmmm create t3 app side-steps a lot of this. But still a great video none the less.
    nit: `prisma generate` 1:07:54 - surely TS will see the updated schema rather than rolling your own.

  • @developedbynick
    @developedbynick Před 2 měsíci +1

    Hey. I'm fairly new to nextJS. However in a traditional express server with Mongoose, you could specify the data to be passed to the create method on the Model, but with next-auth, I see that auth js interacts with the database itself, but I'd like my data to follow a specific shape. Is it possible to do this with next-auth?

  • @darksitopx
    @darksitopx Před 2 měsíci +1

    Your content is quite an experience, I know that what I will say next may not be correct, because your content is free, I am from LATAM and the English language is not my thing so I use an extension to translate your videos, but This translator or the subtitles on CZcams are only available until 3 or 4 hours into the video, then I can no longer translate and I have difficulty following the video, perhaps cutting the videos into sections would be good.

  • @soma7891
    @soma7891 Před 3 dny

    Can you -please- tell me what do you use the create your thumbnails and edit your videos?

  • @drdonice
    @drdonice Před měsícem

    Amazing tutorial! "My pronouns are actually async and await" 😂

  • @jayadityag7670
    @jayadityag7670 Před 17 dny

    Hey, would love to have a tutorial on Firebase, it will help in my hackathons... thx

  • @marishwarannadar5323
    @marishwarannadar5323 Před měsícem

    Great Explaination, One question does the request gets duplicated if we switch to client side authentication when using SessionProvider?

    • @codinginflow
      @codinginflow  Před měsícem

      The server and client requests are separate

  • @kaedien
    @kaedien Před 2 měsíci

    oh I saw u on tiktok

  • @theintjengineer
    @theintjengineer Před 2 měsíci

    Please, add credentials provider.
    Also, can you refactor the project to use drizzle ORM, so that there's a project version using Drizzle?
    You could even have it as another Github branch.
    Cheers🙌

  • @_hugo_cruz
    @_hugo_cruz Před 2 měsíci

    Thanks for this Florian, it has been very interesting, it would be great when everything is stable to update it and could also add the login with email and traditional password. Also I would like you to show at some point how you do the migrations from Prisma to Vercel, I have not been able to make it work. Blessings to the channel and I always recommend it for the quality content it has.

  • @ts3798
    @ts3798 Před 2 měsíci

    Thank you very much for the tutorial. One question, is there a reason that you use uppercase String for the role in the declaration file?

    • @codinginflow
      @codinginflow  Před měsícem

      No I was confused by this myself lol. I think it doesn't matter.

    • @ts3798
      @ts3798 Před měsícem

      @@codinginflow Ok, thanks.

  • @joe_j
    @joe_j Před 2 měsíci +1

    I love this. Hey can you do a project with web sockets

    • @codinginflow
      @codinginflow  Před 2 měsíci

      What do you wanna see exactly?

    • @joe_j
      @joe_j Před 2 měsíci

      @@codinginflow realtime update of data without having to refresh the page, where it keeps track of the current data in the database after I update. I hope this is more clear

  • @devdariill
    @devdariill Před 2 měsíci

    now with supabase :D ty

  • @nomxxn
    @nomxxn Před 28 dny

    In production, the server actions seem to be quite slow for me, for example my login action takes a whole 3 seconds to login the user lol, even after using redis, I'm clearly doing something wrong or maybe credentials login is just slow overall with auth.js, what do you think Florian? btw, appreciate all these tutorials mate, keep it up!

    • @codinginflow
      @codinginflow  Před 28 dny +1

      Rename the middleware.ts to something else and let me know if the problem still persists

    • @nomxxn
      @nomxxn Před 24 dny

      @@codinginflow I didn't even have the middleware setup lol, appreciate that mate!

  • @fismael21
    @fismael21 Před 2 měsíci

    Hi, great video. Just one question. What happened with your Android's Studio tutorials?

    • @codinginflow
      @codinginflow  Před 2 měsíci

      There will be no more Android content on this channel (or any of my social media channels)

  • @kemmouneismail3087
    @kemmouneismail3087 Před měsícem

    can you please make a video about adding scopes to the Oauth providers to get access to more user data? I tried some old next-auth solutions, but it seems they don't work

  • @Prag1974
    @Prag1974 Před měsícem

    Hi Man. Great content. Thanks. But I have a problem: I want to use session based authentication strategy (as you know jwt is little bit unsafe) and I also credentials provider. When I adjust credentials provider in auth.ts and other files, next auth throwing error something like " 'session': 'database' strategy doesn't support credentials provider" is there any way to fix it? if not, can you suggest me a library that allow users credentials login and uses session based strategy. What should I do? Thanks.

    • @codinginflow
      @codinginflow  Před měsícem

      Lucia has username + password login with session. I would use that.

  • @2kceltics
    @2kceltics Před měsícem

    Ive been working on your tutorial but I only use mongodb, I created mongoose models compatible with auth.js docs and I had to create a mongoclient adapter and extend globals type for mongoose compatibility, everything are running well after all... If you want I could fork my final project in a new branch into your repo.

    • @DailyNevFacts
      @DailyNevFacts Před měsícem

      Hey man, I have been having issues on a separate project . I see you have been using adapters for auth js. I am trying to run an adapter for a login in and register form. The form allows users to sign in with google but this will not work. Any ideas?

    • @2kceltics
      @2kceltics Před měsícem

      @@DailyNevFacts this is Florian channel not mine I can't help you unless he allow me to upload my project to his repo in github. 😞

  • @techtips6968
    @techtips6968 Před 2 dny

    This is excellent work. I really appreciate you shared with us. Can you please add server side authentication ie sign up and sign in using email and password?

  • @SachiAkira
    @SachiAkira Před 28 dny

    Hi, I have a small question, does this work with Pages Router? Thanks in advance.

  • @owdx8984
    @owdx8984 Před 2 měsíci +1

    34:41 caught me off guard

  • @user-nm6nw5kp8u
    @user-nm6nw5kp8u Před měsícem

    Hi developer i have qst , i made a external api with Laravel for Oauth providers and it give me the data user I want to know is i can set session to server from client or not , thanks advanced 😊

  • @whoooooo
    @whoooooo Před 2 měsíci

    Will the user be updated if, for example, another user changes their role by removing admin status, in case one user is already logged into the site and another changes their role? Will the user whose role was changed be automatically updated?

    • @codinginflow
      @codinginflow  Před měsícem

      Yes because the user data is retrieved on every request when you use sessions

    • @whoooooo
      @whoooooo Před měsícem

      @@codinginflow Wouldn't it be a strain on the server if, as I understand, every user updates their data with any interaction with the system? That's a request to the server, and when there are many users, it means a lot of requests, doesn't it?

  • @tobitacklestech
    @tobitacklestech Před 2 měsíci +1

    Im getting MissingAdapter when trying to use Resend (I use DrizzleAdapter
    ) any help?

  • @benemma5602
    @benemma5602 Před 2 měsíci

    what if I wanted to use a custom email provider for magic links e.g AWS SES?

  • @kubilaybzk
    @kubilaybzk Před 2 měsíci

    İf we want to set a jwt token ( which comes on the backend api request )
    How we can do that ?
    I mean how we can set expire time and token with nextAuth?
    I want to expired the token backend's token expired.

  • @ilan117
    @ilan117 Před 25 dny

    I would not use “if (!user) ...". to protect the user page because one could still reach out to the user page giving the user id and access the user data. I would use "if (!session?.user) ..." or add it as a 1st condition. What do you think ?

    • @codinginflow
      @codinginflow  Před 25 dny

      Which part do yo you mean exactly? If it's rendered on the server, it should be safe.

    • @ilan117
      @ilan117 Před 25 dny

      sorry my bad … if anyone can access the user page without being logged in then it’s fine. I was heading to allow the access to this page only if a user is logged in.

  • @user-qx5yd3uw9z
    @user-qx5yd3uw9z Před měsícem

    i have the problem, if you run the build productions in local computer, the session speed is lightning fast, but in vercel this is take like about 4-5s to get session in every page

    • @codinginflow
      @codinginflow  Před měsícem

      This might be caused by the middleware bug I was talking about. Delete the middleware (or rename it) and let me know if it's still slow.

  • @kartavyabagga
    @kartavyabagga Před měsícem

    bro i get WEBPACK_EXPORT_DEFAULT error ...authconfig before initialization .when i write
    const session = await auth(); in any server action
    What can be done ?

  • @aurel.visual
    @aurel.visual Před 11 dny

    yes no .env or .env-exemple in the repo, but thank for the video

    • @zeeeeeman
      @zeeeeeman Před 9 dny

      .env - never .env-example yes but with redacted passwords.

  • @Tej_Dev
    @Tej_Dev Před měsícem

    I've seen a new error (This is only in Production), if i authenticate through Google OAuth on server side using signIn() from "@/auth", i'm redirected but i see a 404 error page , but when i reload it works. This is only in Production. But when i get the session from client side and signIn() from "next-auth/react", i don't see this happening. Does anyone know why

  • @syedbilalchand1766
    @syedbilalchand1766 Před měsícem

    How to implement access token and refresh token

  • @ZeeshanElia
    @ZeeshanElia Před měsícem

    I have suggestions for you i u wanna grow up your channel then
    Trying to make live streaming at react animate series
    It high demanding topic now days

  • @robinkantyadav3344
    @robinkantyadav3344 Před 2 měsíci

    Hello this is my request to you that can you tell me how can i make my css folder of next js project accessable to googlebot.
    Actully problem is that when i make project static build the css file is saved under a private folder and so google bot ignore that file when taking screenshot of my webpage (caching) google bot only take only html file so can you pls help me that what should i do.

  • @RishabhSingh-oc6vw
    @RishabhSingh-oc6vw Před měsícem

    Payment integratation please in your ecommerce app

  • @Tej_Dev
    @Tej_Dev Před měsícem

    The Edge Function "middleware" size is 1 MB and your plan size limit is 1 MB. why am i getting this error while deploying the project in Vercel? Can anyone help me

  • @2kceltics
    @2kceltics Před měsícem

    Why do you use prisma instead mongoose ?

  • @bandekhoda7801
    @bandekhoda7801 Před 2 měsíci

    Do they have a date as to when they're gonna release a stable version?

  • @mleite1
    @mleite1 Před 2 měsíci

    Im having a problem with the session callback.. it runs multiple times. So if i want to save something at database there, it's doing 4x times. Couldn't find a solution to this

    • @codinginflow
      @codinginflow  Před 2 měsíci

      It's probably not the right place to store something n your DB

  • @jjoksa
    @jjoksa Před měsícem

    How to handle this problem: Adding an item to the cart on the server side and reFetching cart items number on the client side without need to check every for example 5 seconds or so? I made Navbar client-side component and showed the number of cart items on client side component, how to automatically re-fetch the number after adding a new item?

  • @yj4105
    @yj4105 Před 6 dny

    57:37 redirect("/?callbackUrl=/settings"); isn't it supposed to be working as well? :(

  • @Aekaay
    @Aekaay Před 2 měsíci +1

    it does not work for me unless i specify google client id and secret in auth config

    • @mDHARYL
      @mDHARYL Před měsícem

      Of course you need to add your own Google client id

  • @timothylee3203
    @timothylee3203 Před 2 měsíci +1

    why are u using neon adapter with vercel db?

    • @codinginflow
      @codinginflow  Před 2 měsíci +1

      To make it edge-compatible so it works in middleware. I explain that in the video.

  • @AbdallahMoubarak
    @AbdallahMoubarak Před měsícem

    can you do the same for Mongoose ?

  • @ozdadev
    @ozdadev Před měsícem

    Can you do a authentication and authorization without any auth library

    • @codinginflow
      @codinginflow  Před měsícem

      That's not recommended because there are 1000 things you can do wrong. Also, it's very boilerplaty.

    • @ozdadev
      @ozdadev Před měsícem

      @@codinginflow But there're tons of things to learn there. One other thing is integrating nextjs FE with Nest or express API + axios instance usage(refresh token, SSR, CSR)

  • @rich-able
    @rich-able Před 17 hodinami

    1:28:45 When re-login with useSession That will be be undefined on loading init session. It may need hard-reload. I think that's not proper demonstration.

  • @2kceltics
    @2kceltics Před měsícem

    Wait a minute... I could save the users data in localstorage and give him access to the main app while the cookie isn't outaged... I'll save a lot of callings to database every time the user navigate to a new server route...

    • @codinginflow
      @codinginflow  Před měsícem

      That's highly insecure

    • @2kceltics
      @2kceltics Před měsícem

      ​@@codinginflowOk thanks for the advice.

  • @davidmuturi2078
    @davidmuturi2078 Před měsícem

    Bro add an example.env please

  • @OmarFaruk-bz4gw
    @OmarFaruk-bz4gw Před 2 měsíci +1

    ❤plase crendintial provider

  • @mDHARYL
    @mDHARYL Před měsícem

    toast is not working

  • @user-mh1km3mv7z
    @user-mh1km3mv7z Před dnem

    i just want to make username and password >.< how do i make username password with authjs?

    • @codinginflow
      @codinginflow  Před dnem

      To be honest, I pick Lucia Auth for that. My next tutorial will use it.

  • @zeeeeeman
    @zeeeeeman Před 9 dny +1

    58:11 - This is no longer the way to protect pages czcams.com/video/EGDD0rlBd8Q/video.html
    I can add a RSC: 1 Header and see the children Page content. ( I know it's super annoying )

    • @codinginflow
      @codinginflow  Před 9 dny +1

      He's talking about layouts, not pages.

    • @zeeeeeman
      @zeeeeeman Před 8 dny +1

      @@codinginflow Thank you - TIL! Layouts not pages!

  • @herozero777
    @herozero777 Před měsícem

    Extra thumbs up for the pronouns :')

  • @litDevYT
    @litDevYT Před měsícem

    async/await 💀💀

  • @themesongasker
    @themesongasker Před 11 dny

    bros pronouns are async/await 💀💀💀 btw i can't seem to get the adapter to work (prisma edge function), i am working on my own project tho (not using the starter code)
    anyone can point me to the right direction/documentation about making prisma work with edge?