Implementing Submission Voting Logic In Firebase

Last updated: November 22, 2016

I love Firebase. The power and flexibility of using it alongside my favourite client-side framework Aurelia, unrivalled. Recently whilst building the Built With Aurelia website which uses Firebase, I wanted the ability for logged in users to vote on particular submissions.

My Firebase structure is literally the following:

submissions: {
    pokegorun: {
        added: 1470919840796,
        category: "website"
        description: " is a Pokemon spotting map where you ..."
        name: ""
        repoUrl: ""
        url: "",
        votes: {
            TPdM9feOrbgNHVGHebBT7TBZ8Xj1: true

My submissions object contains submissions keyed by their name. Then inside some basic object properties for this submission and an object for votes which are keyed by the username (so the same user can’t vote twice).

Under the “Rules” tab in Firebase I have the following for my database:

    "rules": {
        ".read": true,
        "submissions": {
            "$slug": {
              ".write": "auth.uid != null",
              "votes": {
                "$uid": {
                    ".write": "auth.uid != null && auth.uid === $uid"

As you can see I have a basic read rule to allow everything to be read by default. Then I define a rule group for my submissions “table” in which I only allow writes if the user is logged in (non-authenticated users can’t submit anything).

Then we get to the meat on the bones, the “votes” part sets up a sub-rule group. This is essentially saying that each item is keyed by a user ID which we are calling “$uid” and then inside we are saying that only the user who has previously voted can alter the vote (retract it and or resubmit their vote). Any registered user can submit a vote because of our .write rule.

Once you harness the power of Firebase’s rules, you can create anything.




Leave a Reply

Your email address will not be published. Required fields are marked *