The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and define the login and logout functions.

This is the content of the firebase-config.js file located in the project root:

import { initializeApp } from 'firebase/app';
import { initializeAuth, browserLocalPersistence, browserPopupRedirectResolver, indexedDBLocalPersistence, signInWithRedirect, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID
};

export const app = initializeApp(firebaseConfig);

export const auth = initializeAuth(app, {
  persistence: [indexedDBLocalPersistence, browserLocalPersistence],
});

export const getUserFirebase = () => {
  return auth.currentUser;
};

export const loginFirebase = () => {
  signInWithRedirect(auth, new GoogleAuthProvider(), browserPopupRedirectResolver);
};

export const logoutFirebase = () => {
  signOut(auth);
};

Below is the auth.js component:

import { useRouter } from 'next/router';
import { useState } from 'react';
import { IconButton, Menu, MenuItem, Button, Box } from '@mui/material';
import { AccountCircle, Logout, ManageAccounts, RateReview, Google } from '@mui/icons-material';
import { getUserFirebase, loginFirebase, logoutFirebase } from '../firebase-config';


export const Auth = () => {
  const router = useRouter();

  const [anchorEl, setAnchorEl] = useState(null);
  const handleMenu = (event) => setAnchorEl(event.currentTarget);
  const handleClose = () => setAnchorEl(null);
  const redirectFromMenu = (url) => {
    handleClose();
    router.push(url);
  };

  return (
    <Box sx={{ marginLeft: 'auto' }}>
      {getUserFirebase() ? (
        <>
          <IconButton
            size="large"
            aria-label="account of current user"
            aria-controls="menu-appbar"
            aria-haspopup="true"
            onClick={handleMenu}
            color="inherit"
          >
            <AccountCircle />
          </IconButton>
          <Menu
            id="menu-appbar"
            anchorEl={anchorEl}
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
            keepMounted
            transformOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
            open={Boolean(anchorEl)}
            onClose={handleClose}
          >
            <MenuItem onClick={() => redirectFromMenu('/account')}><ManageAccounts /> My Account</MenuItem>
            <MenuItem onClick={() => redirectFromMenu('/reviews/write')}><RateReview /> Write Review</MenuItem>
            <MenuItem onClick={logoutFirebase}><Logout /> Logout</MenuItem>
          </Menu>
        </>
      ) : (
        <Button size='small' onClick={loginFirebase} startIcon={<Google />} variant='contained' color='secondary'>
          Login with Google
        </Button>
      )}
    </Box>
  );
};

When trying to log the auth object, it shows an error stating:

'dependent-sdk-initialized-before-auth': 'Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call initializeAuth or getAuth before beginning any other Firebase SDK.'

The app either crashes at startup or faces this issue during authentication. Any assistance would be greatly appreciated.

Answer №1

Assuming you're not utilizing Server-Side rendering, it's important to expose environment variables to the browser.

To do this, you must prefix the variable with NEXT_PUBLIC_.

In your configuration file,

NEXT_PUBLIC_FIREBASE_API_KEY=******************
...
...

You can then access it in your application like this:

apiKey:  process.env.NEXT_PUBLIC_FIREBASE_API_KEY

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

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

Using knockout to data bind a function to an onclick event that takes in multiple parameters

I've scoured the internet and experimented with various methods, but I'm encountering an issue where the click function intermittently fails to fire. Below is my HTML code snippet: <input type="radio" data-bind="checked:a, checkedValue: 0 ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Unable to connect to React Node Socket.IO application from any source other than localhost using IPv4 and NGROK

I recently followed a tutorial on creating a simple React app/Node with Socket.IO. The tutorial worked perfectly, so I decided to test it with two other devices: One PC on the same wifi network (via IPv4 - 192.168.1.8:3000) A mobile device using Ngrok tun ...

Transmitted only JSON data instead of using multiform data with jQuery Ajax

When I use jQuery Ajax to send a JSON object, it ends up being interpreted as 'multiform' instead of pure JSON. How can I make sure my request is sent as a pure JSON object and not multiform? var demo = new Array("One", "Two", "Three"); $.ajax ...

Creating a foolproof image polling platform: A step-by-step guide

I'm in the process of creating a webpage on my site that allows users to view a collection of images. The goal is for each registered user to choose one picture as their favorite, increasing that picture's score by one. The image with the highest ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Label it as submit ID rather than value or label

Check out this awesome plugin called https://github.com/aehlke/tag-it. It's really cool! Here is the issue I'm facing: <input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true"> Tags:<br ...

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

Can a javascript variable be accessed after loading an iframe and returning to the page?

Using a jquery plugin known as colorbox, my colorbox simply opens an iframe on the screen. This detail may not be relevant, as the core issue at hand is that I have 3 variables on my parent window that are retrieved from an AJAX call using jquery: data.re ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...

Tips for modifying the color or personalizing the header arrow for the expandableRow within Mui Datatable

My MUI data table has the expandable rows option, along with an ExpandAll button in the header row. The arrow displayed in the title row is confusing for users as it's similar to the arrows in all other rows. I want to change the color of the header a ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

"Create a Vue element containing a trio of buttons each displaying a distinct numeral

I am currently dealing with a component that generates three items (boxes) each containing three buttons (created using v-for). The issue I am facing is that when I click on a button, all the numbers inside the buttons change simultaneously. I want to be a ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

Problem with exporting data from the API to a JavaScript file in Excel format

Instead of receiving actual data in the response, I am getting a set of characters. However, everything works fine when I click on Download file in swagger. Can someone help me diagnose the issue? function downloadDocFile(data: Blob, ext = 'xlsx' ...