Tips for securing firebase-admin credentials in Next Js

I've encountered a challenge while using firebase-admin in Next Js. I attempted to hide the firebase service account keys using environment variables, but ran into an issue because they are not defined in server-side on Next JS. As a workaround, I had to resort to using NEXT_PUBLIC environment variables, which unfortunately can be accessed and viewed in the client side.

Below is a snippet of 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;

Here is how my config object is structured:

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,
};

Now the conundrum lies in how to conceal the config data. Is it acceptable for it to be public?

Answer №1

A while ago, I successfully implemented this in NextJS - give it a shot:

Store your confidential information as environment variables in a .env file.

In your next.config.js, access the environment variables in publicRuntimeConfig

publicRuntimeConfig: {
  PRIVATE_KEY: process.env.SECRET_KEY_ID,
  PRIVATE_KEY_ID: process.env.SECRET_KEY
    }

Next, in your client-side React code:

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

const secret_key = publicRuntimeConfig.PRIVATE_KEY
const secret_key_id = publicRuntimeConfig.PRIVATE_KEY_ID

NOTE: Upon reflection, I originally used this approach for non-security critical tasks like API endpoints.

Remember, information stored and accessed in this manner can potentially be viewed by inspecting the browser.

For sensitive data that requires secure storage, it is best to handle it on the server-side.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to determine when AJAX-loaded content has completely loaded all of its images?

After making an AJAX request to load HTML, it includes img tags within it. I am in need of a way to detect when these images have finished loading so that I can adjust the container size accordingly. Since I do not know how many images will be present in ...

An automatic selection in my AngularJS drop-down menu

I am currently utilizing AngularJS to develop a basic web application. My goal is to have the values of city A displayed as the default choice in my select dropdown. index.html <body ng-controller="MainCtrl"> <select ng-model="selectedCity" ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

What is the best way to use AJAX to update multiple items with a common customer number on a SharePoint list?

Currently, I am facing an issue while attempting to update a SharePoint list using JavaScript/ajax. The script is running smoothly until it reaches the ajax function, where it encounters a failure. Specifically, it mentions that the ItemID is not defined, ...

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...

JavaScript code to place variables into an array with included variables

Looking for a solution: const myArray = [] myArray.push( { "bob" : { "banana" : "yellow" } }) console.log(myArray) Output: { "bob": { "banana": "yellow" } } Attempting a modifi ...

Tips for transmitting variable values through a series of objects in a collection: [{data: }]

How to pass variable values in series: [{data: }] In the code snippet below, I have the value 2,10,2,2 stored in the variable ftes. I need to pass this variable into series:[{data: }], but it doesn't seem to affect the chart. Can anyone guide me on ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Error message encountered in the latest deployment on Vercel Next 13: "EROFS: read-only file system" issue

Currently, I have a Next.js 13 API route set up to write a list of users to a file and another route that reads from the user's JSON file. const USERS_FILE_PATH = join(process.cwd(), '/tmp', 'data.json'); fs.writeFileSync(POSTS_FIL ...

Capturing Vuejs data for various pathways

Currently, I am developing a Vue file that contains the following code: <router-link :to="{name: 'detailed'}" tag='li' @click='getData("test")'> testing</router-link> In the script section, the code looks like th ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

When you delete a property from a duplicated version of an Object in JavaScript, it ends up impacting the original Object as

Let's imagine we have an array of objects, var data = [{ "sss": "sssssss", "yyy": "ssdsdsds", "www": "1212121", "Group": "Mango" }, { "sss": "sssssss", "yyy": "ssdsdsds", "www": "1212121", "Group": "Mango" }] The desi ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Having trouble retrieving the latest cache data within a component of a server-rendered Next.js Apollo application

Recently, I encountered an issue with my nextjs apollo server-rendered application that uses apollo client state. The problem arises when the local state is updated correctly upon app load, but the graphql query called in the header component seems to retu ...

What is the method to execute a prototype function within another prototype?

I am facing an issue with my JavaScript class and need some help to resolve it. MyClass.prototype.foo = function() { return 0; } MyClass.prototype.bar = function() { return foo() + 1; } Unfortunately, when I try to run the program, it throws an ...

Expecting function to return an undefined response object

My experience with async/await is limited, but I have used these keywords in a function that retrieves or posts data to a MongoDB database. However, it seems like the await keyword does not wait for the promise to be fulfilled and instead returns an undefi ...

Authorization missing in Select2 Ajax request

Encountering an issue while attempting a get request to a secure endpoint that requires an Auth token. Despite fetching the token asynchronously from chrome.storage, it fails to be included in the ajax request and results in a 401 error ("Authorization hea ...