Generating unique ID’s in Firebase

This is just a quick post to show off a tool for generating unique ID’s in Firebase.

These ID’s can be created in Firebase themselves, using the push() method and capturing the newly created ID, but often a developer will want to create some ID’s for a small number of entries they’re adding to the database and they won’t want to write code specifically for doing this one-off job.

Firebase ID’s appear to be random strings of text, but in fact they’re generated from the timestamp of the hardware that the code is running on. It’s then converted into a series of characters that are ideal for use as keys in a key/value object. The great thing about doing things this way is that the ID’s can be turned back into human readable times/dates or even unix timestamps quite easily. Another benefit of these lexographic ID’s is that they are ordered.

If for example a random string was chosen as the key, after a few entries to the database you might notice that things are being thrown in without any consideration for the order in which they were added. This might not be an issue in your specific use-case, but it can make trawling through the database later on a bit of a pain, especially if it starts to get pretty big.

With the Firebase ID’s generated from a timestamp and outputted in a lexographic string of characters, we can see that any data added to the database using these ID’s will be added in a sequential order. This makes for a much neater appearance and makes reading the database much more effecient, as the most recently added data is always at the bottom.

Anyway. Enough waffling on.

Here’s a really handy little tool I found by a developer called mikelehen on GitHub to generate these ID’s for use in your own projects. I hope you find it as handy as I regularly do. 🙂

Hit the “Generate” button above and the script will make a new unique ID for you, based on the current timestamp. You can then paste this into the Firebase console as a key for any of your data. If more than one ID is generated at exactly the same time, the script increments to make sure no duplication occurs, so it has some really handy error handling in there too. 🙂