Escaping issue with firebase privateKey as a Heroku config variable

后端 未结 3 1570
南笙
南笙 2020-12-13 14:03

I\'m trying to create an Heroku node task that reads data from Firebase and console.log it.

My node script (located inside the /bin directory) is:

re         


        
相关标签:
3条回答
  • 2020-12-13 14:21

    I had the same problem today. You need to sanitize the read private key by replacing \\n characters with \n.

    admin.initializeApp({
      credential: admin.credential.cert({
        "projectId": process.env.FIREBASE_PROJECT_ID,
        "private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
        "clientEmail": process.env.FIREBASE_CLIENT_EMAIL,
      }),
      databaseURL: process.env.FIREBASE_DATABASE_URL,
    });
    
    0 讨论(0)
  • 2020-12-13 14:21

    I solved this by using the .replace(/\n/g, '\n') on the private key and also removing the quotes from the private key value on heroku config vars like it is bellow.

    -----BEGIN PRIVATE KEY-----\nMY-PRIVATE-KEY\n-----END PRIVATE KEY-----\n

    0 讨论(0)
  • 2020-12-13 14:35

    In my case I solved it by converting FIREBASE_PRIVATE_KEY to a base64 string, then I saved this new string as an environment variable in Heroku. In my code, I converted the base64 FIREBASE_PRIVATE_KEY to the original private key again.

    const firebase_private_key_b64 = Buffer.from(process.env.FIREBASE_PRIVATE_KEY_BASE64, 'base64');
    const firebase_private_key = firebase_private_key_b64.toString('utf8');
    
    admin.initializeApp({
        credential: admin.credential.cert({
            "project_id": process.env.FIREBASE_PROJECT_ID,
            "private_key": firebase_private_key,
            "client_email": process.env.FIREBASE_CLIENT_EMAIL,
        }),
        databaseURL: process.env.FIREBASE_DATABASE_URL
    });
    
    0 讨论(0)
提交回复
热议问题