Storing id returned from database in app_metadata - unsure whether to do this on the pre or post user registration hook?

I’ve currently setup a post-user registration hook that stores the newly created auth0 user in my database, returning an id from the databse to store in the auth0 app_metadata:

const axios = require("axios");

exports.onExecutePostUserRegistration = async (event) => {
  const response = await axios.post("https://mydatabase/api/users/", 
    { 
        auth0_id: event.user.user_id,
        email: event.user.email,
        username: event.user.username, 
    }
  );

  // Store database id in app_metadata
  event.user.app_metadata.db_id = response.data._id
};

This seems to do what I want but i’m unsure of whether directly mutating event.user.app_metadata is the correct way to do this.

I initially setup the post registration hook based on this part of the Post-User Registration docs.

Reading through the Pre-User Registration docs however suggests that this might be a better place to add to the app_metadata:

At the Pre-User Registration extensibility point, Hooks let you execute custom actions when a new user is created. For example, you can add custom app_metadata or user_metadata to the newly-created user, or prevent the creation of the user in the database.

Is my current setup using the post-user registration hook ok or should I be doing this in the pre-user registration hook instead?

Hi @AlexDring

The pre-reg hook is preferable, as the post-reg is asynchronous, and you are not guaranteed it will complete before the user’s first login.

John

Hi @john.gateley

Thanks for the quick response. I think I’m going to have to use the post-reg hook as I need the user_id from the auth0 user and that isn’t available using pre registration.

To avoid having to store a database id in the users meta data, would it be possible to use the auth0 user_id as an id in the database to reference the user or is that not considered appropriate?

Hi @AlexDring

You can also do it in a rule that checks to see if this is the first time the user has logged in, rather than post-reg.

Both methods you mention (storing your user ID in the Auth0 user’s metadata and storing the Auth0 user ID in your DB) are appropriate, with various trade-offs.

John