Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database.

I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to the home page, otherwise direct them to the login page.

import '../styles/globals.css'
import { useAuthState } from "react-firebase-hooks/auth"
import { auth, db } from "../firebase"
import Login from "./login"

function MyApp({ Component, pageProps }) {

  const [user] = useAuthState(auth);

  

  return <Component {...pageProps} />;
}

export default MyApp

This is how my firebase.js file looks:

import firebase from 'firebase';


const firebaseConfig = {
    apiKey: "apikey",
    authDomain: "authdomain",
    projectId: "projectid",
    storageBucket: "storagebucket",
    messagingSenderId: "messagingsenderid",
    appId: "appid"
  };


const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();

const db = app.firestore();

const auth = app.auth();

const provider = new firebase.auth.GoogleAuthProvider();

export { db, auth, provider };

If anyone can assist me in resolving this issue, I would greatly appreciate it. Thank you in advance!

Answer №1

Currently, the firebase version has been updated to 9+ and changes have been made to the firebase hooks, altering the entire structure. To resolve this issue, you can simply navigate to your package.json file and update the "firebase" version to

"firebase": "8.0.0"
.

Next, locate the entry for "react-firebase-hooks" in the same package.json file and update its version to

"react-firebase-hooks": "^3.0.4"
from the current version.

After making these changes, proceed to your terminal and execute the command yarn install. This will effectively resolve the version discrepancies.

Answer №2

"database": "firebase",
"version": "8.2.1",

The setup described above was successful in resolving the issue at hand, despite encountering a discrepancy with my react-firebase-hooks version being ^5.0.0

Answer №3

To check if the user has been authenticated, you can verify whether the "user" is not null. If the "user" is not null, then the user has been authenticated. However, if the "user" is null, then the user has not been authenticated.

Approach 1

import '../styles/globals.css'
import { useAuthState } from "react-firebase-hooks/auth"
import { auth, db } from "../firebase"
import Login from "./login"

function MyApp({ Component, pageProps }) {

  const [user] = useAuthState(auth);

  if (user) {
    return <Component {...pageProps} />;
  } else {
    return <Login />;
  }
}

export default MyApp

Approach 2

If there are any errors, they will provide information on the location of the issue.

import '../styles/globals.css'
import { useAuthState } from "react-firebase-hooks/auth"
import { auth, db } from "../firebase"
import Login from "./login"

function MyApp({ Component, pageProps }) {

  const [user, loading, error] = useAuthState(auth);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!user) {
    return <Login />;
  }

  return <Component {...pageProps} />;
}

export default MyApp

Approach 3

If the previous methods did not work, attempt wrapping your "auth check" code within an "onAuthStateChange" function as shown below:

import '../styles/globals.css'
import { useEffect } from 'react';
import { useAuthState } from "react-firebase-hooks/auth"
import { auth, db } from "../firebase"
import Login from "./login"

function MyApp({ Component, pageProps }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    auth.onAuthStateChanged(function(currentUser) {
      if (currentUser) {
        setUser(currentUser)
      }
      setLoading(false);
    });
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (user) {
    return <Component {...pageProps} />;
  } else {
    return <Login />;
  }
}

export default MyApp

The variable "currentUser" represents the authenticated user.

Answer №4

Having trouble with a similar issue

I found the solution by navigating to the node_modules directory and updating react-firebase-hook from version 4.0.0 to 3.0.4.

Simply running yarn install resolved the problem for me...

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

Customizing form validation in React using Zod resolver for optional fields

I am currently working on creating a form using React-hook-form and zod resolver. My goal is to have all fields be optional, yet still required despite being marked as optional in the zod schema: const schema = z.object({ name: z.string().min(3).max(50 ...

The updating of Angular 2 CLI variables does not occur

As a complete newcomer to Angular 2, I recently attempted to start my first project using the Angular CLI. Unfortunately, I encountered some issues. It seems that the variables in my views are not updating as expected. I followed the typical steps: ng n ...

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...

Retrieve data from the Redux store within the getServerSideProps function in NextJS

I'm trying to access my Redux store in the getServerSideProps() function of my Next.js app to retrieve the user id stored in the Redux Store and preload user data. I have successfully implemented this on the client side using next-redux-wrapper, but w ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Utilizing JavaScript, HTML, and CSS to incorporate images within circular frames

After finding inspiration from this question about rotating objects around a circle using CSS, I decided to modify the code to include images of Earth orbiting the Sun. The challenge was to make one image orbit another like a planet circling its star. Ear ...

Tips for displaying data by using the append() function when the page is scrolled to the bottom

How can I use the append() function to display data when scrolling to the bottom of the page? Initially, when you load the page index.php, it will display 88888 and more br tags When you scroll to the bottom of the page, I want to show 88888 and more br ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Error: Preflight request returned a 405 HTTP status code when querying Ionic + CI backend

I am currently working on my first app using ionic with a codeigniter backend. However, I am encountering the "Response for preflight has invalid HTTP status code 405" issue in ionic + CI backend. Can anyone help me solve this problem? This is my controll ...

How can I change a ReactNode into a text format?

I am looking for a way to convert the following code snippet into a string while preserving Tailwind CSS and other elements. My project uses Next.js with TypeScript and Tailwind CSS. Input : export default function Header_1() { return ( <div clas ...

How can I verify if my discord.js bot has the necessary permissions from a server or channel?

I need to verify two things: Determine if my bot has a particular SERVER permission (return true/false based on the presence of that permission) Confirm if my bot possesses a specific CHANNEL permission (return true/false depending o ...

Guide to creating a ReactJS higher-order component using modern ES6 syntax

I´m attempting to create a ReactJS higher-order component using ES6 syntax. This is what I have so far: export const withContext = Component => class AppContextComponent extends React.Component { render() { return ( ...

In my Angular application, the Authentication JWT is securely stored by Firebase within the Session Storage. Does this implementation pose any security risks

In order to enhance the user experience of our Angular app, we have integrated Firebase Authentication with Session Persistence. This ensures that users don't need to log in again every time they refresh the page. As part of this process, we store the ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...

Capturing a part of the screen using JavaScript for screen recording

I'm exploring the possibility of implementing a JavaScript screen recorder that captures a video feed rather than the entire screen. I'm wondering if it's achievable using getDisplayMedia or if there's a specific library for this purpos ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Choosing comparable choices from the drop-down menu

I am working on a dropdown menu that contains different options. I need to use jQuery to automatically select the option that corresponds to the branch of the currently logged in user. However, when some option text is very similar, it causes an issue. // ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...