How to sync Clerk authenticated users with your own database in NextJS 13?! | Clerk Pt. 2

Поділитися
Вставка
  • Опубліковано 7 вер 2024
  • In this video, we'll be looking at how to sync your Clerk authenticated users with your own database.
    Clerk | Sync data to your backend: clerk.com/docs...
    Clerk Example using NextJS (Pre v13): github.com/cle...
    Svix webhook verification: docs.svix.com/...
    Starting Code: github.com/kav...
    Final Code: github.com/kav...
    ---
    Website: kavin.me
    Blog: livecode247.com
    Github: github.com/kav...
    #nextjs #reactjs #frontend #webdevelopment #javascript #typescript #authentication #clerk

КОМЕНТАРІ • 106

  • @lexsemenenko
    @lexsemenenko Рік тому +20

    Such an incredible tutorial and love the fact you incorporated this to the new route syntax. You are very dedicated and knowledgeable. I can't thank you enough. It was very generous of you to respond to my request.
    Everyone, Let's show our support and help this amazing creator reach more people!

  • @CaleMcCollough
    @CaleMcCollough Рік тому +6

    Thanks bro. I can't believe I learning from a kid who isn't old enough to vote. Big ups. Good jobs. Your parents must be proud of you. I would avoid using multiple branches for demos. It's too complicated to download.

    • @livecode247
      @livecode247  Рік тому

      Haha. Thank you! Noted your point as well. Thank you for the input :)

  • @gabrielschaldach401
    @gabrielschaldach401 Рік тому +8

    Incredible video! I was wondering how to do exactly this.

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

    i will implement this in my nestjs backend with my nextjs frontend, awesome tutorial. appreciate it 🙏🙏

  • @eyadelghobary9093
    @eyadelghobary9093 Рік тому

    Thank you for this, this video was great and I have been trying for so long to do authentication on NextJs without using NextAuthJS.

  • @ViniciusFeitosaDaSilva
    @ViniciusFeitosaDaSilva Місяць тому

    Excelent video. Thanks for sharing!

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

    This tutorial was great and it worked for me. Can you make a video on JWT template which they have? It will be super helpful if you can upload that soon as there is no tutorial on that.

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

    Thanks for that brother! Exactly what i was looking for. Amazing!

  • @user-ob9gg7wi4m
    @user-ob9gg7wi4m Рік тому

    good work bro but why your channel is so underated? btw u just got a new subscriber

  • @garudaputro
    @garudaputro 6 місяців тому

    Now how to Authentication and Role-Based Access Control in Next.js using clerk ... I mean when you have a different role like admin and user and make middleware to handle it using clerk, would you make a video tutorial about it?
    I think there's not yet video about it

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

    I'm using nextjs and nestjs (as an api). I wish to verify that requests made to the api have authority to do so.
    When I made a full stack app using express, I used passport to control everything on front-end and backend. It prevented someone from making unauthorized CRUD.
    Would I need to maintain users in my database, sessions, and verify JWT to be safe? I can't see how you wouldn't sign in a user on the backend to verify their authorization to CRUD and issue a JWT.

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

      After some digging, I think I found the appropriate solution for this situation. Apparently, I should use passport-jwt on my nestjs to interface with clerk in a secure manner so that I can validate backend calls with the correct jwt.
      This is a simplification and implementation is a little more involved. I'm using a YT video on next.js, nestjs, and clerk. Plus nestjs documentation on passport.

  • @yossyBu
    @yossyBu Рік тому +1

    I dont know why but i get an error
    HTTP RESPONSE CODE
    401
    RESPONSE
    "ERROR":{1 item
    "message":string"src property must be a valid json object"
    }
    is it because the payload is not getting loaded properly? do you have any ideas?

    • @CryptoMarketSummary
      @CryptoMarketSummary Рік тому

      This helped me... copy and paste from a different comment so you see it.
      I had this problem... it turns out it was a middleware issue. Code below made it work for me. The problem? export const config was not registering my publicRoute or ignoredRoutes. Very weird issue but got it working now.
      import { authMiddleware } from "@clerk/nextjs";
      export default authMiddleware({
      // IF THESE ARE IN CONFIG, CLERK THROWS A FIT
      ignoredRoutes: ["/((?!api|trpc))(_next|.+\..+)(.*)"], // use this to ignore routes
      publicRoutes: ["/api/webhooks/user/route"],
      });
      export const config = {
      matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
      };

  • @Insane.18_7
    @Insane.18_7 6 днів тому

    is it possible connect clerk with mariadb? Thanks

  • @gamerquantum2847
    @gamerquantum2847 7 місяців тому

    Getting 401 unauthorised..
    Error message:- src property must be a valid json object

  • @jayng4028
    @jayng4028 Рік тому +3

    Hi good video as usual, could you try update the clerk user object Metadata and see if it on sync with the user metadata get back from currentUser() or auth() function on the server component page?

    • @cesargamer1231
      @cesargamer1231 Рік тому

      x2!
      Hope

    • @livecode247
      @livecode247  Рік тому +2

      This works if i remember correctly. I tried this on a project a few days ago while integrating stripe with clerk. I used the clerkClient.users.updateUser method and then called clerkClient.users.getUser method at another place to get the stripe creds.

  • @LifeSurf123
    @LifeSurf123 Рік тому +1

    Hey there, I was wondering if anyone could help me.
    I am trying to use this code and didn't realize it was for Next 13's app directory and I am still on the pages directory.
    It says the headers are for server components only. How can I go about using this code with the pages directory + T3 Stack? I have routers and the server folder.

    • @seanm7772
      @seanm7772 Рік тому

      He linked an example in the description that uses the pages directory. I'm doing it in a similar way to that but keep receiving the error message in Clerk "src property must be a valid json object", so not sure.

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

    Really useful. Thanks

  • @LalshaDevi-ls2ln
    @LalshaDevi-ls2ln 3 місяці тому

    Bhai kya hum phpmysql ko clerk api se integrate kar sakte hain 😢😢

  • @zefrannatael8938
    @zefrannatael8938 10 місяців тому

    Thanks, that's a great explanation. I'm currently learning to build a my website with Next.js and using Clerk Auth. From your video, I noticed you store all attributes in JSON format. I wanted to ask, what if I only want to store `emailAddress` in separate database columns?

    • @livecode247
      @livecode247  9 місяців тому

      Hey! I just did that for the tutorial purposes. In the real world scenario you would probably store the columns separately. You can basically get back the required column from `evt.data` and then separately insert it into the database instead of what I did with the attributes object at 35:32.

  • @coolnickq
    @coolnickq Рік тому +1

    Do I still need this Svix workaround with 13.4? I feel like there's an easier way now with the router.

    • @livecode247
      @livecode247  Рік тому

      Hmmm, might have to look into this now. Thanks for the feedback!

    • @mouadhnida4639
      @mouadhnida4639 Рік тому

      did you find the answer for your question ?

    • @coolnickq
      @coolnickq Рік тому

      @@livecode247 How about a video on doing this with a Python / FastAPI backend? Would love that

    • @livecode247
      @livecode247  Рік тому

      @@coolnickq Hey man! I try to stick my content to NextJS and React and stuff revolving around it, but ya sure if that's what's needed, I'd be open to it given it wouldn't divert the main course of the channel :)

  • @rishi8413
    @rishi8413 Рік тому

    I am just wondering if we can use middleware proxy for this and sync out database with the data we are sending to clerk server, correct me if am wrong

  • @sonnyboyfuenteblanca1998
    @sonnyboyfuenteblanca1998 Рік тому +1

    I tried to implement this in my t3 stack and i cant add a user. help

    • @Javaded
      @Javaded Рік тому

      have you find the solution? webhook send request successfully but it will not create user and I can not fetch data in console.log

  • @TheAremoh
    @TheAremoh 7 місяців тому

    Great video.
    What if I want to add extra field for role based Auth during registration? What I mean is, if I have multiple user types, say Teacher and Student, how do I include this field during registration so user can select a user type?

    • @livecode247
      @livecode247  7 місяців тому

      You might want to look into custom flows for that: clerk.com/docs/custom-flows/use-sign-up

  • @arthurkids237
    @arthurkids237 9 місяців тому

    Teacher great video, I have a question, such as customizing the login screen and registering in my local language; In my country, we do not use the English language.

    • @awol2
      @awol2 8 місяців тому

      You can use clerk localizations to make that. Once you've imported it you pass a prop in the ClerkProvider component that's named localization and then set the language you need (how to install and import clerk localizations is in their documentation, the language code is also in their documentation). For instance if you want to set spanish as clerk's language you'd have to do:
      Look at how you use the prop localization. Now the translation on those tend to not be that good so you may want to make a pull request to enhance the translation to your language.

  • @abdullahafaq6862
    @abdullahafaq6862 7 місяців тому

    hey great video man, can you make one for firebase please I have a project using openai gtp to create a simple chatbot but I can't save the conversations between bot and the user that is logged in so when the user again logs is he can see his old conversation with the chat I wanted to do that using firebase but I dont know how to intregrate firebase using clerck if you could make a video for that it would be helpful

  • @iangithinji1452
    @iangithinji1452 6 місяців тому

    I dont know what I am doing wrong. I am using mongo as my database. I have hosted my site on vercel and added the endpoint in clerk but i dont get any response or errors. What i just get is clerk webhooks not showing any attempted calls and no data saved in mongo. What could be the problem

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

      I'm facing the same problem

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

      @@alpha7s708 Here is how I solved my problem. First of all make sure that you are sending the correct payload to clerk. Just messing up one field, eg: username, could potentially cause errors to occur. If you have added username for example in your payload, make sure you have activated the username option in clerk dashboard. Next, use ngrok to expose your app, don't use vercel.

  • @johnsoto7112
    @johnsoto7112 8 місяців тому

    Amazing!! What happens when you can to create a table with a relation to the user? Do you have it reference the externalId?

    • @livecode247
      @livecode247  7 місяців тому

      Well since we're storing it in our own database, just use a foreign key

  • @SkySentry7
    @SkySentry7 7 місяців тому +1

    thank you so much dude

  • @user-il7rz1kx2e
    @user-il7rz1kx2e 7 місяців тому

    you saved me 👌👌❤❤ Thank you

  • @muhammed030
    @muhammed030 Рік тому

    Awesome explanation,
    is it possible to add a user role as well?

    • @livecode247
      @livecode247  Рік тому +2

      Yes, you can make use of the metadata api. This is on my video todo list!

  • @HimansuSekharMaharana
    @HimansuSekharMaharana Рік тому

    Can you tell me how to do the same thing using firebase as my backend. Please that would be helpful

    • @livecode247
      @livecode247  Рік тому

      You could just use firebase auth in that case, in my opinion

  • @Grishopping
    @Grishopping Рік тому

    Hello friend, could you make an example with roles for CLERK... I want to make an application for administration and only authorized people could enter and an application for users who enter if they register in the application.... I appreciate your comment... If you can't make the video, at least guidance to try to do it... thanks... Greetings from Venezuela your friend Jose Grillo

    • @livecode247
      @livecode247  Рік тому +1

      Hey man! Will be down to make this video in the future but am a little occupied with some content I've thought about rn. In a nutshell, what you would want to do is manage a role in the user's publicMetadata. I was using this in an application earlier, where I was setting the stripe credentials. It's very similar to that. Just check the role from the metadata, wherever you want to check it for authorization.
      To get the privateMetadata, you can do this:
      _const user = await clerkClient.users.getUser(userId)
      const userData = user.publicMetadata_
      To set it, you can do this:
      _const user = await clerkClient.users.updateUser(userId, {
      publicMetadata: {
      role: "admin"
      },
      })_
      Hope this makes sense.
      Docs Reference: clerk.com/docs/users/user-metadata

  • @user-pz3cv6tq6v
    @user-pz3cv6tq6v 8 місяців тому

    Nice video bro. Can I ask how to make clerk to accept microsoft email from one domain only?

    • @livecode247
      @livecode247  7 місяців тому

      I haven't tried this but you could take a look at this: clerk.com/docs/authentication/configuration/restrictions

    • @user-pz3cv6tq6v
      @user-pz3cv6tq6v 6 місяців тому

      @@livecode247 thanks, I have found it, the only issue is that its not include in the free tier.

  • @RajeevCanDev
    @RajeevCanDev 8 місяців тому

    Brother I need help " i have been stuck on an error of 401 while webhook connection with mongodb since 1week...
    I checked :-
    1 environment variable ✅
    2 routes inside app as api/webhooks ✅
    3 in middleware I also added /api/webhooks in public and ignored routes both
    4 deployment is good✅
    Idk where the problem is ... please help... it's just showing 401 in vercel in my deployment logs( it's just indicating that it's an authentication problem but idk where) please help

    • @abhijeetsingh4190
      @abhijeetsingh4190 8 місяців тому

      Bro I am also facing the same problem....did u get any solution?

    • @RajeevCanDev
      @RajeevCanDev 8 місяців тому

      @@abhijeetsingh4190 yes bro, go to the auth settings in clerk and turn it off that was turned on as default and just by turning it off everything will work fine

    • @abhijeetsingh4190
      @abhijeetsingh4190 8 місяців тому

      Bro what do I have to turn off?

    • @RajeevCanDev
      @RajeevCanDev 8 місяців тому

      @@abhijeetsingh4190 go to organisation settings and turn the first one off

    • @RajeevCanDev
      @RajeevCanDev 8 місяців тому

      @@abhijeetsingh4190 in your clerk dashboard, organisation settings

  • @facinick
    @facinick Рік тому +1

    Thanks!

  • @cesargamer1231
    @cesargamer1231 Рік тому

    Really good!

  • @prathameshkulkarni7132
    @prathameshkulkarni7132 11 місяців тому

    hey, how can I implement user role using clerk any idea?

    • @livecode247
      @livecode247  11 місяців тому

      You can store it in the user metadata and then access it in the middlewarw

    • @prathameshkulkarni7132
      @prathameshkulkarni7132 11 місяців тому

      @@livecode247 can you help me with it do you have discord?

  • @Javaded
    @Javaded Рік тому

    Hi, Thanks for your great video. I'm trying to implement your method in t3 stack. I use your suggested github repo as a reference. webhook in clerk website sends the request successfully and it contains my user data, but on the client side nothing comes through I even console.log("x") anywhere in webhook file but nothing shows in my console! Do you have any suggestion?

    • @livecode247
      @livecode247  Рік тому +1

      Oh ok, let me check! I got a query from a few people saying that the webhook api isn't working as expected. Will look into it ASAP

    • @Javaded
      @Javaded Рік тому

      thanks a lot @@livecode247

    • @Javaded
      @Javaded Рік тому

      is there any chance in which you've looked at this problem?@@livecode247

    • @CryptoMarketSummary
      @CryptoMarketSummary Рік тому +1

      ​@@livecode247 I had this problem... it turns out it was a middleware issue. Code below made it work for me. The problem? export const config was not registering my publicRoute or ignoredRoutes. Very weird issue but got it working now.
      import { authMiddleware } from "@clerk/nextjs";
      export default authMiddleware({
      // IF THESE ARE IN CONFIG, CLERK THROWS A FIT
      ignoredRoutes: ["/((?!api|trpc))(_next|.+\..+)(.*)"], // use this to ignore routes
      publicRoutes: ["/api/webhooks/user/route"],
      });
      export const config = {
      matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
      };

    • @segu_.
      @segu_. 8 місяців тому

      @@livecode247 hey! found any solution for this? setup looks like it works but im not receiving nothing on the server logs

  • @BlhJ400
    @BlhJ400 Рік тому

    Are the usernames unique? I want to each user to have a unique name for the slug dose clerk offer that?

    • @livecode247
      @livecode247  Рік тому

      Haven't exactly tried this but the "User & Authentication" tab in your app's dashboard has the "Username" option

  • @mathewadeyemi5389
    @mathewadeyemi5389 7 місяців тому

    thanks a lot

  • @rayyanwz
    @rayyanwz 7 місяців тому

    thanks bro

  • @garretthumbert3145
    @garretthumbert3145 10 місяців тому

    Anyone running into an issue where ngrok shows a temporary redirect when clerk calls your webhook
    /api/webhooks/user 307 Temporary Redirect
    Dont forget to add your API to your middleware public routes
    import { authMiddleware } from '@clerk/nextjs'
    export default authMiddleware({
    publicRoutes: [
    '/api(.*)',
    ],
    ...
    })

  • @ELONMUSKS-jn8pg
    @ELONMUSKS-jn8pg 9 місяців тому

    Hello , can i get some help with this where can i contact you?

    • @livecode247
      @livecode247  9 місяців тому

      Hey! You can email me at mail@kavin.me

  • @Grishopping
    @Grishopping Рік тому

    Greetings... I am already subscribed..... you have Discord....??
    if you don't have it yet I invite you to do it.... It looks like this channel is going to take off soon... Congratulations you explain very well
    Greetings Jose Grillo from Venezuela

    • @livecode247
      @livecode247  Рік тому

      Hey! Thank you so much! I do have a discord user(kavinvalli) but don't have a server. I don't think my making a server right now, makes a lot of sense lol, since I don't have that much traffic yet, but hopefully that day will come soon!

    • @Grishopping
      @Grishopping Рік тому

      @@livecode247 OK I understand .... I can only tell you
      A journey of a thousand miles begins with a first step.
      A thousand blessings and the best of success you deserve it.

    • @livecode247
      @livecode247  Рік тому +1

      Thank you so much! Means a lot ❤️!