Deploying Next.js App to Firebase Functions
First things first: what is Next.js?
A small framework for server-rendered universal JavaScript webapps, built on top of React, Webpack and Babel.
It comes out of the box with preconfigured features like routing, static optimization, server-side rendering, code splitting, CSS-in-JS support, hot reloading and API routes à la Express.js,
Deployment to ZEIT Now is super easy but I would like to explore to possibility to deploy my apps to Firebase Functions, in order to have a central common point for database, analytics, advertising and hosting.
There are not as much sources as one could think, given Next.js and Firebase popularity. I found the following ones, that are great:
- https://github.com/jthegedus/firebase-gcp-examples/tree/master/functions-nextjs
- https://codeburst.io/next-js-on-cloud-functions-for-firebase-with-firebase-hosting-7911465298f2
- https://github.com/zeit/next.js/tree/canary/examples/with-firebase-hosting
I have thought to write this article because I would like to provide a fast path to deploy an existing project, skipping deep explainations.
Step 1: configure Firebase
Go to your Firebase console and create a new project. Remember you need to adopt Blaze plan in order to be able to load external network resource from you cloud functions.
Then open terminal, go to your project folder and initialize Firebase inside it:
Choose only Hosting feature, then go on with defaults. Once firebase
finishes its operations, delete public/index.html
: it would interfere with routing.
Then, edit firebase.json
to this:
It tells Firebase hosting to rewrite all requests to nextjs-server
function we are going to define.
Step 2: configure server code
First of all, let’s install dependencies:
So, you can create server code in src/server/index.js
:
Then, you tell Babel how to generate Node.js server code from index.js
source by creating src/server/.babelrc
file:
Step 3: move Next.js app code
Put all you app code inside src/client
folder. You have to move also next.config.js
and, if you have it, tsconfig.json
.
Edit src/client=next.config.js
to change distribution path:
Update package.json
in order to use proper entry point and proper Node.js version on Firebase server:
Step 4: configure build scripts
Inside package.json
insert some useful scripts to develop you app:
Another batch of scripts can be dedicated to build:
You can launch a Firebase local server to debug your cloud function:
Finally, deployment scripts to upload release builds to Firebase:
Notes
You can see the whole project on Github.