0

So I am using firebase-admin in Next Js. I used environment variables but can't hide the firebase service account keys because they are not defined in server-side on Next JS. So i had to use NEXT_PUBLIC environment variables. And NEXT_PUBLIC environment variables can be accessed and viewed in client side.

This is my firebase-admin file

const firebase = require("firebase-admin");
const { fireStore, getFirestore } = require("firebase-admin/firestore");
import { adminConfig } from "./serviceAccountKey";

if (!firebase.apps.length) {
      firebase.initializeApp({
      credential: firebase.credential.cert(adminConfig),
      });
}
export const db = getFirestore();

export default firebase;

And this is how my config object looks like.

export const adminConfig = {
      type: process.env.NEXT_PUBLIC_FIREBASE_TYPE,
      project_id: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      private_key_id: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY_ID,
      private_key: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY,
      client_email: process.env.NEXT_PUBLIC_FIREBASE_CLIENT_EMAIL,
      client_id: process.env.NEXT_PUBLIC_FIREBASE_CLIENT_ID,
      auth_uri: process.env.NEXT_PUBLIC_FIREBASE_AUTH_URI,
      token_uri: process.env.NEXT_PUBLIC_FIREBASE_TOKEN_URI,
      auth_provider_x509_cert_url:
      process.env.NEXT_PUBLIC_FIREBASE_AUTH_PROVIDER_CERT_URL,
      client_x509_cert_url: process.env.NEXT_PUBLIC_FIREBASE_CLIENT_CERT_URL,
};

So How do i hide the config data. Or is it alright even if it is public?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • 3
    No, the service account credentials **MUST NOT** be public so do remove `NEXT_PUBLIC_` so they cannot be access on client side. – Dharmaraj Sep 09 '22 at 06:05
  • IF i remove NEXT_PUBLIC, i cannot access them in my config file as the config file gets stored in client side. And i cannot store the config file under next js api folder because it creates a route for every file inside api folder. – Pritam Upadhya Sep 29 '22 at 10:16

1 Answers1

1

I managed to do this in NextJS some time back (hopefully it's still relevant) - try this:

Store your secrets as environment variables in a .env file.

In your next.config.js load the environment variables in publicRuntimeConfig

publicRuntimeConfig: {
  PRIVATE_KEY: process.env.FIREBASE_PRIVATE_KEY_ID,
  PRIVATE_KEY_ID: process.env.FIREBASE_PRIVATE_KEY
    }

Then in your client side React:

import getConfig from 'next/config';
const {publicRuntimeConfig} = getConfig();

const private_key = publicRuntimeConfig.PRIVATE_KEY
const private_key_id = publicRuntimeConfig.PRIVATE_KEY_ID

EDIT: Actually, now that I think about it, I used this method for things that didnt require absolute security like API_URIs.

Secrets stored/accessed like this will still be exposed to inspection in the browser.

For anything that requires securely storing secrets, definitely perform them on server-side.

limco
  • 1,310
  • 1
  • 15
  • 24