0

I'm looking for a secure way to handle API keys in my NextJS web app using Firebase.

I see the suggestion to "hide" the keys in an ENV file then make sure of the variables by calling something like process.env.NEXT_PUBLIC_MYSUPERSECRETKEY. This will still reveal the key in the source code when it renders on the client browser.

... 
const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
}
... 

I tried to use the process.env.FIREBASE_API_KEY (with the .env.local file defining FIREBASE_API_KEY) form to keep the variable server-side but Firebase throws an error:

FirebaseError: Firebase: Error (auth/invalid-api-key).

I looked at some code on GitHub and saw people were defining the ENV in the next.config.js file but that has the same result of showing on the client-side as well:

next.config.js

module.exports = {
  env: {
    API_KEY: process.env.FIREBASE_API_KEY,
  },
}  

.env.local

FIREBASE_API_KEY="XXX" 

firebaseApp.js

... 
const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,  
... 

https://nextjs.org/docs/api-reference/next.config.js/environment-variables

engineer-x
  • 2,173
  • 2
  • 12
  • 25
  • That web config is meant to be public and you won't be able to initialize Firebase "Client" SDK without that. Check the linked answer for more information. – Dharmaraj Jan 06 '23 at 07:11

1 Answers1

0

When you choose a hosting platform, for example we will use vercel.

You will more than likely point vercel towards your GitHub repo for it to build the application from.

When configuring the project on vercel, in the project settings there will be fields to enter your environment variables into. This will take care of the potential security issue you are seeing.

See here: https://nextjs.org/docs/basic-features/environment-variables

Venex
  • 101
  • 7