Getting Started with Cloud Firestore with Node.js – Firecasts
Articles,  Blog

Getting Started with Cloud Firestore with Node.js – Firecasts


JEN PERSON: Hey, all
you Firebase developers. Let’s talk about two
of my favorite things– Cloud Firestore
and the Admin SDK. [MUSIC PLAYING] So I love that Firebase
has such robust client side SDKs for iOS, Android, and web. But did you know that Firebase
also has a server side option? The Admin SDK. The Admin SDK lets you access
Firebase features server side. So you can, for
example, read and write to Cloud Firestore
outside of the client. This is especially useful for
offloading CPU intensive tasks and keeping secrets
away from the client. Now, if you’ve
seen Todd’s videos on getting started with Cloud
Firestore for iOS or Android, you’ll already be
familiar with the sample app I’m going to use– one that stores an
inspiring quote. If you haven’t
seen these videos, I highly recommend
you check them out. Todd gives a great overview
of the Firestore structure. I’m going to use the iOS
version of the inspiring quotes app, which looks like this. You can see the quote and
author, as well as text fields to write a new quote
and a new author. In this video, I’ll show you
how to use the Admin SDK to make changes to Cloud
Firestore, which can then be seen here in the client. So you may be
wondering, how can I keep my quotes fresh with
new inspiration every day? I could rely solely on users
to write quotes, or just try to remember something
interesting and type it in the console manually. After all, there’s no shortage
of misinterpreted quotes on the internet. Didn’t George
Washington say that? Anyway, one neat way I can
handle this is server side. I could use one
of the many quote generating REST APIs out
there to get my quotes for me, and then write them to the
database using the Admin SDK. I can also use server side
code to send a notification to users, or something
like that, if I wanted to. So that’s what I want
to show you today– how to get started using the
Admin SDK to read and write data to Cloud Firestore. I’m going to show you the
Firebase Admin SDK for Node.js. But Java, Python, and
Go are also supported. OK, let’s get started. First, I need service
account credentials, which I can download from
the Firebase console. Under the Firebase
Admin SDK tab, I’ll select Generate
New Private Key. This downloads a JSON file
containing the service account credentials. I’ll add this to my
project’s directory. Now this service
account JSON file contains sensitive
information, including your service account’s
private encryption key. Remember to keep
it confidential. Never add it to version control. Never put it in a client app. And never store it in
a public repository. Now I’ll install the
Firebase Admin package in my project directory. I’ll make a new JavaScript
file for my code. I’ll be running my code
locally, but you can add yours to the server of your choice. I’ll require the
Firebase Admin package. I’ll also require the config
file containing the service account key. Then, I can initialize the SDK
using my downloaded service account key file. Note that if I were using the
Node.js Admin SDK in a Cloud Function, I could automatically
initialize the SDK through the function’s
config variable. I wouldn’t need to download
the service account. If using the Admin SDK on
the Google Cloud Platform, you can initialize the app
using the application default credentials, like this. But no matter how I
initialize the app, I’ll then initialize an
instance of Cloud Firestore the same way, calling
admin.firestore. Now that I’ve initialized
the Admin SDK, I’m ready to get a random quote
and write it to the database. But before I get coding, let’s
briefly examine the structure of the quotes app. At the top level, I start with
a collection called sampleData. This collection contains
just one document called inspiration. This document will itself
have two key value pairs, or we can call them fields– one called quote, and
another called author. Now, as an aside,
keep in mind, I’m not storing one quote per user. Everybody in the world will
be altering this one document. If I were looking to save
a different quote per user, I’d probably set up
a users collection and create a different
document for each user. And again, if you’d like to see
how to build this app on iOS or Android, check
out Todd’s Firecast on getting started with
the Cloud Firestore. Now, I’m going to call a
function I’m calling getQuote, the result of which
contains a JSON object with a random quote. The result of the function
looks something like this. All right, let’s
generate a quote, and then add it to
Cloud Firestore. OK, I’m going to call the
getQuote function, which returns a promise with
the response from the HTTP endpoint. I’ll parse the results and
create an object containing two key value pairs– a quote and an author. I’ll write the quote
to the inspiration doc in the sample data collection
using the set function, which sets the document’s
data to whatever data I pass to the function. If the document does not yet
exist, it will be created. So keep in mind
that this replaces all the data in the
document with the data pass. If I wanted to update some
fields or add to the document, I’d use the update
instead of set function. Once that work is complete,
I’ll log that the quote was written to the database. All right, let’s see
this code in action. In the terminal, I’ll
run node index.js to run my node app locally. The console logs tell
me that the new quote was written successfully. We can see the quote here. And we can also see it
in the Firebase console. But I think it’s cooler to watch
the quote change in the app. Here’s the iOS version
of the quotes app, with a current randomly
generated quote. When I run my node
up again, I can see that the quote changed
in the iOS app as well. See? Pretty cool. My server side code can
now generate quotes, great. That’s sure to keep
users motivated. But I may also want to be
able to read data from Cloud Firestore server side– say, if I wanted to sanitize
bad words from quotes or send notifications when
new quotes are written. So let’s look at getting
data from Firestore. I’ll get data from
the inspiration doc in the sample data
collection using get. I’ll also include a catch block
to handle if an error occurs. I’ll just log it for now. OK, after I get
the data, I’m going to check if the document exists. If not, I’ll log that
no document exists. Then, I can use
the document data to do whatever my app needs,
such as sending a notification. And there you have it. Now you know how to use
Cloud Firestore for Node.js on your server. I hope this inspires you to
incorporate the Cloud Firestore and Admin SDK into
your Firebase projects. Be sure to subscribe
to be the first to know about new videos for
Firebase, including Firecasts like this one. Thanks for watching, and I’ll
see you on a future episode. [MUSIC PLAYING]

21 Comments

  • John Smith

    I am learning node … and i don't find these short burst tutorials all that useful. I have followed several and built various mini firebase apps but always end up with more questions than answers.
    It would be great if you could show how to use firebase to build an incredibly simple app which covers everything you need to build a real world app. Including authentication, crud, jwt and whatever other essential features are required to build and app these days.

  • AmsaAce

    Say if multiple doc.set operations occur a second, does firebase guarantee that all of the clients will see every single change? e.g. if called a 1000 times a second, would each client receive 1000 quotes a second.

  • LuckyMANUTDLuke

    Thank you for these videos! Could you please add next time link to git repository with created code? I got lost few times because video doesn´t contain everything. Thank you again 🙂

  • Mateja Petrovic

    Awesome firecast, Jen! Can you continue where you left off an implement push notifications, that'd be super cool!

  • Purple Haze

    I've installed firebase admin on my server and when I get to the line where you write "code index.js" then I get: "-bash: code: command not found". If I create an index.html with javascript as suggested here: https://firebase.google.com/docs/admin/setup?authuser=0 I get object error: "(index):11 Uncaught ReferenceError: require is not defined at (index):11" which is the: "var admin = require('firebase-admin');" line. There is no issue at all installing firebase locally, why can't I for the life of me get it to work on my server and thus my website? Why can't you make a video that shows how to get started to begin with before making these other videos?

Leave a Reply

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