I'm using the new middleware in nextjs 12 and am trying to add authentication using firebase.
But when i try to use the hook useAuthState it's giving me an error saying: "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. null"
I have not made any changes in the app other than creating 2 components both in pages directory
login.js and _middleware.js
here is my _middleware.js
import { NextResponse } from "next/server";
// import firebase from "firebase"
import { initializeApp } from "firebase/app";
import "firebase/auth";
import { getAuth } from "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
initializeApp({ ... });
const auth = getAuth();
export async function middleware(req) {
const [user] = useAuthState(auth);
const { pathname } = req.nextUrl;
if (!user) {
return NextResponse.redirect("/login");
}
return NextResponse.next();
}
Here is my login.js
function login() {
const signInWithGoogle = () => {
console.log("Clicked!");
};
return (
<div>
<button onClick={signInWithGoogle}>Sign in with google</button>
</div>
);
}
export default login;
And here's my package.json
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"firebase": "^9.5.0",
"next": "^12.0.4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-firebase-hooks": "^4.0.1"
},
"devDependencies": {
"autoprefixer": "^10.2.6",
"postcss": "^8.3.5",
"tailwindcss": "^2.2.4"
}
}