Error: Firebase encountered an issue (auth/invalid-api-key) while deploying on Netlify

I'm currently working on a Next.js application that utilizes Firebase Auth for client authentication and is hosted on Netlify.

firebaseConfig.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

The code snippet below verifies ID tokens using the "firebase-admin" library.

firebaseAdmin.js

var admin = require("firebase-admin");
var serviceAccount = require("./secrets.json");

export const verifyIdToken = (token) => {
    if (!admin.apps.length){
        admin.initializeApp({
            credential: admin.credential.cert(serviceAccount),
        })
    }
    return admin.auth().verifyIdToken(token).catch((err) => console.log(err))
}

The following code snippet handles global user state and manages cookies.

auth.js

import { createContext, useState, useEffect, useContext } from "react"
import { onIdTokenChanged } from "firebase/auth"
import { auth } from './firebaseConfig'
import nookies from 'nookies'

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
    
    const [user, setUser] = useState(null);

    useEffect(() => {
        return(onIdTokenChanged(auth, async (user) => {
                if(!user){
                    setUser(null);
                    nookies.set(undefined,"token", "", {});
                    return
                }
                const token = await user.getIdToken(true);
                setUser(user);
                nookies.set(undefined,"token", token, {});
        }))
    },[]);

    return(<AuthContext.Provider value={{ user }}>{ children }</AuthContext.Provider>);
}

export const useAuth = () => useContext(AuthContext);

While everything works fine during development, deployment on Netlify results in the following error:

7:25:04 AM: FirebaseError: Firebase: Error (auth/invalid-api-key).
7:25:04 AM:     at createErrorInternal (file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:467:40)
7:25:04 AM:     at _assert (file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:471:15)
7:25:04 AM:     at file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:6075:13
7:25:04 AM:     at Component.instanceFactory (file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:6092:11)
7:25:04 AM:     at Provider.getOrInitializeService (file:///opt/build/repo/node_modules/@firebase/component/dist/esm/index.esm2017.js:290:39)
7:25:04 AM:     at Provider.initialize (file:///opt/build/repo/node_modules/@firebase/component/dist/esm/index.esm2017.js:234:31)
7:25:04 AM:     at initializeAuth (file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:585:27)
7:25:04 AM:     at getAuth (file:///opt/build/repo/node_modules/@firebase/auth/dist/node-esm/index-1491e429.js:6141:18)
7:25:04 AM:     at /opt/build/repo/.next/server/chunks/373.js:82:68 {
7:25:04 AM:   code: 'auth/invalid-api-key',
7:25:04 AM:   customData: { appName: '[DEFAULT]' }
7:25:04 AM: }
7:25:04 AM: > Build error occurred
7:25:04 AM: Error: Failed to collect page data for /
7:25:04 AM:     at /opt/build/repo/node_modules/next/dist/build/utils.js:949:15 {
7:25:04 AM:   type: 'Error'
7:25:04 AM: }

My .env.local file has all the correct Firebase values, but I'm still unable to pinpoint the cause of the error.

Answer №1

The reason for this issue is likely due to Netlify not being aware of your environment variables when deploying. To resolve this, ensure that you also include these environment variables from the .env.local file in Netlify. Simply navigate to the Build & Deploy settings within your Netlify Site Settings and input your values into the "Environment variables" section.

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

Implementing adaptive window.scrollY listener in React to account for different screen sizes

I am currently using a useEffect hook to create a fade-in effect for text based on scroll position. While this works perfectly on my 27-inch MAC screen, I am facing challenges when viewing it on a smaller screen. I am unsure how to adjust the useEffect to ...

Guide on Showcasing Countries on a Global Map with Various Colors Using react-svg-map

I'm currently working on a project that involves highlighting specific countries on a world map. The default color for the countries is light blue, but I need to change it to dark blue for the highlighted ones. Although the library I'm using has ...

The label for Firebase Admin Cloud Messaging Analytics is missing from the reports section

I have been facing an issue while sending push notifications to the app users through the firebase cloud messaging service. The notifications are being successfully delivered, but the analytics label is not appearing under the Reports tab as expected. Belo ...

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

When a user clicks on a specific element's id, the image will rotate accordingly

When the elements in ul are clicked, the image rotates. The default position of the image is already rotated by a certain number of degrees, and on each click, it rotates to the desired value. This was achieved using the following code: $("#objRotates"). ...

The process of incorporating a function into a website's source code using a web driver

In the source code, there is a button with an onclick event to change the paragraph content. However, the code provided does not seem to be functioning properly. ((JavascriptExecutor) this) .executeScript("function test123() { y=docume ...

Creating personalized error messages for API endpoints in Next.js

I'm looking to implement custom error responses for errors like 404 and 500 in my Next.js application. While I know that I can create custom error pages within the /pages directory, I specifically need JSON format for errors on my pages/api endpoints. ...

Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method. for (let i = 0; i < this.prodList.length; i++) { let setContent = false; for ...

Unable to proceed with entering subsequent values into the input field after the initial input in reactjs

Issue with login form: Unable to provide second value after entering the first one. The text input field does not allow for entering more than one value before completing the existing entry. import React, { useCallback } from 'react'; import { Te ...

Broadening the capabilities of jQuery through a versatile function

Currently, I am in the process of developing a generic function for my website using jQuery that will be utilized across the entire site to display success or error messages. After careful consideration, I have decided to transform this function into a plu ...

Is there a framework available to animate Pseudo CSS elements?

Recently, I was working on developing a bar chart that utilized pseudo CSS elements (::before, ::after). While I successfully created bars that look visually appealing, I encountered a challenge when attempting to animate the height changes. Whenever I us ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Clicking on an anchor tag will open a div and change the background color

.nav_bar { background: #c30015; margin-left: 50px; float: left; } .nav_bar ul { padding: 0; margin: 0; display: flex; border-bottom: thin white solid; } .nav_bar ul li { list-style: none; } .nav_bar ul li a { ...

The required validator in Mongoose is not being triggered by the function

I'm trying to use a function as a validator in a mongoose schema, but it doesn't seem to work if I leave the field empty. The documentation states: Validators are not run on undefined values. The only exception is the required validator. You ...

Incorporating External Content into Your HTML Website

Looking to incorporate third-party content in the form of an HTML page within my own website, I considered utilizing iframes. This would allow me to embed the external HTML page within my site while keeping their libraries and CSS separate from mine. Howe ...

Tips on modifying the main color of an application through the UI in React JS (Next JS) with the help of tailwind CSS

If the primary color of each button is initially set to bg-gray-600, and you want to change it to bg-indigo-600</ode>, attempting to use template literals seems ineffective in altering the UI.</p> <pre><code>const customizeButton = ...

Aggregate the values in each position across various arrays and merge them into distinct arrays

I'm facing an issue that I can't seem to solve on my own. Imagine we have several arrays: [1,2,3] [1,2,3] [11,12,13] How do I go about extracting all the values at each index from these multiple arrays and combining them into separate arrays? T ...

Creating a CSS animation to mimic the fading in and out effect of the Mac scrollbar when scrolling begins

My journey begins with this: *::-webkit-scrollbar { } *::-webkit-scrollbar-button { } *::-webkit-scrollbar-track { } *::-webkit-scrollbar-track-piece { } *::-webkit-scrollbar-thumb:active { width: 6px; background-color: red; } *::-webkit-scr ...

Unable to locate the module 'winston'

Developed a small module that utilizes winston for logging purposes. Installed winston using sudo npm install -g winston (since it's on a virtual machine, not too concerned with sudo permissions). NPM log: <a href="/cdn-cgi/l/email-protection" c ...