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...
Always lovely to see official guides on these important topics :)
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
hey there ! just wanted to tell you that your videos are amazing. thank you for your efforts, keep UP the good work
@codewithantonio thank you for your efforts, your work is admirable and helped me alot.
Antonio the goat of web tutorials. Really enjoyed your next-auth v5 tutorial.
Thanks Antonio for your auth tutorial
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.
Looking for this tutorial for months. So nice to have a official tutorial to follow. Thanks!
Nice and concise tutorial on a subject matter that tend to be very tedious and confusing. Great job Lee!
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!
Thanks for Lucia shout out, I've integrated the V3 recently and it was a breeze.
Yup, Lucia is great
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! 👍
Great addition! 🙂
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.
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
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
Would love a video about using OAuth to login with a custom backend and how to refresh a session with your own issued JWT!
Please keep uploading these videos how you have been the last bit I've been really enjoying them and finding them useful
Lee great job. If you could create a video on how Next.JS handles “authentication” -vs- “authorization” that would be awesome.
Thanks Lee….😁👍🏿✨
I have to say the canonical approach (authorization middleware) seems a little too basic but if it works it works.
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.
That's what I expected. Next-auth is already well documented
@@aberba lol
@@aberba it's not good at all.
Awesome stuff! And really appreciate how the Next docs are being filled out to cover these things ❤
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.
Thank you! Smol bug :)
I want to thank you for this excellent introduction to authentication in Next.js
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
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.
seems the first method has gotten me 90% of the way there. 3 days i flapped at this.
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
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!
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. 😁
Just saw the news about the promotion ( a few months after it happened ) -- congrats!
I love to watch videos where the focus is on proper documentation
Спасибо! В документации не нашел примера нужного, а тут стало понятнее.
Wow finally, thank you for this video. This really helped my understanding of how to implement my auth flow!
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
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.
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.
How to use updateSession() for jwt accessToken and refreshToken
You have no idea how helpfull is this video to me. Thanks a lot for an insightful explanation and for the amazing content
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.
look at this how awesome. giving lightweith version of topic is really good. thanks man
Great video! Can't wait to see the full guide on the updated next-auth lib!
Awesome video, congrats! Specially due to explanation of the missing sign in part that is not in the Next.js docs. Thank you.
Bravo Lee and Balázs! I just copied the code, liked it so much!😅
This is more informative beyond nextjs and React... well the first example 😊😊
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.
Thanks ! we need more content about authentification. Very usefull topic.
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!
This was incredibly insightful, thanks Lee
can someone help why do we get null value in the email area
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.
Exactly what I've been waiting for
This is what I have been waiting for. thanks!
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).
God bless you. I couldn't figure out just how to do exactly that
Vercel Auth would be great to complete with clerk, auth0. Something built-in and easy to use / deploy.
this tutorial is my life saver, thanks a lot lee!
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.
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.
Nextjs & discord auth would be awesome, extending the Session, modify the callbacks etc
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
Thank you for a basic tutorial
The guide is so useful. Thanks a lot!
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 :(
I tryed next-auth, authjs, but this satisfied what I was looking for. thanks
Yes we would like to talk more . Authorization
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.
This is very helpful, Great !!!
Great video.. a deep dive using supabase auth will be helpful
Can this be done as easily on the pages router? Does anyone have a video or example of this? Thanks
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
Can I access the token or session from client side component. because I think httponly cookie don't access from client side.
finally an official guide!!!
Thanks for the most needed content ❤
This was great. Thank you
would be great if there is an example with service worker.
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.
Thanks Lee, always helpful!
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?
Pretty good video, as usual!
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)
You don't need to use JWTs but it's something I get asked about frequently since many people do!
That's just your opinion.
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.,)
More of this you ask? Yes, please 🧠👍
We want full client(User) + admin authenctication tutorial including role based auth and routes for admin.
doesnt auth.js v5 handle encryption and sigining of jwt by default? why are you manually doing it?
Thanks for the tutorial!
No database session in nextAuth credentials strategy, hence why i prefer Lucia Auth
Thanks a lot Lee, This was really helpfull
Worth its weight in gold!! Nice one, Lee!!
Thanks for this Lee!
Next js is getting more and more unclear regarding the authentication/authorization process
R u serious?
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
What?
This is me right now
Skill issue
thank you for the repo, mate
Why is email 'null'? Shouldn't the email that was typed in be displayed under the form?
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
im using nextui which uses client" but the login functions use "use server" i get errors tried looking everywhere for a fix 😭😭
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?
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.
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!
I feel your pain
I believe they're working on a new version!
So true
Good to know - it is absolutely overdue - hope it comes soon !@@leerob
Yeah I feel your pain
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?
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
What a awesome tutorial
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
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.
Thank you Lee, very helpfull!
which nextjs version is this? which version should I take for a new project?
Hello, I have a genuine doubt: how can we use clean architecture on Next?
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?
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.
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?
Can you please make a page transition video using next.js v14 with app dir and framer motion? Including exit animation?
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?
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?