Setting Firebase Functions is optional. You only need to set up Firebase Functions if you need certain features, such as Firestore Triggers, Storage Triggers, Authentication Blocking Functions, etc.
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:
- You want to implement Authentication Blocking Functions
- You need to use Firebase Storage Triggers
- 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"
build:functions
builds the functions bundle and then exitsbuild:functions:watch
builds the functions in development mode, so it will re-bundle your code on changesdeploy: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