I'd like my NestJS API to listen to a Keycloak event (such as a new user having registered) and run some code when it happens

Disclaimer: I don’t know if this is the right place to post this, please tell me if there is a better place to ask such a question.

Context: I am developing a NestJS application which uses Keycloak for authentication, the users have the option to register with a Microsoft account (business account) or register by themselves. I have one PostgreSQL instance running which has two databases, one for my application and one for Keycloak data. The user roles which I’ve created in Keycloak are already being handled by my application and the API endpoints are protected based on authentication and roles (I use @nestjs/jwt). In Keycloak I use OpenID.

Question: I’m looking for a way for my NestJS app to listen to the event of a user being created and run certain code based on that.

Use-case #1: The application is being used internally. The users are supposed to register themselves but if they fail to do that, a person with a certain role (editor) can create a user for them in the system (with the user’s internal email address). However, if a user registers after a profile has already been created for them, then the two profiles should be merged (the email should stay the same).

Use-case #2: Microsoft account is the preferred way for signing up, the only reason there is a regular email+password registration as well is because there are going to be a really small number of external users who do not have an account. However, if an internal employee tries to register with their business email, the app shouldn’t let them register, it should tell them to register with Microsoft SSO.

I think I can handle both use-cases if I find a way to listen for events of:

  1. A new user being created in Keycloak
  2. A new user trying to use an email address which already exists in the database or it is a certain format (a specific company email address).