Setting up Firebase Functions for your MakerKit application

Learn how to set up Firebase Functions in your Makerkit SaaS project

While you may want to use Next.js's own API functions for your application's API, there are many scenarios where you may be required to use Firebase Functions, for example:

  1. You want to implement Authentication Blocking Functions
  2. You need to use Firebase Storage Triggers
  3. You need to use Firebase Firestore Triggers

Therefore, it's essential to know how to set up Firebase Functions in a Next.js environment, such as the Makerkit SaaS template.

Initializing Firebase Functions

Assuming you have a working Makerkit project installed, let's type the following command in your terminal:

firebase init functions

When prompted about creating a new project, choose not to create a default project, as you may have already done it.

After completing the CLI prompts, you should have a few more files in your project:

✔ Wrote functions/package.json
✔ Wrote functions/tsconfig.json
✔ Wrote functions/src/index.ts
✔ Wrote functions/.gitignore

Adjust or delete the eslint configuration file

You may need to delete (or adjust) the eslint file generated by the CLI, as it may conflict with the one in the root of your project. We recommend using the one in the root of your project shipped with Makerkit.

If you leave it as is, you may see linting errors in your functions code, that can also prevent you from deploying your functions.

Firebase Functions setup

I usually proceed to copy some of the scripts to the root package.json, such as the below:

"build:functions": "tsc -P functions/tsconfig.json",
"build:functions:watch": "tsc -P functions/tsconfig.json --watch",
"deploy:functions": "firebase deploy --only functions"
  1. build:functions builds the functions bundle and then exits
  2. build:functions:watch builds the functions in development mode, so it will re-bundle your code on changes
  3. deploy:functions deploys your Functions to the Firebase cloud

Writing your First Function

Let's write our first, very simple Firebase Function:

import { https } from 'firebase-functions';
export const helloWorld = https.onRequest((req, res) => {
res.send({ Hello: `World` })
});

Running the Firebase Functions emulators

When using Makerkit, simply run the emulators:

npm run firebase:emulators:start

If working correctly you'll see the following output:

✔ functions: Loaded functions definitions from source: helloWorld.

🎉 And now you can finally use the full power of Firebase's Functions!

Ignore the Firebase Functions folder when deploying to Vercel

Since Firebase Functions are to be deployed to Firebase, you can ignore the functions folder when deploying to Vercel.

To do so, create a file named .vercelignore in the root of your project and add the following line:

functions