How do I add Google Application Credentials/Secret to Vercel Deployment?

Viewed 2665

I am using Vercel Deployments with a NextJS app. Deployments are automatically run when I push to master, but I don't want to store keys in GitHub. My serverless functions are reliant on my database. When run locally, I can simply use Google's Default Authentication Credentials, but this is not possible when deployed to Vercel. As such, I created a Service Account to enable the server to have access.

How do I load the service account credentials without pushing they key itself to GitHub?

3 Answers

Rather than using a path to a JSON file, you can create an object and include environment variables as the values for each object key. For example:

admin.initializeApp({
  credential: admin.credential.cert({
    client_email: process.env.FIREBASE_CLIENT_EMAIL,
    private_key: process.env.FIREBASE_PRIVATE_KEY,
    project_id: 'my-project'
  }),
  databaseURL: 'https://my-project.firebaseio.com'
});

Then, you can add the environment variables inside your project settings in Vercel.

Adding to @leerob's answer, I found that putting quotes around the FIREBASE_PRIVATE_KEY environment variable in my .env file fixed an error I kept getting relating to the PEM file when making a request. I didn't need any quotes around the key for calls to the standard firebase library though.

This was the config I used to access the Google Cloud Storage API from my app:

const { Storage } = require('@google-cloud/storage');

const storage = new Storage({ projectId: process.env.FIREBASE_PROJECT_ID,
                              credentials: { client_email: process.env.FIREBASE_CLIENT_EMAIL,
                                              private_key: process.env.FIREBASE_PRIVATE_KEY_WITH_QUOTES
                                            } 
                            })

I had this problem too but with google-auth-library. Most of Googles libraries provide a way to add credentials through a options object that you pass when initializing it. To be able to get information from Google Sheets or Google Forms you can for example do this:

const auth = new GoogleAuth({
  credentials:{
    client_id: process.env.GOOGLE_CLIENT_ID,
    client_email: process.env.GOOGLE_CLIENT_EMAIL,
    project_id: process.env.GOOGLE_PROJECT_ID,
    private_key: process.env.GOOGLE_PRIVATE_KEY      
  },
  scopes: [
    'https://www.googleapis.com/auth/someScopeHere',
    'https://www.googleapis.com/auth/someOtherScopeHere'
  ]
});

You can just copy the info from your credentials.json file to the corresponding environment variables. Just take care that when your working on localhost you will need to have the private_key in double quotes but when you put it into Vercel you should not include the quotes.

Related