Running BackendKit (Firebase Functions) Locally
Of course you can always straight up deploy your functions to the cloud and then call them from your front.
But what if your app is already live and you don't want to mess up your backend while you're developing new features? Or don't want to wait up to a couple of minutes for your changes to be live?
That's why we recommend to run your backend locally, while you're developing for it. It's also pretty straight forward after initial setup.
Setup
Make sure you have the Firebase CLI installed
We already cover this in the BackendKit Setup, but in case you don't have it installed yet, you can do so by running:
npm install -g firebase-tools
Set up admin credentials
To use Auth and other sensitive Firebase services locally, you need to set up admin credentials.
Get Service Account Key
Go to your Service Account Panel (opens in a new tab) and select your Firebase project. (In case you don't have one yet, DO THE INITIAL SETUP FIRST!)
Select the Service account with the name App Engine default service account, press on the three dots and select Manage Keys.
Press on Add Key > Create New Key.
Select JSON and press on Create. This will download a JSON file with your credentials.
Place the key next to your firebase.json
file in your Backend Folder (projectpath/Backend/firebase-func/drop-it-here
)
Set your Google default credentials to point to the downloaded key. First, copy the path of the key file, then paste it into the terminal and run:
export GOOGLE_APPLICATION_CREDENTIALS="path/to/key.json"
Set up Cloud Functions Emulator
Go to your /firebase-func
folder and run:
firebase init emulators
In the setup, select the following:
- Select your Google Account that is connected to your current Firebase project.
- Select Functions Emulator, Firestore Emulator and Authentication Emulator
- Keep pressing enter to select the default options.
Set up your App to use the Local Backend
In your app, go to your functions definition in FirebaseBackend.swift
, run .useEmulator()
after declaration.
Use the DEBUG flag so it will only be included in development builds of your app.
import FirebaseFunctions
// ...
public class DB: ObservableObject {
// ...
let functions: Functions
// ...
init() {
functions = Functions.functions()
#if DEBUG
functions.useEmulator(withHost: "127.0.0.1", port: 5001)
#endif
// ...
}
// ...
}
// ....
Running the Emulator
From your /firebase-func
folder, run:
firebase emulators:start
Now, if everything went smoothly, you will see a following output in your terminal, telling about the relevant emulator URLs:
Go to http://localhost:4000
and see the Firebase Emulator Suite.
You can now test your functions locally, without affecting your live backend. (Things like the Firestore Database will also work locally!)
Local changes are also reflected immediately, so you can test your changes right away. Click here to see how to deploy your changes to the cloud.