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
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.
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!
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! 👍
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.
I just finished this feature tonight. after that I watched TH-cam and saw that you had made the tutorial. this is such a coincidence. keep up the spirit, Bro. 😁
Great video. Someone asked me why 10 seconds, so figured I'd comment here. Correct me if I have something wrong. Setting it to 10 seconds was just to demo it (although maybe some app has a need for it). Typically you would have a longer (7 days, 30 days, forever) "refresh token" as the cookie that continuously updates a short-lived "access token" that you would put in memory. That token could be 10 seconds, although I think 5 minutes is more common. Depends on the application though. But to anyone reading this, just use NextAuth! Don't play with fire.
Hey there, what you've described is how I'm currently handling my auth process. However, I'm looking to move toward server components and I'm not sure how to store a token in memory, it turns up undefined. Can you shed some light on that? Or, do both tokens have to be stored in cookies/storage when using RSC?
As I see it, when you use JWT you can’t invalidate token. So if you change user roles or simply disable user in database, user session will keep alive as long as JWT is valid. Giving a 10 seconds expiration time you can be sure to keep user data in token allways in sync
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
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.
Thank you !! I've been banging my head against the wall on this for the past 2 hours! More on authentication with auth.js/App/RSC/Google Login please !
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
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 :(
00:01 Basic session authentication in Next.js without additional libraries. 01:15 Authentication process involves login and session creation 02:49 Asynchronous function for encrypting JWT based on payload and algorithm. 04:16 Updating session expiration and cookies for user authentication. 05:51 Implementing minimal session-based authentication in Next.js app. 07:20 Using middleware for refreshing page data 08:51 Authentication and session handling with Next.js App Router 10:15 The Next.js app router authentication is deeply complex.
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.
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).
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?
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.
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
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
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!
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
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.,)
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?
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.
Hi, I'm having a problem using authjs, when the admin deletes the user from the admin dashboard or database, then the user who is deleted should be logged out and their session cookie should be deleted but nextauth is not following that behaviour or maybe I'm not setting things up correctly, so If you have any idea about this then please let me know, and I'm using the "JWT Strategy". Thanks
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.
i got this error below when using getSession() on the middleware and other page. also the cookies is suddenly got deleted in random occassion. although i did the exact same method with your example. node_modules\jose\dist\browser\lib\jwt_claims_set.js (89:18) @ default "exp" claim timestamp check failed
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
I wanted to use Zustand to have my user data and token in a client-side store, the I made my as server component and did the "get token and user" logic there and wrapped the zustand Provider around the children of the component, since I couldn't use layout.tsx because it didn't update I used template.tsx instead is it a bad practice? what should I do? I am using Laravel as my backend service please answer I need your help
hi. how can i import a model in middleware file? i need it for fixing jwt authentication... when I import my user model in middleware, next js return this error. export default mongoose.models.M_User || mongoose.model("M_User", M_user_schema);
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.
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?
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
Great video 👍👍 It would much helpful if you make a detailed video on authentication using lucia, I'm really confused as they havn't completed its documentation yet. Many of the sections just say "work in progress".
The website I'm working on uses Akamai as the first cache layer to cache the HTML response. In this case, the login mechanism must be handled client-side to avoid security issues and data leaks right? Does this prevent me from managing the session server-side?
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?
Hi, do i need a contextProvider with api request for logout button to work or even to show session informations on 'use client' navbars ? Or are you forced to write a ?
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.
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?
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?
Sadly this doesn't work for me in version 13.5. I need to make sure the user loses the session when he closes the app but I couldn't find any guide on that.
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.
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!
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!
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
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.
Please keep uploading these videos how you have been the last bit I've been really enjoying them and finding them useful
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.
Awesome stuff! And really appreciate how the Next docs are being filled out to cover these things ❤
Finally, an easy tutorial explaining Next Authentication using Jose. Well done. I;m a new subscriber.
I just finished this feature tonight. after that I watched TH-cam and saw that you had made the tutorial. this is such a coincidence. keep up the spirit, Bro. 😁
Great video. Someone asked me why 10 seconds, so figured I'd comment here. Correct me if I have something wrong. Setting it to 10 seconds was just to demo it (although maybe some app has a need for it). Typically you would have a longer (7 days, 30 days, forever) "refresh token" as the cookie that continuously updates a short-lived "access token" that you would put in memory. That token could be 10 seconds, although I think 5 minutes is more common. Depends on the application though. But to anyone reading this, just use NextAuth! Don't play with fire.
Hey there, what you've described is how I'm currently handling my auth process. However, I'm looking to move toward server components and I'm not sure how to store a token in memory, it turns up undefined. Can you shed some light on that? Or, do both tokens have to be stored in cookies/storage when using RSC?
As I see it, when you use JWT you can’t invalidate token. So if you change user roles or simply disable user in database, user session will keep alive as long as JWT is valid. Giving a 10 seconds expiration time you can be sure to keep user data in token allways in sync
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!
that would be great! fingers crossed
Just saw the news about the promotion ( a few months after it happened ) -- congrats!
congratz you managed to take something relatively simple and complicate more than it needs to be for no reason...
I want to thank you for this excellent introduction to authentication in Next.js
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.
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.
Thank you !! I've been banging my head against the wall on this for the past 2 hours! More on authentication with auth.js/App/RSC/Google Login please !
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
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.
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 love to watch videos where the focus is on proper documentation
look at this how awesome. giving lightweith version of topic is really good. thanks man
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 :)
You have no idea how helpfull is this video to me. Thanks a lot for an insightful explanation and for the amazing content
Great video! Can't wait to see the full guide on the updated next-auth lib!
Great neat straight to the point explanation. Love it!
Спасибо! В документации не нашел примера нужного, а тут стало понятнее.
Wow finally, thank you for this video. This really helped my understanding of how to implement my auth flow!
Love that you did this without libs 🙌
can someone help why do we get null value in the email area
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 :(
00:01 Basic session authentication in Next.js without additional libraries.
01:15 Authentication process involves login and session creation
02:49 Asynchronous function for encrypting JWT based on payload and algorithm.
04:16 Updating session expiration and cookies for user authentication.
05:51 Implementing minimal session-based authentication in Next.js app.
07:20 Using middleware for refreshing page data
08:51 Authentication and session handling with Next.js App Router
10:15 The Next.js app router authentication is deeply complex.
Bravo Lee and Balázs! I just copied the code, liked it so much!😅
El mejor video que he visto. The best video I have ever seen.
Can I access the token or session from client side component. because I think httponly cookie don't access from client side.
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 video, congrats! Specially due to explanation of the missing sign in part that is not in the Next.js docs. Thank you.
Thanks ! we need more content about authentification. Very usefull topic.
Can this be done as easily on the pages router? Does anyone have a video or example of this? 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).
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?
Why do you do:
const session = request.cookies.get('session')?.value
and don't:
const session = (await cookies()).get('session')?.value;
This is more informative beyond nextjs and React... well the first example 😊😊
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.
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
How to use updateSession() for jwt accessToken and refreshToken
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
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!
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
This was incredibly insightful, thanks Lee
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.,)
This is what I have been waiting for. thanks!
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?
Great video, would love to learn more about auth!
which vscode theme is this?
Yes we would like to talk more . Authorization
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.
im using nextui which uses client" but the login functions use "use server" i get errors tried looking everywhere for a fix 😭😭
Hi, I'm having a problem using authjs, when the admin deletes the user from the admin dashboard or database, then the user who is deleted should be logged out and their session cookie should be deleted but nextauth is not following that behaviour or maybe I'm not setting things up correctly, so If you have any idea about this then please let me know, and I'm using the "JWT Strategy". Thanks
Sounds like hell, did you figure it out?
@@shadowB33 nah, moved to lucia lol
@@maliksidk19 no time to waste 😂
@@maliksidk19lucia is so good and so simple for real
doesnt auth.js v5 handle encryption and sigining of jwt by default? why are you manually doing it?
Thanks for the tutorial!
Exactly what I've been waiting for
It's been 9 months since the making of this video & Next Auth v5 (aka auth.js) is still in its shitty dev phase. thanks a lot Clerk! 😠😠
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.
which nextjs version is this? which version should I take for a new project?
i got this error below when using getSession() on the middleware and other page. also the cookies is suddenly got deleted in random occassion.
although i did the exact same method with your example.
node_modules\jose\dist\browser\lib\jwt_claims_set.js (89:18) @ default
"exp" claim timestamp check failed
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
Awesome! I was looking for this explanation, thanks!!
Hi Lee,
How to do webpack config.externals.push('aws-iot-device-sdk-v2'') in Nextjs app?
what theme do you use please
I wanted to use Zustand to have my user data and token in a client-side store, the I made my as server component and did the "get token and user" logic there and wrapped the zustand Provider around the children of the component, since I couldn't use layout.tsx because it didn't update I used template.tsx instead
is it a bad practice? what should I do?
I am using Laravel as my backend service
please answer I need your help
hi. how can i import a model in middleware file?
i need it for fixing jwt authentication...
when I import my user model in middleware, next js return this error.
export default mongoose.models.M_User || mongoose.model("M_User", M_user_schema);
at 10:00, what if I want to use more middleware and not just export auth as the only one?
this tutorial is my life saver, thanks a lot lee!
I tryed next-auth, authjs, but this satisfied what I was looking for. thanks
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;
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.
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?
As i anderstand we does not have barear token anymore, that is we use to keep in localstorage? (Access token)It only session? (Refresh token).
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
Great video 👍👍
It would much helpful if you make a detailed video on authentication using lucia, I'm really confused as they havn't completed its documentation yet. Many of the sections just say "work in progress".
The website I'm working on uses Akamai as the first cache layer to cache the HTML response. In this case, the login mechanism must be handled client-side to avoid security issues and data leaks right? Does this prevent me from managing the session server-side?
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?
with rsc there is only cookies possible? or would it just be more work to send auth header explicitly and verify in middleware but possible?
Hi, do i need a contextProvider with api request for logout button to work or even to show session informations on 'use client' navbars ? Or are you forced to write a ?
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.
Can you please make a page transition video using next.js v14 with app dir and framer motion? Including exit animation?
Pls make a video on session update when we update user details in database
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?
God bless you. I couldn't figure out just how to do exactly that
The guide is so useful. Thanks a lot!
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?
how will this work in case of custom backend, means if i have login api and refresh token API?
Why is email 'null'? Shouldn't the email that was typed in be displayed under the form?
would be great if there is an example with service worker.
Sadly this doesn't work for me in version 13.5. I need to make sure the user loses the session when he closes the app but I couldn't find any guide on that.