Building a Serverless React App on Firebase Functions

View of the Bernese Alps from Schilthorn. © 2019 John Apostol

This is a step-by-step guide to building your own serverless React app with the practicality afforded by Next.js and the Firebase ecosystem.

After reading about Next.js’s new serverless mode and attending ServerlessDays ATX, I got the itch to wire up a simple example for a Firebase-flavored serverless app.

Read before you proceed: Firebase bundles all of your functions together and doesn’t natively support per-function bundling. A sufficiently large app with many routes may run into scaling issues. See this comment.

I wrote this all before I found this out so I’m publishing this anyway. Proceed if you dare!

First, let’s take a look at our toolbox.

Next.js

If you’ve ever built a major React app from scratch, you know what config hell it can be. Next.js is an opinionated, fully-featured React framework that gives you sane defaults upfront. Later on, you can customize your .babelrc and webpack config to suit your app’s needs. You can even pre-render your app on the server (or function in our case).

Most important for our purposes, Next.js features a new serverless mode that’s optimized for cold starts and small function size.

Firebase Functions

AKA Cloud Functions for Firebase

Can’t have serverless functions without a serverless hosting provider. There’s servers running our code somewhere but we want them abstracted away.

The Firebase platform is a nice choice, because it can scale with your app’s needs for a data store, authentication, logging (albeit simple), static file hosting, and user file storage. There’s a little bit of a learning curve when integrating with some features but I’ve generally found it simpler to work with when compared to something like AWS.

That said, permissions are currently platform-wide with beta support for per-function IAM. Be wary if you’re keen on following the principle of least privilege.

The rest of this post will explain how to set everything up step-by-step. If you’d rather get going with less hand-holding, see this repo instead:

From scratch

Fire up your text editor and mkdir something fancy, then let’s get started!

Begin by installing or swapping over to Node.js 8. Use the version of npm bundled with that to run these commands.

  1. npm init
  2. npm install next react react-dom

Our app’s main dependency is on the next package, which lists react and react-dom as peer dependencies. Installing just next is not enough.

Specify "engines": { "node": "8" } in your package.json so Firebase Functions knows which runtime to provide you.

One of my secret joys is to use the latest version of Node.js in whatever new project I work on. Hold off on that urge here, because it’s important to note that Firebase Functions only support Node.js 6 or Node.js 8 runtimes as of this writing. Lock it down for now to avoid any headaches later.

Let’s continue by installing some more dependencies.

  1. npm install firebase-admin firebase-functions
  2. npm install firebase-tools --save-dev

firebase-admin and firebase-functions are necessary for your functions to run on Firebase, while firebase-tools is what you’ll use to deploy and manage your app.

After setting up those dependencies, let’s create a new Firebase project for our app to live in. Visit https://console.firebase.google.com/ and follow the on-screen steps in order to create a project.

Once you have your project, you can associate your code:

  1. npx firebase login
  2. npx firebase use --add

The first command will launch your browser and prompt to login to the Google account associated with your Firebase project. Use the second command to select the project you just created.

Notice that a .firebaserc file was created in your project directory. This file serves to map local development aliases to Firebase projects. If you create more projects and define more aliases, npx firebase use [alias] can be used later to swap deploy targets. A common scenario is swapping between production and staging environments.

We should have a directory structure that looks like this:

|-node_modules
|-.firebaserc
|-package-lock.json
`-package.json

OK, now we will need to build a simple Next.js app with routing.

Different routes are served by different functions (at runtime). We can deploy new code on separate routes without breaking our whole Next.js app!

Create a directory structure with blank files like so:

|-node_modules
|-src
| `-app
| |-components
| | `-Nav.js
| |-pages
| | |-About.js
| | `-Index.js
| `-static
| `-placeholder.json
|-.firebaserc
|-package-lock.json
`-package.json

All upcoming examples will assume this directory structure.

Let’s build out the Nav component:

Now wire up those two pages, Index and About:

The static directory is where your app can store static files like favicon.ico or robots.txt. Having any file here is necessary for defining Firebase hosting route configs. placeholder.json is an empty file here just for this purpose.

Create the serverless functions

Now let’s add serverless functions to handle each app route:

|-node_modules
|-src
| |-app
| | |-components
| | | `-Nav.js
| | `-pages
| | |-About.js
| | `-Index.js
| `-functions
| `-index.js
|-.firebaserc
|-package-lock.json
`-package.json

Inside the newly minted functions directory, we’ll have a single index.js file that serves as a function manifest for our route functions. This file will export each individual named route, as you can see:

Note: index.js is one large bundle. Don’t mistakenly believe that each export is its own bundle!

Compiling and deploying!

Our super simple app and super simple route functions are ready. Now we can put the pieces together and get everything running in Firebase.

First, we’ll create a config file for Next.js:

Great, we’ve configured Next.js to bundle each page individually and where to put those bundles.

Now, we’ll define some simple scripts and include those in our package.json file so that we can automate some common tasks:

"build:app" is self-explanatory. This will build out our app using direction from the src/app/next.config.js file we created. Go ahead and run it now with npm run build:app if you wish. You’ll notice a new dist directory at your project root. You can find your app page bundles nested within that.

dev is even simpler. You can now use npm run dev to hack away at your app with a modern local development server.

Let’s install a few more dependencies to make our lives easier:

  1. npm install cpx rimraf --save-dev

I like using cpx for recursive file copying and rimraf for recursive file deletion, because they work just as well on my Mac OS X and Windows machine.

Update package.json with some more scripts:

build:functions doesn’t build functions necessarily. In this simple project we’ve written Node.js 8 compatible code so it’s enough to copy our functions over to dist as they are.

build:public copies static assets from the src/app/static directory. Our lone placeholder.json file will be served by our app’s domain once deployed.

clean is for deleting our dist directory to ensure we are properly building our app from scratch before each deploy.

copy:deps is interesting. It copies our dependencies over to the function directory. This ensures that we are using the same dependencies in our serverless functions and client code. One would have to define a separate set of npm dependencies within the src/functions directory without something like this.

The final piece of the puzzle is the firebase.json file, which we’ll create now:

functions.predeploy runs our package.json scripts in order to ensure that each deploy is reproducible.

functions.source points to the dist/functions directory as the source of our serverless functions. Our compiled manifest file, dist/functions/index.js, sits in that directory and its named exports are our functions.

hosting.predeploy contains the package.json script responsible for setting up our static assets.

hosting.public points to dist/public, which is the directory that will have its contents uploaded as static assets.

hosting.rewrites is a mapping of URL endpoints to functions. This configuration points /about to the about page function, while all other routes will be served by the index page function. You can think of this config as your router!

With the addition of firebase.json, our directory structure resembles this:

|-node_modules
|-src
| |-app
| | |-components
| | | `-Nav.js
| | `-pages
| | |-About.js
| | `-Index.js
| `-functions
| `-index.js
|-.firebaserc
|-firebase.json
|-package-lock.json
`-package.json

And we can now deploy our entire project to Firebase.

  1. npx firebase deploy

Firebase will deploy our static code (placeholder.json), deploy our serverless functions, and rewrite our app routes to be served by those same functions.

At the end of the deploy you will see a Hosting URL for your project, something like https://[project-name].firebaseapp.com. Check it out!

One thing you’ll notice if you haven’t dealt with serverless applications before is that initial visits to routes will feel slower because the functions serving those routes go through a cold start if they haven’t been used recently. If a function has been invoked recently, it’s considered hot and will respond much more quickly. Having regular traffic to your functions will keep them hot. Thankfully, Next.JS’s serverless mode optimized for cold starts.

That’s it! Please let me know if you found this post helpful at all! 😃

Thanks

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store