35

I am parse.com user, and now I look for another service. How can I write back end logic to firebase?

let say I want to validate all the values on server side, or trigger things. I thought about one solution, but I want to know the recommended way.

I think to

  1. create nodejs server, that uses express.
  2. create middlewares to handle the logic.
  3. send rest request from the app, that triggers the middlewares
  4. use the nodejs sdk of firebase to update the values according to the params of the http request.
  5. And implement on the app firebase handler that listen to changes

enter image description here

their something simpler? In parse I used cloud code, I want that the logic will not be on the client side but on a server side.

Alon
  • 2,919
  • 6
  • 27
  • 47
  • 1
    Great question! As you probably already saw, Firebase does not have a direct equivalent for Cloud Code (yet). I've described/linked a few approaches below. Just comment if something is not clear! – Frank van Puffelen Feb 12 '16 at 14:44
  • [Have you seen this video yet of Rob Dodson explaining how to use Firebase with Polymer](https://youtu.be/1f_Tj_JnStA?t=12m52s)? I think it's a very powerful combination. https://youtu.be/1f_Tj_JnStA?t=12m52s – Let Me Tink About It Feb 15 '16 at 18:56

4 Answers4

44

Update (March 10, 2017): While the architecture I outline below is still valid and can be used to combine Firebase with any existing infrastructure, Firebase just released Cloud Functions for Firebase, which allows you to run JavaScript functions on Google's servers in response to Firebase events (such as database changes, users signing in and much more).


The common architectures of Firebase applications are pretty well-defined in this blog post Where does Firebase fit in your app?.

The architecture you propose is closest to architecture 3, where your client-side code talks both directly to Firebase and to your node.js server directly.

I also highly recommend that you consider option 2, where all interaction between clients and server runs through Firebase. A great example of this type of architecture is the Flashlight search integration. Clients write their search queries into the Firebase database. The server listens for such requests, executes the query and writes the response back to the database. The client waits for that response.

A simple outline for this server could be:

var ref = new Firebase('https://yours.firebaseio.com/searches');
ref.child('requests').on('child_added', function(requestSnapshot) {

    // TODO: execute your operation for the request

    var responseRef = ref.child('responses').child(requestSnapshot.key());
    responseRef.set(result, function(error) {
        if (!error) {
            // remove the request, since we've handled it
            requestSnapshot.ref().remove();
        }
    });
})

With this last approach the client never directly talks to your server, which removes all kind of potential problems that you have to worry about. For this reason I sometimes refer to them as "bots", instead of servers.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    It's a queue system. So the client can whatever it wants (well: whatever your [security+validation rules](https://www.firebase.com/docs/security/guide/) allow) as a request, but your bot/server determines what to do with it and what response to give (if any). It can just ignore requests it deems "invalid" and leave the rogue client waiting for a response. You can also build error handling into the request/response protocol, and send a "NOPE" type response. It's just like an API, except that you use our database as for exposing it. – Frank van Puffelen Feb 12 '16 at 14:54
  • So In this case that I need server. This is not better use socket.io? it seems to me like remove one layer and more simpler. – Alon Feb 13 '16 at 16:34
  • 1
    If you like doing middleware, there are tons of alternatives. What is "better" is subjective. I just wanted to elaborate on how you can build an API on Firebase, without doing middleware. It's the most commonly used alternative to Cloud Code with Firebase at the moment. – Frank van Puffelen Feb 13 '16 at 16:54
  • For anyone interested in the message bus / queue system described above, this series of posts might be useful https://howtofirebase.com/fire-stack-4195a13daf96#.aixh3q4xy – Kildareflare Feb 08 '17 at 03:05
4

2017

Today Google announced Cloud Functions for Firebase https://firebase.google.com/features/functions/

This is a great solution for the architectures and back end logic in Firebase.

Alon
  • 2,919
  • 6
  • 27
  • 47
  • I got to know this and now It had solved my issue that i was facing just a month back , Thank you firebase team ! – Ravi Rajput Mar 16 '17 at 12:08
  • I came to this StackOverflow question because I can't filter my eCommerce website using the only firebase. how I can achieve that. if I use some REST API Can you plz guide me what i should do – George C. Jul 15 '17 at 12:25
  • @George you can use the new firebase cloudstore. But still, you can't do a full text search. I think you might be want to use external search engine such as algolia to enable a advanced search feature in your website. – Moses Aprico Oct 29 '17 at 10:45
  • Came thru some comment that firebase may have some issues with React-Native. Wondering if there is any concern if the app is built on RN? – SuicideSheep Feb 02 '18 at 08:47
2

Here's what I would do:

  • Validade all the inputs with the ".validate" rules. No server needed for that.
  • If you have tasks to run, use Firebase Queue, a bot to run the tasks and you are done.

If you don't do the last one, you may have two problems:

  • If you try use the diagram you posted it will be a little tricky to get the auth object at the server (but not impossible). Go ahead if you don't need to validate the user to allow the request.

  • If you use just the regular firebase app to listen to changes and respond (editing the object for instance, like Frank van Puffelen's example code), you might have scalability problems. Once your back end scales to two (or more) instances, a firebase edit will trigger the task on all of them. Each instance will notice there was a change, then run the same task once each, add/replace the response object once each and try to remove the request object once each..

Using Firebase Queue avoids both of these problems.

ThadeuLuz
  • 902
  • 8
  • 12
0

You can combine these two behaviors simultaneously:

Client side communicates directly with the Database

One excelent thing about the Firebase Realtime & Firestore is that you are able to listen in realtime to database changes. But is important to configure the Security Rules so the client can't modify or read data that he is not suppose to.

Client communicates with a Node.js server (or other server)

The node.js server will have adminstrative privilegies by using the Firebase Admin SDK, it can perform any change in the database regardless how the Firebase Security Rules are configured.

The Client Side should use the Firebase Authentication library to obtain the ID Token, it will inform to the server on each request (e.g. on headers). For each received request, the node.js server verifies if the ID Token is valid by using the Firebase Admin SDK.

I created a documented GitHub project of a Node.js server that uses Firestore Database and Firebase Authentication, check the example here.

Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34