GraphQL Server Using Firebase

Devayan Kumar Sarkar
The Startup
Published in
4 min readNov 19, 2020

--

GraphQL and Firebase are awesome together.

Why Firebase ?

Firebase is comprehensive app development platform that allows you to build your apps at scale. It’s an easy to use platform that has a free tier where you can play around to your heart’s content and to be honest, the free tier can comfortably accommodate a major chunk of use cases without breaking a sweat.

For example in the free tier, you can have 10k authentications and 125k function invocations per month and many more. With Firebase you can build at “web” scale without any worry.

We were using Firebase functions for quite some time now and they have served us well. (See the pun ? No, alright.)

Now, GraphQL

For our next project we wanted to use GraphQL, primarily to only retrieve the fields we wanted. We had an experience where the frontend was loading a huge chunk of json only to use 10 to 20 percentage of the information. That was a waste of bandwidth. We wanted to avoid that and hence, GraphQL.

So, we planned to put our GraphQL server in Firebase functions.
And it was a straightforward one.

Let’s start with an easy example of having a GraphQL server using Firebase functions.

Create a Firebase project with Firestore

We are going to use Firestore as a database for this project. It is a powerful one with advanced querying capabilities.

Creating a project

Once you have your project, go ahead and enable Firestore.

As of today, you can push Firebase functions with Nodejs version 8 without adding a card. This will be discontinued in the near future. You can upgrade by adding a credit card and have the capability to push functions with Nodejs version 10. This will upgrade you to a Blaze plan which provides even more quota than the the free tier (Spark plan).

Install Firebase CLI

Install the Firebase CLI from here. This cli helps you to create a project, run emulators and even deploy the project from the terminal.
Once you installed it run firebase login. This will log you in the cli.

Creating the project

Setting up workspace

Once you have setup your workspace in your favourite language, you can see this folder structure:

Initial workspace setup

To verify, you can run npm run build (is you have typescript) and firebase emulators:start in the terminal to see it in action.

Let’s GraphQL

You would need these dependencies:

express
graphql
apollo-server-express

Now, let’s build the server.

const functions = require(‘firebase-functions’);// For accessing Firestore database
const admin = require(‘firebase-admin’);
const express = require(‘express’);
// GraphQL dependencies
const { ApolloServer, gql } = require(‘apollo-server-express’);
// Will initialize with default settings and database
admin.initializeApp()
const db = admin.firestore()const app = express();

Well, now that the boilerplate stuff is out of the way, we need to set up types and resolvers for our data.

Let’s define a simple User type

const typeDefs = gql`
type User {
firstName: String
lastName: String
email: String
}
type Query {
users : [User]
}
`

Now, we have to add a resolver to return a list of users.

const resolvers = {
Query: {
users: () => {
return new Promise((resolve, reject) => {
fetchAllUsers((data) => {
resolve(data);
});
});
}
}
}
// Function to fetch all users from database
const fetchAllUsers = (callback) => {
db.collection('users')
.get()
.then((item) => {
const items = [];
item.docs.forEach(item => {
items.push(item.data())
});
return callback(items);
})
.catch(e => console.log(e));
}

That’s it.

Now, we just wrap everything up into a function.

const server = new ApolloServer({ typeDefs, resolvers });server.applyMiddleware({ app, path: '/' })exports.graphql = functions.https.onRequest(app);

Now, we can run firebase emulators:start. This will start the local emulators for testing.

You will see see the resources and their ports:

Functions and Firestore running locally

Go ahead and add a few documents in the users collection.

Adding data in local Firestore emulator

Once you are done, head to http://localhost:5001/<your-project-id>/us-central1/graphql and you can see your function working.

Sample GraphQL server

And here we have a working graphql server using firebase function. All that remains is to do firebase deploy and the functions will be deployed.

We were able to leverage the free quotas for a long time and have a running GraphQL server without paying anything extra. Of course this is a very simple example but then again, we can build on top of this. Firebase makes a lot of things possible.

Have fun building your GraphQL server.

Source code on GitHub.

--

--

Devayan Kumar Sarkar
The Startup

Creator, developer and tinkerer. Loves to read books and play badminton. Keeps things simple.