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

Steps for initializing input field with pre-existing values using Redux form

After reviewing the Redux Form documentation, I noticed that the example provided only fetches initial values upon button click. However, my requirement is to have these values available immediately when the page loads. In my current setup, I can successf ...

Issues with websockets functionality have been reported specifically in Firefox when trying to connect to multiple

I am currently working on a websocket client-server application. The client code is as follows: const HOST = "wss://localhost:8000"; const SUB_PROTOCOL= "sub-protocol"; var websocket = new WebSocket(HOST, SUB_PROTOCOL); websocket.onopen = function(ev ...

After each animation in the sequence is completed, CSS3 looping occurs

I have currently set up a sequence of 5 frames, where each frame consists of 3 animations that gradually fade into the next frame over time. My challenge is figuring out how to loop the animation after completing the last sequence (in this case, #frame2). ...

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

What sets apart the npm packages @types/express and express?

Can't decide whether to use @types/express or express for building a node server? Take a look at the code snippet below: 'use strict'; const express = require('express'); const http = require('http'); const path = requir ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

Requiring three parameters, yet received four

Encountering an error in the dashboard.tsx file while trying to implement a line of code: "const { filteredEvents, stats, tableApps, formattedDate } = filterData(dataAll, Prefix, listApp, dateSelected);" The issue arose with the dateSelected parameter resu ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

What is the best way to incorporate React Odometerjs into a Next.js project?

It's quite disheartening that despite spending 3 days trying, I still can't seem to successfully integrate Odometer js into my Next js project. I'm at a loss as to where I might be going wrong in my code. Here is the code I've been work ...

Utilize AngularJS to retrieve and interact with the JSON data stored in a local file once it has

Please do not mark this as a duplicate since I have not found a solution yet. Any help would be appreciated. I have a file called category.json located next to my index.html file, containing the following JSON data: [{"name":"veg"},{"name","non-veg"}] W ...

Error: Unable to access the `insertUsername` property as it is not defined

When I attempt to submit the login form created by the new.ejs file, instead of being redirected to the expected page, I am encountering an error message that reads: Cannot read property 'insertUsername' of undefined This same error message is ...

Is the each() method in jQuery essentially a for loop?

Experimenting with adding a serialized class to a group of objects, I attempted the following approach: jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="&apos ...