简体   繁体   中英

How to access environment variables from JSON file?

I am using firebase authentication in my nextjs app. I have stored my service account credentials in a file called secret.json. I wanna hide those credentials in my next.config.js file. How can I access those credentials in the secret.json file? Maybe this will be the same approach not only for nextjs apps but also for other apps. What is the common way to achieve that or is there any specific way for nextjs app?

You might consider storing your private key as an environment variable, which Next.js has built-in support for. You can then avoid the risks of exposing your secrets in next.config.js and services like Heroku andVercel make it easy & secure to store your env vars in production.

To initialize Firebase on your server, you need just 3 things from your secret.json file:

  • project_id
  • client_email
  • private_key - store this as an env var (eg, FIRESTORE_PRIVATE_KEY)

You can then use the firebase-admin package to initialize Firebase on your server:

import { cert, initializeApp } from 'firebase-admin/app'

const serviceAccount = {
  projectId: 'my-project',
  clientEmail: 'myServiceAccount@my-project.iam.gserviceaccount.com',
  privateKey: process.env.FIRESTORE_PRIVATE_KEY,
}

const credential = cert(serviceAccount)

initializeApp({ credential })    

Saving the private_key as its own env var will also avoid problems arising from attempting to save/parse the entire Firestore json as an env var (eg, ENAMETOOLONG error) and not require you to do any string manipulation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM