How to Manage User Roles in NextJS / NodeJS

Поделиться
HTML-код
  • Опубликовано: 7 сен 2024
  • In this video, we'll look at how to manage user roles in NextJS or NodeJS. By understanding how user roles work, you'll be able to specify which role is able to access exactly which pages in your application.
    We'll cover topics like creating user roles, assigning user roles, and managing user access. By following this video, you'll be able to manage user roles according to your specific role requirements and access-levels.
    My GitHub: github.com/jos...
    Wishing you lots of fun building your own cool stuff with this knowledge!

Комментарии • 109

  • @daheck81
    @daheck81 Год назад +39

    You might be interested in isomorphic authorization with something like CASL where you build abilities instead of relying on roles for example. Would be cool if you could give it a take

    • @TheBuddilla
      @TheBuddilla Год назад

      Thank you for this, I was looking for something that was more synonymous with *nix type permission structures.

  • @freakinmonkey85
    @freakinmonkey85 Год назад +5

    The main purpose of JWT is that the system can generate a token that lasts for a certain amount of time. The JWT callback is called whenever session needs to use a token, that means that in your code, because you start out with making a database call in the jwt callback, you will have a lot of redundant calls to the database. You should refactor this to only refetch data as needed, eg. whenever an update trigger is called, or when time since last fetch is over a certain threshold. The jwt will still return the user role, but the amount of db calls will be several order of magnitudes lower.

    • @bnssoftware3292
      @bnssoftware3292 4 месяца назад +3

      But what about real time role changes? If you get a token with a certain role and that role is revoked, the user may still have access based on the role in the token until it expires, right? That's not good.

  • @casual_xyz
    @casual_xyz Год назад +8

    big fan from Brazil, I learn a lot from your videos, keep it up my man, gj!

  • @murtadanazar
    @murtadanazar Год назад +27

    Hello Josh, can you do a simple course consisting of a full stack using Next jS and Prisma, Next Auth, and explain most of the basic concepts such as accessing data by role

    • @joshtriedcoding
      @joshtriedcoding  Год назад +30

      Good idea man.

    • @techworld3043
      @techworld3043 Год назад +2

      @@joshtriedcoding waiting

    • @joshtriedcoding
      @joshtriedcoding  Год назад +12

      @Google Personal 1. Create all possible user roles in your database and assign a default one to every user;
      2. Whenever a user logs in, fetch their role from the database and put it into their JWT
      3. Whenever you want to check the user's role, decrypt their jwt and check the role property in there
      that has worked well for me

    • @keremeersoy
      @keremeersoy Год назад +1

      @@joshtriedcoding I definitely need a tutorial like this

    • @James-the-elder
      @James-the-elder Год назад

      ​@@joshtriedcoding this is what I do

  • @abdullah_mufti
    @abdullah_mufti Год назад +4

    I love they way you teach.
    Watched your 5 hour video on fullstack with nextjs. I request you to create a video on boilerplate repo for nextJS13 app. Where
    1. Dashboards for different users are developed.
    2. Authentication and route protected and pucblic are maintained.
    3. Authetication on client-side and Serverside sessions
    4. File handling /storage

  • @akadaygame8634
    @akadaygame8634 Год назад +1

    thank you for sharing this one. your explanation is really great..
    db -> next-auth jwt() -> next-auth session()..

  • @harsh_vish
    @harsh_vish Год назад

    I have also done, User Roles, I was working on the backend, so I used middleware for that, this was very new concept for me, so I did a little research on this and I found out about middleware, as I was new in this I was able to deliver this within a week, and the result was great

  • @shreyasvaidya9552
    @shreyasvaidya9552 Год назад +1

    You made this concept very easy to understand. Thank you Josh 😃

  • @yo1414
    @yo1414 Год назад +2

    Very helpful videos! Thank you for your time!

  • @StephanHaloftis
    @StephanHaloftis 11 месяцев назад

    I would say this is a very clean approach.

  • @waykingas
    @waykingas Год назад +1

    Simple and clean ❤. You became a strong tutor!

  • @mikoo1991
    @mikoo1991 Год назад +2

    how did you implement showing the error template component that comes after throwing an error?

  • @logistics_guy
    @logistics_guy Год назад +1

    Hi Josh, a tutorial about NextAuthJS and Next-Intl would be perfect

  • @freddy_254
    @freddy_254 Год назад

    Nice one Josh. Appreciate your content. You make it make sense.

  • @Luka_brx
    @Luka_brx Год назад

    Video request. It would be cool if u make video about places where u deploy your website, database, where do u buy domains and so. thanks on the great content, and make discord plsss

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      That is a really good idea too thanks for suggesting (and edit): Yes, discord soon

  • @aymenbachiri-yh2hd
    @aymenbachiri-yh2hd 2 месяца назад

    Very helpful

  • @lennartl.4588
    @lennartl.4588 Год назад

    Genau das was ich gesucht habe. 👍

  • @cheronecom
    @cheronecom Год назад +1

    Would have been nice to have more than 1 role assigned like user and manager.

  • @jimshtepa5423
    @jimshtepa5423 Год назад +2

    is checking the value of role against 'admin' string happens on the client? if so is it not possible to open dev tools and change this statement such that it evaluates to true and the component renders data even if the role is not admin?

  • @speedster784
    @speedster784 Год назад +1

    Would be nice if you do a full stack application where you mainly focus on authentication and can implement email verification using next auth without using the credentials provider and also resetting password via email verification.

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      Email verification is definitely an interesting one

  • @timmoran1613
    @timmoran1613 Год назад +1

    Hey Josh, I might need to watch this video again more closely, but how is the getServerSession method getting that extra role information? That method getServerSession gets the session stored in the DB doesn't it. Using the strategy: 'jwt' makes everything stored in the cookie rather than DB session I thought?

  • @ZiaCodes
    @ZiaCodes Год назад +1

    Hey josh, could you make a tutorial on mssql connected with nextjs? I have already connected but I think you can improve the code quality and some complex understandings...

  • @giannifed
    @giannifed Год назад +1

    Thank you for your video. I don't understand. If I have the user with getServerSession, Why can't I do a search directly in the database to find the user's role without putting it in jwt and session? I would be sure that the user is enabled without waiting for the token to expire.

    • @luca4479
      @luca4479 Год назад

      You can but puts extra strain on server

  • @liebebilder3529
    @liebebilder3529 7 месяцев назад

    Could you please make a video of vendor, user, admin dashboard with booking, cancellation , room reserved , etc

  • @user-vv5kp2ob1k
    @user-vv5kp2ob1k Год назад

    Can you make a video with your vscode extensions and configuration? It will be really helpful, thanks!

  • @isaachatilima
    @isaachatilima Год назад

    Hi Josh, your videos are always good to watch and learn from. When you are free, are you able to make a web app back and front end with role-based authentication using prisma as here? I will buy the coffee.

  • @nasko235679
    @nasko235679 3 месяца назад

    The issue I'm having is that whenever I change the user's role in real time from my DB they still hold on to their old role inside the JWT session. How do I do real time checking? Do I need to query my database and compare?

  • @amur_
    @amur_ Год назад

    How do you implement the sign up for an admin? This video shows how to access the role of the account. But how can i assign the role during the sign up process using next auth?

  • @altaysimsek8304
    @altaysimsek8304 Год назад +1

    Hi Josh, could you please make video about how to use both google,github providers etc. and credentials provider with prisma ? Or do you have any resource

    • @altaysimsek8304
      @altaysimsek8304 Год назад

      because I'm confusing about how to create a prisma schema which is contains additional data like password, fullnames when we are using recommended schema from next-auth

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      ​@@altaysimsek8304 Your database and your auth providers are two completely separate things that don't rely on each other. For example, using google for auth can be done just the same with a Redis database as with Prisma

  • @ahmedaq9018
    @ahmedaq9018 8 месяцев назад

    this guy is amazing ❤‍🔥❤‍🔥❤‍🔥❤‍🔥❤‍🔥

  • @Shahbaaz.28
    @Shahbaaz.28 Год назад +1

    Thank you for this but is there any other approach to achieve that like a protected route. so we can add multiple route

    • @JulianKingman
      @JulianKingman 2 месяца назад

      you should be able to use a layout file to accomplish that

  • @germantellez2710
    @germantellez2710 Год назад +1

    Hi Josh, is it secure to send request to the database in the jwt callback? without token or secrets or something like that? it seems to be public

    • @xdneos
      @xdneos Год назад

      It happens on the server section, remember that nextJS is a node framework so it runs a server to manage all these things like middlewares, api calls etc

  • @zettai8087
    @zettai8087 9 месяцев назад

    Cool but can we create an interface to set the role? Like include a role field in a SignUp page for only admins for example.

  • @kemoboy
    @kemoboy Год назад

    So, is this simple? I'm overcomplicating a lot of things when it comes to authentication. I was thinking, for my new app, to just make a request each time to the db and check what the user has access to or not, but seeing this, this is way simpler.

  • @chinwubachukwudi4483
    @chinwubachukwudi4483 Год назад

    you're the best man!

  • @SharunKumar
    @SharunKumar Год назад

    I used t3 app for my uni project but I used SQLite for my db, and at the time prisma complained that enums can't be done in SQLite :(
    Idk if they've polyfilled it now though

  • @notfadeaway6617
    @notfadeaway6617 Год назад +1

    i kind of feel this is a design pattern. do you know the name?

  • @mubashirwaheed474
    @mubashirwaheed474 11 месяцев назад

    Josh great but how should we approach the creation of super admin?

  • @egretfx
    @egretfx Год назад

    but what if am using Clerk, and i want to have an admin role and a user role...?

  • @haryanvideveloper582
    @haryanvideveloper582 Год назад

    Hey do you know any github repo that has example for handling dynamic roles (like based on role and crud permission dashboard will be customised) in MERN stack ? or if you could suggest something

  • @samking618
    @samking618 11 месяцев назад

    Just like you protected the /dashboard route, can we protect the nested routes like /dashboard/a , /dashboard/b etc without using getServerSession on every page?

    • @trace6585
      @trace6585 10 месяцев назад

      Yes, wrap it in the layout

  • @qcode_co
    @qcode_co Год назад

    the jwt callback is called several times, I don't see optimal to consult the role in this callback.

  • @MRtorki55
    @MRtorki55 11 месяцев назад +1

    Using middleware is simpler and more efficient

  • @1chbinamin
    @1chbinamin Год назад

    3:50: If you only have 2 enums, wouldn't be easier to just put a boolean in model User indicating whether it is an admin or not?

    • @joshtriedcoding
      @joshtriedcoding  Год назад +1

      In this case that would be equally as good. The enum allows for way more flexibility if you'd like to add additional roles later on though

  • @belkocik
    @belkocik Год назад

    Have you uploaded a video where you have been showing how to implement session logic?

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      Not sure what you mean by that

    • @belkocik
      @belkocik Год назад

      ​@@joshtriedcoding I mean did you make a video where you show how to handle JWT authentication or session in React/NodeJS apps?

  • @4twi352
    @4twi352 Год назад

    What if you don't use NextAuth for whatever reason or you have different back-end or adapter that isn't directly supported by NextAuth?

    • @joshtriedcoding
      @joshtriedcoding  Год назад +2

      This is not next-auth specific. The important thing is that you depict possible user roles in your database, retrieve those on login, and store them in a JWT or server-side session to access throughout your app. That can be done in whichever framework and database you like, I just happen to use PostgreSQL. All an adapter does is receive user data and put it into your db, you could write that logic yourself

  • @alleneben8144
    @alleneben8144 Год назад

    Please how were you able to implement the fallback page when you threw new Error?

    • @zivtamary
      @zivtamary Год назад

      next.js 13 - error.tsx page. automatically catches error (using error boundaries)

  • @wakibtz7134
    @wakibtz7134 Год назад

    Hello Josh! I have a problem with Next Auth middleware. I can not find answer in internet. When i make simple next auth code and then try use middleware i get error:
    ./node_modules/next-auth/next/middleware.js
    Module parse failed: Identifier 'NextResponse' has already been declared (3:6)
    | "use strict";
    | const NextResponse = require("next/dist/server/web/spec-extension/response").NextResponse;
    > const NextResponse = require("next/dist/server/web/spec-extension/response").NextResponse;
    I tried rewrite code from begin but i still get it. If u have a time or know how to solve this problem, can u help me pls?

  • @firewatermoonsun
    @firewatermoonsun 9 месяцев назад

    Can i implement when user has 2 roles?

  • @user-de6bt9uu1e
    @user-de6bt9uu1e Год назад

    is there any alernative way of checking the role from session in the component like using protected routes or something instead of checking the session in every page

    • @velhoguidsd
      @velhoguidsd Год назад

      NextJS is "server first" so it is not a good practice to do this. But you can do the "old" react way using context and wrapping the components with another component to check the credentials first.

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      Context works fine, middleware is a great alternative where you can decrypt and validate the token for each route you wish to protect

  • @amr3162
    @amr3162 Год назад

    was expecting something a bit
    more advanced than this

  • @enucar
    @enucar Год назад

    Laravel Breeze 💪

  • @gabrielbianchi2246
    @gabrielbianchi2246 11 месяцев назад +16

    Remember kids: if authentication happens in the client, then you don’t have auth. Have a good night

    • @diptabose7187
      @diptabose7187 5 месяцев назад +14

      Page.tsx ( which he used in the video ) in NextJS is by default a server side component. Have a good day.

  • @AlfonsusAC
    @AlfonsusAC Год назад

    Good video

  • @kidzoona6032
    @kidzoona6032 Год назад

    thanks finally found what i needed.. can u share the code pleasee

  • @user-ld1de1mc4h
    @user-ld1de1mc4h Год назад

    How did you do the Error page that catches the error messages?

    • @junaidali1966
      @junaidali1966 5 месяцев назад

      my question is also the same

  • @nolep5555
    @nolep5555 Год назад

    please make video about magic link auth (no password require) vs normal email and password verification with send verification token to user

  • @Costa_Nj
    @Costa_Nj Год назад

    Hey Josh! I tried your solution! JWT callback triggered multiple times after refresh page and every call triggered db request, that is not too good! Do you have the same problem? Any ideas how to fix it?

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      Might be due to react strict mode, shouldn't be that way in production. You can disable strict mode locally in either your plain react index file or in the nextjs config for nextjs

    • @Costa_Nj
      @Costa_Nj Год назад +2

      I didn't find the reason of multiple callbacks, but I realized, that we don't need to make a request, cause we have user as callback argument (only available on sign in). So, to add role inside token, we just need:
      jwt({ token, user}) {
      if(user) {
      token.role = user?.role
      }
      }

  • @kalpadhwaryu7929
    @kalpadhwaryu7929 Год назад

    Nice

  • @hn3m3s1s
    @hn3m3s1s Год назад

    beautiful

  • @0b3ryn29
    @0b3ryn29 Год назад

    can't find the github repo. wanted to check why there was a Session Model in schema.prisma. I thought if the next-auth strategy being used was jwt, there was no longer a need to store the session in the DB.

  • @Chris...S
    @Chris...S Год назад

    Hey Josh, I'm guessing this technique wouldn't work if you wanted an Admin to add additional roles. How would you go about that?

  • @tausifkhan6539
    @tausifkhan6539 9 месяцев назад

    #josh in my nextjs project i have two type of components on for mobile and second for desktop so what i want i want to use "userAgent" and render component based on user device type this is my nextjs project middleware file code [import { NextRequest, NextResponse, userAgent } from 'next/server'

    export function middleware(request: NextRequest) {
    const { device } = userAgent(request)
    const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'

    request.nextUrl.searchParams.set('viewport', viewport)
    return NextResponse.rewrite(request.nextUrl)
    }] so please meke on video on this topic how to i render component based on user device type i mean if user come from mobile then i want only load mobile component from server and render so how to i do that in my nextjs 13 app directory project please make video on this topic

  • @isis8719
    @isis8719 Год назад

    Ty!

  • @27sosite73
    @27sosite73 Год назад

    source code would be awesome to have

  • @solomonogu1393
    @solomonogu1393 Год назад

    Setting defaults in a database is not a good idea, especially performance wise

  • @ayushgogna9732
    @ayushgogna9732 Год назад

    amazing video can you share the code ?

  • @haydenthai935
    @haydenthai935 Год назад

    can you please link the code

  • @hawadota2
    @hawadota2 Год назад

    teach roles and permission pls

  • @dikson7951
    @dikson7951 Год назад

    kevin de bruyne programmer?xd

  • @getporti
    @getporti Год назад +1

    🫰

  • @khawajashowzib1644
    @khawajashowzib1644 Год назад

    Hello brother i think your most of the tutorials are not so beginner friendly, can you please make simpler videos instead of so much complex code videos

    • @joshtriedcoding
      @joshtriedcoding  Год назад

      Trying to make them as beginner-friendly as possible. Anything specific you found too unclear / fast?

  • @rp2804
    @rp2804 Год назад

    Why do you assume we know primsa whatever it is? Why include it in every video but not in title, half of your videos have prisma in it

  • @Grishopping
    @Grishopping Год назад

    discord???