firebasegoogle-cloud-platformfirebase-authenticationgoogle-cloud-functions

How to set a custom uid inside firebase authentication


I am working on a project, where I want the users to able to view each others profiles. I want the URL to be like GitHub, so my-project.com/username. To achieve that I want to set a custom uid for every user. I don't want the uid to be random characters like it is by default in Firebase authentication. I want it to be a unique and readable username.

I tried researching inside Firebase docs about this, but I could not find anything. the closest thing to the way the auth cloud function trigger functions.auth.user().beforeCreate(). But this is not what I need because through this I cannot set the uid.


Solution

  • I want to set a custom uid for every user. I don't want the uid to be random characters like it is by default in Firebase authentication.

    You can use the createUser() method of the Admin SDK to create a user in the Auth service with specifying your own uid, as explained in the documentation:

    getAuth()
      .createUser({
        uid: 'some-uid',
        email: 'user@example.com',
        phoneNumber: '+11234567890',
        // ...
      })
    

    You can execute this Admin SDK code in a Cloud Function (recommended option) or from a server that you control. In other words this method cannot be called from a client (i.e. front end). However you could call, from a Client, a Callable Cloud Function which uses this method: see this article for an example.

    I want (this custom uid) to be a unique and readable username.

    You are responsible to choose the custom uid value and to ensure its unicity. It must be "a string between 1-128 characters long, inclusive" and must be unique (if a user with a same id exists, the createUser() method will return an error).