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

КОМЕНТАРІ • 46

  • @heniyentertainment
    @heniyentertainment 4 місяці тому +7

    please provide complete repo this is so much useful

  • @nishanthapa2236
    @nishanthapa2236 5 місяців тому +2

    exactly what ive been searching for, amazing yet again

  • @BipulPoudel
    @BipulPoudel 5 місяців тому +4

    Thanks for tutorial! One of the best tutorial for role-based authentication of next-auth. Very helpful!

  • @bipulpoudel3869
    @bipulpoudel3869 5 місяців тому +2

    Nice tutorials! Specially the custom access hooks is much easier to understand and use. Thank you :)

  • @samuelayegbusi3877
    @samuelayegbusi3877 4 місяці тому +1

    This is awesome. The best video I have seen on this topic.

  • @josephfarinloye
    @josephfarinloye 5 місяців тому +1

    Just keeping creating awesome videos like this 🔥👌

  • @rgagankumar5191
    @rgagankumar5191 5 місяців тому +1

    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

    • @DevInteprid
      @DevInteprid  4 місяці тому

      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.

  • @iamronish007
    @iamronish007 5 місяців тому +1

    Insane hai insane

    • @DevInteprid
      @DevInteprid  5 місяців тому

      Thank you for your comment. Much appericated.

  • @morshedulislamriaad6496
    @morshedulislamriaad6496 4 місяці тому +1

    Good explanation.

  • @Tech-VMastermind
    @Tech-VMastermind 5 місяців тому +1

    Nice tutorial sir

  • @kidzoona6032
    @kidzoona6032 2 місяці тому

    Nice tutorials, may i ask what backend and http client did u use?

  • @larrymcfarlane6202
    @larrymcfarlane6202 3 місяці тому +1

    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. 🙂

    • @DevInteprid
      @DevInteprid  3 місяці тому

      Thank you for your comment :)

  • @abdarker1043
    @abdarker1043 5 місяців тому +1

    really good video. but which next-auth version are you using?

    • @DevInteprid
      @DevInteprid  5 місяців тому

      Thank you for your comment. I am using next-auth 4.24.5

  • @JeetPatel-xd3cw
    @JeetPatel-xd3cw Місяць тому

    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.

  • @naylord5
    @naylord5 4 місяці тому +1

    Excelent video mate! 🔥
    Could you please consider to update this guide but with server actions?
    Thank you in advance! 😊

    • @DevInteprid
      @DevInteprid  4 місяці тому

      Thank you for your comment. Will add a new video soon then :)

  • @JulioGarcia-yc3kl
    @JulioGarcia-yc3kl 5 місяців тому +1

    nice!!!!!

  • @elsonjunior2112
    @elsonjunior2112 4 місяці тому +2

    My friend, can you share the complete code on Github? The provided link has only 4 files. Thank you

    • @DevInteprid
      @DevInteprid  4 місяці тому

      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

  • @BkDev23
    @BkDev23 3 місяці тому

    Nice Job, Please can you provide the completed repo link ?

  • @darawan_omar
    @darawan_omar 4 місяці тому +1

    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 ?

    • @DevInteprid
      @DevInteprid  4 місяці тому

      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?

    • @darawan_omar
      @darawan_omar 4 місяці тому +1

      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 ?

  • @mdsafikulislam9113
    @mdsafikulislam9113 3 місяці тому

    Is it Server Actions or API?

  • @munkh-erdenez2117
    @munkh-erdenez2117 3 місяці тому +1

    Do you know how it is done in next-auth v5?

    • @DevInteprid
      @DevInteprid  3 місяці тому

      I am not sure, I have to look into it for now.

  • @nishanthapa2236
    @nishanthapa2236 4 місяці тому +1

    killer

  • @johnaroj
    @johnaroj 4 місяці тому +2

    can you share the whole repo?

    • @DevInteprid
      @DevInteprid  4 місяці тому

      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

    • @kanojvora2491
      @kanojvora2491 4 місяці тому

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

    • @DevInteprid
      @DevInteprid  4 місяці тому

      Hi, do you want to connect? I can try to see if I can help

    • @johnaroj
      @johnaroj 4 місяці тому +1

      @@DevInteprid i figured alot out already. I just wanted to see how this project was structured. But i could figure it out

  • @deepakyadav-ri2fv
    @deepakyadav-ri2fv 2 місяці тому

    Hi, I want to connect with you but how ?

    • @DevInteprid
      @DevInteprid  2 місяці тому

      Hi, you can email me on bipulpoudeldev@gmail.com