Role-based Authentication in Next 14 using Next-Auth | App Router | Protected Routes | Custom Hooks
Вставка
- Опубліковано 20 лип 2024
- 🔒 Welcome to my comprehensive guide on implementing user-based role authentication in Next.js 14 using the Next-Auth library! In this tutorial, I'll take you on a coding journey where we explore the intricacies of setting up protected routes with middleware in Next.js 14.
👨💻 What's Inside:
- A step-by-step walkthrough of the code to help you understand how to protect your routes using middleware in Next.js 14.
- Creation of a custom hook to efficiently manage authentication states and permissions.
- Techniques for dynamically showing and hiding components based on user permissions, enhancing the user experience and security of your app.
- A detailed explanation of how to structure your database, focusing on users and roles entities to support a robust authentication system.
- Real-world examples and best practices to help you grasp the concepts quickly and effectively.
🔗 Resources:
- [github.com/dev-inteprid/role-...] - Access the complete project code and resources to help you follow along and implement these features in your own project.
🚀 By the end of this video, you'll have a solid understanding of how to implement sophisticated user-based role authentication in your Next.js 14 applications. Whether you're building a small project or a large-scale application, these skills are essential for creating secure and user-friendly web applications.
💡 Don't forget to like, share, and subscribe for more videos on web development and Next.js tips!
#NextJs #NextAuth #WebDevelopment #JavaScript #RoleBasedAuthentication #Middleware #UserPermissions #CodingTutorial #WebSecurity
please provide complete repo this is so much useful
exactly what ive been searching for, amazing yet again
Thank you :)
Thanks for tutorial! One of the best tutorial for role-based authentication of next-auth. Very helpful!
Glad it was helpful!
Nice tutorials! Specially the custom access hooks is much easier to understand and use. Thank you :)
Glad it was helpful!
This is awesome. The best video I have seen on this topic.
Glad you liked it!
Just keeping creating awesome videos like this 🔥👌
Thanks! Will do!
Awasome 🎉❤ it's complex yet you made it simple.
We need more content like this.
Particularly i got more interesting in how you have structured and crud operations in UI, with all dynamic routes, usemutations etc. stuff.
please please please please please please please please make video on it. it's much needed topic of, how to perform CRUD operations in optimal way
Thank you so much 😀. I am abit busy for few weeks because of traveling. Will add video as soon as possible. Thank you for recommendation.
Insane hai insane
Thank you for your comment. Much appericated.
Good explanation.
Glad you liked it
Nice tutorial sir
Thank you
Nice tutorials, may i ask what backend and http client did u use?
Nice! All I see are role based videos here and there. It's fun to see a post regarding permissions and potential policies within a role...I'm assuming these are stored in a JSON field in your table? I didn't catch your schema...Woops, nm i just went back and caught it. 🙂
Thank you for your comment :)
really good video. but which next-auth version are you using?
Thank you for your comment. I am using next-auth 4.24.5
You did great job for this app router, where i was getting confuse, bcos I know what to do for achieve this but how to implement this in new app router was big confusion. Grate Job.
i have done almost similar thing using CASL library in my old next project(page router, not app router). what i have done different is:
const MyProductPage = () => {
....component code here
}
// below is access control object for this component. and all role and permissions is already comming from DB with user login so i build ability context for later use like hide/show button or nav menu or other thing and can also do access denied kind of stuff.
MyProductPage.acl = {
action: permissions.VIEW, ---> 'view'
subject: modules.product ---> 'product'
}
export default MyProductPage
and i created permission check wrapper and wrap whole app. there is lot more but you will get idea.
Excelent video mate! 🔥
Could you please consider to update this guide but with server actions?
Thank you in advance! 😊
Thank you for your comment. Will add a new video soon then :)
nice!!!!!
Thank you! Cheers!
My friend, can you share the complete code on Github? The provided link has only 4 files. Thank you
Unfortunately, it’s a client project, so I cannot share complete code, what do you need? If you let me know, will add it to link
Nice Job, Please can you provide the completed repo link ?
how we can do that if user want to visit that page that is not have access it or permission it to visit it directly logout by using the function signOut of next-auth ? please help me how we can do that ?
I guess you could clear next auth session, for logging out?? Or redirect user to logout page which has useEffect with logout function? I guess both of this methods work?? Let me know, if this helps?
import { auth } from "@/auth";
// import { signOut } from "next-auth/react";
import { authRoutes, apiAuthPrefix, DEFAULT_LOGGIN_REDIRECT } from "@/routes";
import { notFound, redirect } from "next/navigation";
import { NextResponse } from "next/server";
import { signOut } from "next-auth/react";
export default auth(async (req) => {
const isLoggined = !!req.auth;
const { nextUrl } = req;
// const userPagePermission = req.auth?.user.user_permissions;
const userPagePermission = ["main", "sale_a", "users", "my_debts"];
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isAccess = userPagePermission.includes(nextUrl.pathname.split("/")[1]);
// console.log(nextUrl.pathname.split("/")[1]);
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLoggined) {
return Response.redirect(new URL(DEFAULT_LOGGIN_REDIRECT, nextUrl));
}
return;
}
// if (isAccess) {
// console.log("access it");
// return;
// }
// if (!isAccess) {
// // signOut();
// // redirect("/not-access");
// // console.log("not access");
// }
if (!isLoggined) {
// return Response.redirect(nextUrl.origin + "/login");
return NextResponse.redirect(new URL("/login", req.url));
}
return;
});
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};...................................................this is my code in the condition not isAccess clear the session when clear the session it will return the user to login automaticlly , but i do not know how do that the both method signOut not working in the condition !isAccess give me the sloution please ?
Is it Server Actions or API?
Do you know how it is done in next-auth v5?
I am not sure, I have to look into it for now.
killer
can you share the whole repo?
Hi there, unfortunately cannot as it’s a client project. Can you tell me what you wanted to know? I can create a new video
@@DevInteprid Can you share how you did post requests with CSRF tokens? Been trying to figure out how to get this done securely. I have an example:
const csRes = await fetch(`localhost:3000/api/auth/csrf`)
const resCS = await csRes.json()
console.log('rescs', resCS)
const csrfToken = resCS.csrfToken
const res = await fetch(`localhost:3000/api/users/getAll`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken,
},
credentials: 'include',
body: JSON.stringify({ userId, csrfToken }),
});
For some reason, this isn't secure (getting a CSRF vulnerability when running it through a scanner), any advice?
Hi, do you want to connect? I can try to see if I can help
@@DevInteprid i figured alot out already. I just wanted to see how this project was structured. But i could figure it out
Hi, I want to connect with you but how ?
Hi, you can email me on bipulpoudeldev@gmail.com