skip to Main Content

We use Firestore for our DB and use Vercel’s Next.js hosting. We wanted a completely isolated development / production DBs, so we set up two separate projects on Firebase, and this gave us two different API keys for each of the projects.

What is the best way to switch between the two configs depending on the Vercel’s production / preview / development settings (perhaps based on NEXT_PUBLIC_VERCEL_ENV)?

We tried creating two different .json files containing the configs, and switching based on the NEXT_PUBLIC_VERCEL_ENV environment variable, but this seems to yield an undefined value for the environment variable on the client rendered pages in my local development build.

const firebaseDevConfig = await import("./configs/dev-config.json");
const firebaseProdConfig = await import("./configs/prod-config.json");

const firebaseConfig =
  process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
    ? firebaseProdConfig
    : firebaseDevConfig;

Update: It seems that the NEXT_PUBLIC_VERCEL_ENV returns the expected value "preview" in the deployed preview version. How do I get it to return "development" in my local dev build?

2

Answers


  1. Chosen as BEST ANSWER

    I managed to work around this issue by storing the development config as a string in the .env file and also setting up the production environment variable through Vercel's dashboard.

    The final code looked something like this:

    export const firebaseConfig = JSON.parse(
      process.env.NEXT_PUBLIC_FIREBASE_CONFIG!
    );
    

    where NEXT_PUBLIC_FIREBASE_CONFIG is the name of the environment variable containing the dev/prod Firebase configs as a JSON string.


  2. Are you using .local.env file or just .env? Also, I recommend setting up the firebase CLI and emulators see –> https://firebase.google.com/docs/emulator-suite

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search