0

I am running into an issue while trying to implement authentication with firebase (via google) within my next.js app, and am consistently seeing the app crash. I will show the code for the auth.js page component, as well as where I configure firebase and define the login and logout functions.

Here is the firebase-config.js file which is stored in the root of the project:

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


const firebaseCredentials = {
  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(firebaseCredentials);

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

Here 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 />&nbsp;My Account</MenuItem>
            <MenuItem onClick={() => redirectFromMenu('/reviews/write')}><RateReview />&nbsp;Write Review</MenuItem>
            <MenuItem onClick={logoutFirebase}><Logout />&nbsp;Logout</MenuItem>
          </Menu>
        </>
      ) : (
        <Button size='small' onClick={loginFirebase} startIcon={<Google />} variant='contained' color='secondary'>
          Login with Google
        </Button>
      )}
    </Box>
  );
};

When attempting to log the auth object, it contains an error that states:

'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 starting any other Firebase SDK.'

The app either gets killed on startup, or this occurs when trying to authenticate. Any help would be much appreciated

1
  • Does this error persist if you leave out the auth persistence? Commented Sep 27, 2022 at 4:37

1 Answer 1

1

I am assuming you are not using Server-Side rendering. If so, you need to expose those environment variables to the browser.

In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_.

In your env file,

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

and you can access in your app like below,

apiKey:  process.env.NEXT_PUBLIC_FIREBASE_API_KEY
Sign up to request clarification or add additional context in comments.

2 Comments

After adding this to all the environment variables, it is just getting "killed" on start up
I realised that I was running out of memory haha. This worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.