Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize correctly Firebase admin SDK in Atlas trigger (Node JS)

I am trying to send a firebase admin push notification from my Atlas trigger.

The firebase admin sdk requires initialization by file (i could not find any documentation on how to do differently) so here is the code i have got so far :

const admin = require("firebase-admin");
const json_creds = context.values.get("admin_key");

 admin.initializeApp({
      credential: admin.credential.cert(json_creds)
    });

This throws the following error :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"message":"Failed to parse service account json file: FunctionError: file not found: {   \"type\": \"service_account\",   \"project_id\":........}

So i understand from this that admin.credential.cert() takes a file as input and not a String, however in Atlas trigger i have store the value as a secret and linked it to a value to be retrieved from context.values.

To solve my problems i have two different questions :

  1. How to initialize the firebase admin SDK from the content of the service_account.json and not from file but from an accessible String value such as an env var i could set in Atlas Trigger ?
  2. OR : How to store a file to be read from the context in Atlas Trigger ?

Thanks a lot in advance !

>Solution :

If you are passing a string to cert(), then that should be path to a file and as the error suggest the provided path does not exists (it seems a stringified JSON). Instead you can parse the string and pass an object as shown below:

admin.initializeApp({
  credential: admin.credential.cert(JSON.parse(json_creds))
});

In case of Typescript, you can assert that provided object is a ServiceAccount like this:

admin.credential.cert(JSON.parse(json_creds) as ServiceAccount)

Alternatively, you can store each key of a service account separately like:

const fb_project_id = context.values.get("project_id");
const fb_private_key = context.values.get("private_key");

admin.initializeApp({
  credential: admin.credential.cert({
    project_id: fb_project_id,
    private_key: fb_private_key
  })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading