Next.js App Router Authentication (Sessions, Cookies, JWTs)

Поділитися
Вставка
  • Опубліковано 26 вер 2024
  • Learn the foundations of session based authentication through cookies in the Next.js App Router, and how community libraries like Auth.js build on top of this model. Auth is a deep topic, so let me know what else you want to see here!
    ◆ Basic: github.com/bal...
    ◆ NextAuth: github.com/ver...
    ◆ Docs: nextjs.org/doc...

КОМЕНТАРІ • 289

  • @codewithantonio
    @codewithantonio 7 місяців тому +385

    Always lovely to see official guides on these important topics :)

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

      Lee Robinson is awesome, always with videos right on point. Also thanks for your guide on next-auth, I'm almost done with it.. 1 or 2 hours left xD. Learning a lot

    • @filthynirvana5553
      @filthynirvana5553 7 місяців тому +6

      hey there ! just wanted to tell you that your videos are amazing. thank you for your efforts, keep UP the good work

    • @masaratech
      @masaratech 7 місяців тому +1

      @codewithantonio thank you for your efforts, your work is admirable and helped me alot.

    • @rig-xf6or
      @rig-xf6or 7 місяців тому +2

      Antonio the goat of web tutorials. Really enjoyed your next-auth v5 tutorial.

    • @Pra2wins
      @Pra2wins 7 місяців тому +2

      Thanks Antonio for your auth tutorial

  • @daytatech-youtube
    @daytatech-youtube 6 місяців тому +4

    I think authentication is a super important topic for web development and next.js and I think you guys should expand more on this. Security is the most important thing for modern web applications and I think you guys should keep talking about it. Great work.

  • @Leo-dx6uc
    @Leo-dx6uc 7 місяців тому +18

    Looking for this tutorial for months. So nice to have a official tutorial to follow. Thanks!

  • @franknguyen8396
    @franknguyen8396 7 місяців тому +11

    Nice and concise tutorial on a subject matter that tend to be very tedious and confusing. Great job Lee!

  • @Oxygen.O2
    @Oxygen.O2 5 місяців тому +1

    Sweet Jesus, where were you the last couple of weeks when I was trying to implement it the correct way? Your solution is so simple yet powerful and God thanks you did it in less thans 12 minutes, thanks man!

  • @wayslow
    @wayslow 7 місяців тому +15

    Thanks for Lucia shout out, I've integrated the V3 recently and it was a breeze.

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

      Yup, Lucia is great

  • @zykloprt3391
    @zykloprt3391 7 місяців тому +5

    Great tutorial on Next.js authentication, very clear and straightforward! Quick note, though: using both "expires" and the official "exp" claim for JWT expiration seems redundant, as most libraries handle expiration with "exp" directly. This could simplify things:
    - Stick to "exp" and drop the custom "expires" claim.
    - Use `setExpirationTime` for consistency across your session and JWT.
    This keeps your code clean and in line with standard practices. Keep up the great work! 👍

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

      Great addition! 🙂

    • @rob90991
      @rob90991 5 днів тому +1

      As I understand it "expires" is not a custom property but the time at which the cookie expires and "exp" is the time the jwt expires.
      If I omit the expires property the cookie becomes session based and deletes on browser close.
      I don't know of any way to use "exp" as the "expires" date for cookie expiration as "exp" time is jwt encrypted and can't be read the the browser without decryption and conversion to correct format first.
      Let me know if I have misunderstood something.

  • @nardove
    @nardove 21 день тому

    Thanks! for the tutorial, just a small note for those that wonder why the email value is always null, simply add name='email' to the input field

  • @AndreiValasevich
    @AndreiValasevich 7 місяців тому +1

    I would like to see a video on the topic of authorization/authentication for cases when a third-party server(node/nest/etc...) is used and also how it should work for "use client" components/pages

  • @yunglee.
    @yunglee. 7 місяців тому +2

    Would love a video about using OAuth to login with a custom backend and how to refresh a session with your own issued JWT!

  • @williamschaefermeyer7007
    @williamschaefermeyer7007 7 місяців тому +4

    Please keep uploading these videos how you have been the last bit I've been really enjoying them and finding them useful

  • @pistolplasma
    @pistolplasma 7 місяців тому +4

    Lee great job. If you could create a video on how Next.JS handles “authentication” -vs- “authorization” that would be awesome.
    Thanks Lee….😁👍🏿✨

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

      I have to say the canonical approach (authorization middleware) seems a little too basic but if it works it works.

  • @thepromisebenard
    @thepromisebenard 7 місяців тому +16

    Nice Video. I think authentication and authorization is not really talked about often. It will be nice to see more indepth videos on rolling out custom auth and using libraries like auth js and clerk.

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

      That's what I expected. Next-auth is already well documented

    • @SAsquirtle
      @SAsquirtle 7 місяців тому +4

      @@aberba lol

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

      @@aberba it's not good at all.

  • @WebDevEducation
    @WebDevEducation 7 місяців тому +3

    Awesome stuff! And really appreciate how the Next docs are being filled out to cover these things ❤

  • @SteveDotNet
    @SteveDotNet 7 місяців тому +4

    Great walkthrough as always.
    And for those who noticed the null email, I see someone opened a PR on the linked repo to fix it.

    • @leerob
      @leerob  7 місяців тому +1

      Thank you! Smol bug :)

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

    I want to thank you for this excellent introduction to authentication in Next.js

  • @textual
    @textual 3 місяці тому +3

    the two examples shown are not the same. ones a credentials provider and the other is oauth. it would've been nice to see a simple example of credentials using next auth. but the fact that so many are seeking help around this illustrates next is missing the point here in some way

  • @marktaylor865
    @marktaylor865 4 місяці тому +1

    a month ago i was entirely new to node.js react.js tailwind next.js and typescript and i have been enjoying it so much until i got to authentication. it has been a horrible experience. this video outlines a more direct approach to authentication and session management and I'm hoping it can help me implement properly because I'm pretty close to quitting next.js.

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

      seems the first method has gotten me 90% of the way there. 3 days i flapped at this.

  • @6099x
    @6099x 7 місяців тому +1

    awesome to see attention to auth* - its such a crucial topic! Would love to see ways to work with open source solutions like keycloak or Ory + Next. They solve nearly anything a large scale product might need while being completely open source

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

    The way this video explains Auth in Next.js reminds me of how Dan explained React Redux. Next.js App Router next-auth changes are also super exciting!

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

    I just finished this feature tonight. after that I watched UA-cam and saw that you had made the tutorial. this is such a coincidence. keep up the spirit, Bro. 😁

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

    Just saw the news about the promotion ( a few months after it happened ) -- congrats!

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

    I love to watch videos where the focus is on proper documentation

  • @АрсенийАлександрович-ж4ь

    Спасибо! В документации не нашел примера нужного, а тут стало понятнее.

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

    Wow finally, thank you for this video. This really helped my understanding of how to implement my auth flow!

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

    This is great, but what I hoped to get is information about was how authN and authZ intersects with the caches of server components and other server-side functions, as well as how and when to authorize server actions

  • @eulersson
    @eulersson 7 місяців тому +5

    Very useful video :D One minor point: shouldn't the encrypt/decrypt really be `encode_and_sign` and `decode_and_verify_signature`? I don't believe you are encrypting unless I am missing something.

    • @david.thomas.108
      @david.thomas.108 7 місяців тому

      You are correct. The JWT isn’t encrypted. It is signed and the signature is verified. The JWT payload is base64 encoded and visible after decode. JWT has a different spec for encryption, known as JWE.

  • @manujgogoi
    @manujgogoi 4 місяці тому +1

    How to use updateSession() for jwt accessToken and refreshToken

  • @RaulHernandez-to3ce
    @RaulHernandez-to3ce 7 місяців тому

    You have no idea how helpfull is this video to me. Thanks a lot for an insightful explanation and for the amazing content

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

    good session. yes we need more detail session on this. As this is related to auth or security we don't need to learn this from anywhere else.

  • @SaidYeter-j1w
    @SaidYeter-j1w 7 місяців тому

    look at this how awesome. giving lightweith version of topic is really good. thanks man

  • @ЛусінеАтаджанян
    @ЛусінеАтаджанян 7 місяців тому

    Great video! Can't wait to see the full guide on the updated next-auth lib!

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

    Awesome video, congrats! Specially due to explanation of the missing sign in part that is not in the Next.js docs. Thank you.

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

    Bravo Lee and Balázs! I just copied the code, liked it so much!😅

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

    This is more informative beyond nextjs and React... well the first example 😊😊

  • @paramaggarwal
    @paramaggarwal 7 місяців тому +1

    On the input element name="email" was missed, hence the formData read was failing and hence email was getting set as null in the JWT cookie.

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

    Thanks ! we need more content about authentification. Very usefull topic.

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

    I've been able to run the nextauth version just fine in dev mode, but when building in standalone mode, I'm having all sorts of issues. It would be awesome if a version of that in standalone mode were released. thank you, Lee!

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

    This was incredibly insightful, thanks Lee

  • @mystickago
    @mystickago 7 місяців тому +2

    can someone help why do we get null value in the email area

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

    Nice, server components are great for websites or when you don't have much interactivity in a component in a application. Having the option of using them is really helpful althogh I much prefered if they didn't had put them as default in next.js.

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

    Exactly what I've been waiting for

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

    This is what I have been waiting for. thanks!

  • @Edgar-pu1lc
    @Edgar-pu1lc 7 місяців тому +1

    Authentication in next js is the only reason why I don't use next, but if I have implemented authentication and authorization process on backend(Nest Js), what should I do in that case ? Where to save access token after successful authentication ? How to send access token along with header on each request ? In normal react this process is done very easily with axios or state manager(redux).

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

    God bless you. I couldn't figure out just how to do exactly that

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

    Vercel Auth would be great to complete with clerk, auth0. Something built-in and easy to use / deploy.

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

    this tutorial is my life saver, thanks a lot lee!

  • @traezeeofor
    @traezeeofor 3 місяці тому

    In video, under session in , "email" returns null.
    This is an error/oversight on your part. Please see corrected code below:
    name property missing from input element. 😋. You're welcome.

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

    I know this is a very big long shot, but I would absolutely love to see a video about a multi-tenant nextjs app with authentication (with custom domains and such). Ideally without using the Vercel starter kit, cuz that's no way to learn how it actually works... Also not ideal for people not hosting on Vercel. As far as I can tell there is not a single good resource for this on either UA-cam or Google.

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

    Nextjs & discord auth would be awesome, extending the Session, modify the callbacks etc

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

    For those getting user { email: null } in the session output, remember to add a name attribute `name='email'` in the email input in the `page.tsx` file

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

    Thank you for a basic tutorial

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

    The guide is so useful. Thanks a lot!

  • @MrJettann
    @MrJettann 7 місяців тому +2

    Alright, so you set the session on frontend, but what to do if i should do it on backend with refresh and access tokens? Can you make a video about server authentication with these tokens? I can't find any valuable info about this :(

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

    I tryed next-auth, authjs, but this satisfied what I was looking for. thanks

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

    Yes we would like to talk more . Authorization

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

    Lee, can you do one about GDPR?
    I was worried when I learned that google fonts was not compliant, and then gladly surprised when I learned that next/font does self-hosting automatically.
    I would love to know more on how small projects can comply without it being a headache.

  • @justusadams2770
    @justusadams2770 7 місяців тому +1

    This is very helpful, Great !!!

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

    Great video.. a deep dive using supabase auth will be helpful

  • @joshuasingh854
    @joshuasingh854 7 місяців тому +1

    Can this be done as easily on the pages router? Does anyone have a video or example of this? Thanks

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

    This is great.Please can you do a video on how to use nextjs and an external cookie based authentcation api (e.g nodejs express) and how to persist the cookies in deployed nextjs.Once again thank you

  • @rayhanislam7518
    @rayhanislam7518 7 місяців тому +2

    Can I access the token or session from client side component. because I think httponly cookie don't access from client side.

  • @John-hz8si
    @John-hz8si 5 місяців тому

    finally an official guide!!!

  • @talha-nagorik
    @talha-nagorik 7 місяців тому

    Thanks for the most needed content ❤

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

    This was great. Thank you

  • @longhuynh8277
    @longhuynh8277 17 днів тому

    would be great if there is an example with service worker.

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

    I would love to see a deep dive on this. Admittedly I need handholding or a follow along a few time before I get things.
    I'd like to do something where there is a Username/Email and Password OR Google OR Github. Smurf the actual user lookup initially but then be able to plugin a database or something like AWS cognito, after the fact.

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

    Thanks Lee, always helpful!

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

    Very informative, Can you please make a more detail article on how to implement client side and server side validations on the server components during login process?

  • @Fernando-v8l
    @Fernando-v8l 7 місяців тому

    Pretty good video, as usual!

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

    Thanks for doing this as I think a lot of developers are new. The JWT piece seems unnecessary. You could easily just sign (not encrypt) a user_id or 1 off session value from the server (stored in database)

    • @leerob
      @leerob  7 місяців тому +2

      You don't need to use JWTs but it's something I get asked about frequently since many people do!

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

      That's just your opinion.

  • @HigherStudyAspirant
    @HigherStudyAspirant 7 місяців тому +1

    Perfect. I always look for the custom way as next-auth is very abstract and I don't know what is going behind. Now my question is do we need to check getSession in each page, if yes, then will it work for Server and Client in the same way? and second query is how to handle callback url, I know if I check the session in each page, then I need to redirect and put the callback of each page, but if there is any way where I can define these in central/one place instead of checking in all pages.
    P.S: I am not using library (auth.js, clerk etc.,)

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

    More of this you ask? Yes, please 🧠👍

  • @kbin.a475
    @kbin.a475 7 місяців тому

    We want full client(User) + admin authenctication tutorial including role based auth and routes for admin.

  • @navidehyaee8123
    @navidehyaee8123 2 дні тому

    doesnt auth.js v5 handle encryption and sigining of jwt by default? why are you manually doing it?
    Thanks for the tutorial!

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

    No database session in nextAuth credentials strategy, hence why i prefer Lucia Auth

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

    Thanks a lot Lee, This was really helpfull

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

    Worth its weight in gold!! Nice one, Lee!!

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

    Thanks for this Lee!

  • @mekelilyasa9561
    @mekelilyasa9561 5 місяців тому +66

    Next js is getting more and more unclear regarding the authentication/authorization process

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

      R u serious?

    • @haiffy
      @haiffy 4 місяці тому +1

      Yeah... Even next-auth has a half-assed documentation. I ended up searching tons of tutorial vids and github project examples just to implement email & password authentication with mongodb... Most of them are still on next-auth v4 too

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

      What?

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

      This is me right now

    • @adreto2978
      @adreto2978 24 дні тому +4

      Skill issue

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

    thank you for the repo, mate

  • @rtoronto7637
    @rtoronto7637 20 днів тому

    Why is email 'null'? Shouldn't the email that was typed in be displayed under the form?

  • @fullstackjavascript2757
    @fullstackjavascript2757 3 місяці тому

    how do we get modified headers from middleware.ts to the page.tsx and access cookies in the client component? please do a video for a better understanding

  • @mystickago
    @mystickago 7 місяців тому +1

    im using nextui which uses client" but the login functions use "use server" i get errors tried looking everywhere for a fix 😭😭

  • @guilhermedavid3232
    @guilhermedavid3232 7 місяців тому +2

    Lee, I have two questions about authentication in Next js.
    Can I use node js apis in middleware? Or do middleware necessarily run on the edge?
    The next-auth auth function is not memoized on the server, can I use the react cache function to memo the auth function?

  • @ViliamKopecky
    @ViliamKopecky 7 місяців тому +1

    Encrypt/decrypt naming is misleading here. It should be encode/decode. JWT contents are only base64 encoded - readable by anyone. The crypto part only generates a signed checksum to verify those contents were published by trusted entity.

  • @UwU-dx5hu
    @UwU-dx5hu 7 місяців тому +22

    Next auth has the worst documentation in the history of documentations!
    It took me weeks to get used to it.
    Everything is scattered here and there.
    Come on people! Dont just make great software!, Make minimum descent documentation first!

    • @darrenpierre9903
      @darrenpierre9903 7 місяців тому +1

      I feel your pain

    • @leerob
      @leerob  7 місяців тому +1

      I believe they're working on a new version!

    • @shakapaker
      @shakapaker 7 місяців тому +1

      So true

    • @TechCode50
      @TechCode50 7 місяців тому +1

      Good to know - it is absolutely overdue - hope it comes soon !@@leerob

    • @A03L
      @A03L 7 місяців тому +1

      Yeah I feel your pain

  • @jrnxf
    @jrnxf 7 місяців тому +1

    This is a really well done video, Lee! However, as I've mentioned before, the issues here is not reading the user data off the session, but the inability to use the updated session user to set client-side state immediately (without relying on a useEffect or a hard refresh) due to the router cache. Any update on when this can be fixed?

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

      I'm having the same problem ... Did you fix it? Fucking nextjs cache, it's a pain in the ass and is incredible how difficult is to deal with it, there is no information about it, not even in the documentation

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

    What a awesome tutorial

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

    This is great! Isn’t it more accurate to say “encode” / “decode” and “sign” / “verify signature” versus encrypt / decrypt? Nothing is encrypted so imo using that terminology could be a little misleading

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

    Love the video, Can you make more video on integration for app router with next auth showing server side loading user data on page , and server side check for authenticated pages. it will be really helpfull, couldn't find any resources out there.

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

    Thank you Lee, very helpfull!

  • @0GRANATE0
    @0GRANATE0 5 днів тому

    which nextjs version is this? which version should I take for a new project?

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

    Hello, I have a genuine doubt: how can we use clean architecture on Next?

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

    In the video, Lee uses middleware to upate the expiry of the cookie. Why is he doing that? Is it not better to keep the expiry of the cookie identical to the expiry of the JWT?
    It kind of defeats the purpose of an expire date, if you keep pushing it forward in time on every reload.
    My best guess is that you want to give more time every time a logged in person visits the page, so they could effectively stay logged in forever if they reload every 9 seconds (since he set expiry to 10 sec).
    Also, someone else already asked, but did not get an answer: What vscode color theme is used in the video?

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

    yeah more guides on roll your own auth and more guide on building RBAC and adding MFA and 2FA in Next.js with App Router.

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

    Thank you, Lee, this is very helpful! I started working on an app using Auth.js but seeing how easy it it to implement authentication with Next.js, I'm wondering if it is worth using Auth.js. What's the added value compared to just implementing our own auth with Next.js?

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

    Can you please make a page transition video using next.js v14 with app dir and framer motion? Including exit animation?

  • @quemistrymtech31
    @quemistrymtech31 3 місяці тому

    The Jwt looks like it is encoded to Base64 string instead of encrypted. The encrypt function is signing the JWT and decrypting is validating the signature?

  • @infohpreet
    @infohpreet 3 місяці тому

    The auth session object return only name, image, email. Can you please show how can we make callback to getServerSession to fetch other user parameters like id, userPrinciPalName, etc, in case of Entra Id?