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

Поделиться
HTML-код
  • Опубликовано: 27 сен 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!

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

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

  • @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 RUclips 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

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

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

  • @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!

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

  • @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 RUclips 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

  • @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 :(

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

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

  • @Edwinil
    @Edwinil 6 месяцев назад

    I tryed next-auth, authjs, but this satisfied what I was looking for. 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!

  • @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.,)

  • @AbuBakr1
    @AbuBakr1 2 месяца назад

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

  • @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!

  • @shilohgeorge1078
    @shilohgeorge1078 5 месяцев назад

    Thanks a lot Lee, This was really helpfull

  • @mekelilyasa9561
    @mekelilyasa9561 6 месяцев назад +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 25 дней назад +4

      Skill issue

  • @27sosite73
    @27sosite73 6 месяцев назад

    thank you for the repo, mate

  • @rtoronto7637
    @rtoronto7637 21 день назад

    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?

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

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

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

  • @DespicariPirates
    @DespicariPirates 7 месяцев назад

    next video if possible be authrization
    any maybe protecitng routes /pages

  • @wuffgang5333
    @wuffgang5333 7 месяцев назад

    middleware can be async too? why is there waituntil helper then?

  • @william_keller
    @william_keller 7 месяцев назад +3

    First like ❤

  • @nmdpa3
    @nmdpa3 5 месяцев назад

    In the authjs overview toward the end, one of the added security checks shown via the devtools / applications display was a CSRF token. Is the "role your own" auth in this video (using JWT and the session cookie) also in need of a CSRF token, and if so, any examples of how that would be added to the existing code example?

  • @psyferinc.3573
    @psyferinc.3573 3 месяца назад

    more auth please

  • @zomars
    @zomars 7 месяцев назад

    You're missing name="email" in the email field on the login form.

  • @Joi-w2t
    @Joi-w2t 7 месяцев назад

    tell me dear developers, what place did you think when you released the new version of nextjs, even if you can't make a chain of middlewares?

  • @bartesler5262
    @bartesler5262 7 месяцев назад

    Thanks for this awesome video!
    Assuming you have a server that is returning a JWT in an API call, and you’re using the pages router, whhat is the right place for the login, logout functions? Using Next api handlers?
    Also, in this scenario would you still set the JWT in cookies in the same way?

  • @nikako1889
    @nikako1889 7 месяцев назад +2

    which vscode theme is this?

  • @BuhuuRecords
    @BuhuuRecords 4 месяца назад

    Is it possible to show next-auth, but also just with your own login and password? I have searched a lot of youtube and nowhere have I found a clear example of such an application, and it seems to me that to learn the basics of the backend it is much more useful to just implement your own solution than a provider like github.
    PS. when someone logs in via google/github etc. how can we for example add such a user to the database as a user that exists with us? because basically he doesn't seem to have an "account" on the platform.

  • @maximezanos
    @maximezanos 7 месяцев назад

    Thanks for the video but the main issue with Next Auth is sharing the auth context between Server Component and Client component ...

  • @ARUNRAWAT-rh5ks
    @ARUNRAWAT-rh5ks 7 месяцев назад

    Pls make a video on session update when we update user details in database

  • @GhulamRasool-kr4ld
    @GhulamRasool-kr4ld 7 месяцев назад

    Can you create a video on how to build and deploy a production-ready application on AWS, including how to export output data? I've been struggling with this for the past few days.
    #nextjs
    #production
    #build

  • @carloschavezlucero9142
    @carloschavezlucero9142 7 месяцев назад

    Best video ever

  • @abhinasregmi9742
    @abhinasregmi9742 5 месяцев назад

    Middleware I can't seem to make it work properly

  • @mosharafhossain2521
    @mosharafhossain2521 4 месяца назад

    Great job. When destroying session after jwt expired or deleted jwt session from browser for test purposes, is it redirected after clicking logout in the server action?

  • @RuslanGonzalez-ox6vz
    @RuslanGonzalez-ox6vz 7 месяцев назад

    Great Video!

  • @ecodersofficial
    @ecodersofficial 5 месяцев назад

    Error: JWS "alg" (Algorithm) Header Parameter missing or invalid
    Source
    lib.ts (17:38) @ input
    15 |
    16 | export async function decrypt(input: string): Promise {
    > 17 | const { payload } = await jwtVerify(input, key, {
    | ^
    18 | algorithms: ["HS256"],
    19 | });
    20 | return payload;

  • @EvHaus
    @EvHaus 7 месяцев назад

    Thanks for the video. Biggest issue I've run into with this flow is that it seems nearly impossible to kick users out when using JWTs. Would love a video on that. ie. A bad actor signs up for my app and I need to kick them out immediately (faster than the JWT expiry date). How do I do that?

  • @hoanglongluong4355
    @hoanglongluong4355 3 месяца назад

    "Thanks so much!!!"