We can check if user is sign-in, returning Boolean from authorized Callback, and user's role and rewrite the URL with "/denied" page inside middleware function. So if user's role is "user" and is signed-in, he/she try to visit some protected route, we can rewrite the Url with NextResponse.rewrite("/denied", request.nextUrl). I think it should work.
Thanks this was a great explanation, particularly when you explained part of the sequence in which the callbacks run. Any more on that would be super useful. Also to take things a step further it would be interesting to see how you would implement authorization in a scenario where you are fetching tailored data according not only to the user's role, but also according to attributes within the data itself. A classic example would be a Todo App, where Admin users see everything, but regular users only get to see Todos that are assigned to them, and Managers only get to see Todos where they are the assigned manager.
Okay, let's say a user is already logged, and we want to the user to link to other social media account to connect so maybe for instance we can show that social platform on their profile page. Something like that please.@@hamedbahram
I hope you can make a series of videos about Optimize to increase google speed insight scores. Some common cases include: Fake API from backend, render to Nextjs using swiper slider. Focus on "Eliminate render-blocking resources". This is the most common problem when optimizing. How to asynchronously load CSS while linking CSS files in Nextjs are automatically generated each time you build. If you cannot lazy this CSS and JS file, it will have Eliminate render-blocking resources, affecting LCP and FCP. Thank you bro
how did you assigned role? i mean if user is using google to signin and there are multiple roles and we want user to select one, how we will do that? Currently you already have data i.e role in your db so i couldn't understand. Thanks in advance
@@hamedbahram my question is, nextauth handles role based auth so is there a way when we are using nextauth for registering like Google or email providers, at that time we can assign or user can select role?
Yes, absolutely. You can update the user object in your DB and then update the session using the `update` function returned from the `useSession` hook.
Awesome work ❤ thanks so much for that. I would like to know if you have a blog where you explain that? Also is it possible to make a video how to reset password combine with something like EmailJs
Glad to hear that. I don't have a blog version of this video, but I'll write about it at some point. Password reset is a good topic. I'll have that in mind for future videos.
You kinda skipped over the most important part - how do we implement real-time role changes? This is what I've been stuck on. I've made a nextjs app with latest next auth and it's all great but the issue is the jwt token persist the old user role and even if I change their role if they don't reauthenticate and get a new token it doesn't work. The only way I managed to make it work is by querying the database on each request to compare the db's user role and the session's user role but that doesn't seem scalable at all. This is especially important in apps where you want to ban/deauthorize users in real time. I'm yet to find a guide on how to do it properly without querying the database, if you have any ideas please make a video.
@@hamedbahram The issue is that once the token gets issued I (as an administrator) can't change the user's role. Well I can, but just because it's changed in the database doesn't mean it's affecting the user because they still have their old token. The obvious issue is that I as an admin can't deauthorize an user on demand. This usually gets solved by providing a "refresher token" along with the jwt token but there is 0 documentation on authjs regarding how to implement refresher tokens with credentials provider. So right now every time a user makes a request I query the database and check their role. Imagine 500k users opening 10-20 pages per minute and what kind of db server load that would create. I can't even schedule the db calls to be let's say once every 5 minutes because NextJS is serverless so it doesn't support it.
Instead of handling this in the middleware, what if we create a layout component in the admin folder and use the getServerSession to verify if the user is admin else redirect to a 404 page that gives the user a nice error message and a back button. 🤔
That's also a viable solution. Just keep in mind that you can redirect the user to the same page from the middleware. The benefit of the middleware is that it runs on the edge before the request is completed.
I have created an authentication system in Next.js using NextAuth and protected my route handlers using getServerSessions. However, when I make a fetch request from a client component, my cookies are automatically sent to the backend, and I get authorized. But when I make the same fetch request from a server component, I get unauthorized even I am logged in. Maybe my cookies are not sent automatically . Please reply, why is this happening?
You have to pass the headers to your fetch request. First get the `header` from `next/headers` then pass it to your fetch request like: ``` fetch(endpoint, { method: "GET", headers: headers() } ```
Hi, I am using Laravel APIs with Nextjs, How can I pass authentication bear token to my APIs in Nextjs.(I Just have to protect APIs) Please help me out.
Hello! Can anyone know the solution for this problem Problem: I used google provider in next js. And it is working fine in pc for me. But when I used forward port of vs code to make it possible open website for my friends. But getting error like can't get /api/auth/callback/google Please help me
@@hamedbahram Thank you very much. It worked. I thought it should change only when in production. Thanks again. Have a good day. And wish you a fortune.
I need to have another middleware that includes other pages different than the protected, how can I add the other middleware? In another file, the same file?
Hi there. thanks for recording this video. please make another video with nextAuth and make authorization with phoneNumber. in this case from authOptions we use phoneNumber but is session.user i don't have phoneNumber field... because of this, i asked you to record a video for this problem.. thanks :D
Good question! you can pass the `middleware` function to the `withAuth` function to run the next middleware. I'll create a video on this combining the `next-auth` middleware and the i18n middleware together this coming week.
Looking forward for the next video@@hamedbahram. Btw anyway to run a middleware before the auth in withAuth? cause If you run the middleware inside withAuth it will run after it, if I am not mistaken.
@@hamedbahram 6:46 your saying : "if there is a role on the user object", google does not provide a role property. The only reason you add in your db is because of the Nullish coalescing Then you changed the role manually in the Mongo db to admin. What everyone wants in is this, this will be the ideal case : This is what I'm thinking to implement When signing up using Google, by default it'll be user or admin role (depends on your application) then using a token in the callback url, decode the token in the signin callback and get the role from a token stored table which has the role column, using this update the user table. I don't know if my approach is correct though, couldn't find much resources online to tackle my problem
Sir you are very talented teacher. you followed the different path of teaching web developement.
Thank you!
Man i was on my way writing the same text!!!
We can check if user is sign-in, returning Boolean from authorized Callback, and user's role and rewrite the URL with "/denied" page inside middleware function. So if user's role is "user" and is signed-in, he/she try to visit some protected route, we can rewrite the Url with NextResponse.rewrite("/denied", request.nextUrl). I think it should work.
Yeah that can work, we can rewrite in the `middleware` function.
NextJS redirect or router push id imagine?
Thanks this was a great explanation, particularly when you explained part of the sequence in which the callbacks run. Any more on that would be super useful.
Also to take things a step further it would be interesting to see how you would implement authorization in a scenario where you are fetching tailored data according not only to the user's role, but also according to attributes within the data itself. A classic example would be a Todo App, where Admin users see everything, but regular users only get to see Todos that are assigned to them, and Managers only get to see Todos where they are the assigned manager.
My pleasure! Thanks for the suggestions.
I think you can do it just based the content on the role with useSession() or getServerSession()
Liked this video, would love to see a video on account linking with next-auth(workaround). But thanks again for the tutorial
Sure thing! Can you expand on what you mean by account linking?
Okay, let's say a user is already logged, and we want to the user to link to other social media account to connect so maybe for instance we can show that social platform on their profile page. Something like that please.@@hamedbahram
Thank you for your video , You are teaching developers everyday , How can someone use AuthJs , with a custom backend
You're welcome. I'll create that video at some point.
Another great video, Thanks Hamed.
My pleasure!
I hope you can make a series of videos about Optimize to increase google speed insight scores. Some common cases include: Fake API from backend, render to Nextjs using swiper slider. Focus on "Eliminate render-blocking resources". This is the most common problem when optimizing. How to asynchronously load CSS while linking CSS files in Nextjs are automatically generated each time you build. If you cannot lazy this CSS and JS file, it will have Eliminate render-blocking resources, affecting LCP and FCP. Thank you bro
That's such a good idea! I'll definitely work on it. Thanks.
소스코드를 올려주는 당신 너무 좋아요
You're welcome!
how did you assigned role? i mean if user is using google to signin and there are multiple roles and we want user to select one, how we will do that?
Currently you already have data i.e role in your db so i couldn't understand.
Thanks in advance
You can have the admin to assign roles, or an onboarding flow where the user selects the role.
@@hamedbahram my question is, nextauth handles role based auth so is there a way when we are using nextauth for registering like Google or email providers, at that time we can assign or user can select role?
very nice tutorial, one question, can user role be automated and changed after user has purchased some plan using stripe for example?
Yes, absolutely. You can update the user object in your DB and then update the session using the `update` function returned from the `useSession` hook.
Is it possible to handle dynamic privileges for different roles
Can you expand on your question?
Awesome work ❤ thanks so much for that. I would like to know if you have a blog where you explain that? Also is it possible to make a video how to reset password combine with something like EmailJs
Glad to hear that. I don't have a blog version of this video, but I'll write about it at some point. Password reset is a good topic. I'll have that in mind for future videos.
You kinda skipped over the most important part - how do we implement real-time role changes? This is what I've been stuck on. I've made a nextjs app with latest next auth and it's all great but the issue is the jwt token persist the old user role and even if I change their role if they don't reauthenticate and get a new token it doesn't work. The only way I managed to make it work is by querying the database on each request to compare the db's user role and the session's user role but that doesn't seem scalable at all. This is especially important in apps where you want to ban/deauthorize users in real time. I'm yet to find a guide on how to do it properly without querying the database, if you have any ideas please make a video.
That'll make a good example usecase. Is it that the user can change their own roles, or and admin changes someone else's role?
@@hamedbahram The issue is that once the token gets issued I (as an administrator) can't change the user's role. Well I can, but just because it's changed in the database doesn't mean it's affecting the user because they still have their old token. The obvious issue is that I as an admin can't deauthorize an user on demand. This usually gets solved by providing a "refresher token" along with the jwt token but there is 0 documentation on authjs regarding how to implement refresher tokens with credentials provider. So right now every time a user makes a request I query the database and check their role. Imagine 500k users opening 10-20 pages per minute and what kind of db server load that would create. I can't even schedule the db calls to be let's say once every 5 minutes because NextJS is serverless so it doesn't support it.
Instead of handling this in the middleware, what if we create a layout component in the admin folder and use the getServerSession to verify if the user is admin else redirect to a 404 page that gives the user a nice error message and a back button. 🤔
That's also a viable solution. Just keep in mind that you can redirect the user to the same page from the middleware. The benefit of the middleware is that it runs on the edge before the request is completed.
Plz make one video in complete frontend development roadmap with next.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤
Absolutely! Thanks for the suggestion.
Thanks for making this
My pleasure!
I have created an authentication system in Next.js using NextAuth and protected my route handlers using getServerSessions. However, when I make a fetch request from a client component, my cookies are automatically sent to the backend, and I get authorized. But when I make the same fetch request from a server component, I get unauthorized even I am logged in. Maybe my cookies are not sent automatically . Please reply, why is this happening?
You have to pass the headers to your fetch request. First get the `header` from `next/headers` then pass it to your fetch request like:
```
fetch(endpoint, {
method: "GET",
headers: headers()
}
```
@@hamedbahram Thanks ! It worked.
Hi, I am using Laravel APIs with Nextjs, How can I pass authentication bear token to my APIs in Nextjs.(I Just have to protect APIs) Please help me out.
You can use the `headers` or `cookies` function from `next/headers`
@@hamedbahram Please make video on ecommerce with Laravel and Nextjs, I do can not find any video about this on youtube.
Hello! Can anyone know the solution for this problem
Problem: I used google provider in next js. And it is working fine in pc for me. But when I used forward port of vs code to make it possible open website for my friends. But getting error like can't get /api/auth/callback/google
Please help me
You have to update the `NEXTAUTH_URL` env variable and set it to the url you're using to share you project.
@@hamedbahram Thank you very much. It worked. I thought it should change only when in production. Thanks again. Have a good day. And wish you a fortune.
@@KSalvatore Glad to hear that!
I need to have another middleware that includes other pages different than the protected, how can I add the other middleware? In another file, the same file?
Watch this video => ua-cam.com/video/fmFYH_Xu3d0/v-deo.html
Hi there. thanks for recording this video. please make another video with nextAuth and make authorization with phoneNumber. in this case from authOptions we use phoneNumber but is session.user i don't have phoneNumber field... because of this, i asked you to record a video for this problem.. thanks :D
Sure, I'll have that in mind for future videos.
How would you add this auth middleware to the chain from your chaining middlewares video?
Good question! you can pass the `middleware` function to the `withAuth` function to run the next middleware. I'll create a video on this combining the `next-auth` middleware and the i18n middleware together this coming week.
Looking forward for the next video@@hamedbahram. Btw anyway to run a middleware before the auth in withAuth? cause If you run the middleware inside withAuth it will run after it, if I am not mistaken.
@@nomadmack That's right it would run after the `authorize` callback. I'll look into that for the video.
@@hamedbahram This would be awesome! I'm looking forward to see this video. 😊
@@any_account-b6x Absolutely!
Awesome work ❤
Thanks 😄
Your content is great sir sometimes I even think you made a mistake making it free 😅
Thank you for your efforts
Glad to hear that!
Thanks for the video 🇭🇺
My pleasure!
Plz make one video in complete frontend development roadmap with react.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤
For sure, that a good idea! welcome to the channel.
@@hamedbahram waiting for video. I means waiting for a world best front-end development roadmap video. Best of luck hamed ❤️🇧🇩
@@thisishabib744 Thanks! I'll try 🤓
You missed the main part, how to assign users with different roles when doing a google signin?
That's exactly what I explained in the video.
@@hamedbahram
6:46 your saying : "if there is a role on the user object", google does not provide a role property. The only reason you add in your db is because of the Nullish coalescing
Then you changed the role manually in the Mongo db to admin.
What everyone wants in is this, this will be the ideal case :
This is what I'm thinking to implement
When signing up using Google, by default it'll be user or admin role (depends on your application)
then using a token in the callback url, decode the token in the signin callback and get the role from a token stored table which has the role column, using this update the user table.
I don't know if my approach is correct though, couldn't find much resources online to tackle my problem
Awesome bro
Appreciate that.
awesome always :)
Thank you!
I guess the solution closest to the real world would be just hiding the "Admin" menu item.
That's right! However the user might still try to manually access the `admin` route.