简体   繁体   中英

Next.js app crashes when attempting to implement google firebase authentication

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM