Authentication
Firebase
For NextJS

How to use Firbase ?

Note: The uko template uses the firebase authentication system by default.

  • Step-1 : Visit Google Console (opens in a new tab). Create a project next, then gather configuration data from it and add it to the .env file.

  • Step-2 : Open the src/app/layout.jsx file then import the AuthProvider from contexts/firebaseContext and wrap the Root Layout component with it.

  • Step-3 : Open the src/hooks/useAuth.js file. Thereupon, import the AuthContext from src/contexts/firebaseContext then pass it as an argument in the useContext hook.

  • Step-4 : Call the useAuth hook inside AuthGuard, GuestGuard components, Login, Register page etc.

Step 1


_10
REACT_APP_FIREBASE_APT_KEY=
_10
REACT_APP_FIREBASE_AUTH_DOMAIN=
_10
REACT_APP_FIREBASE_DATABASE_URL=
_10
REACT_APP_FIREBASE_PROJECT_ID=
_10
REACT_APP_FIREBASE_STORAGE_BUCKET=
_10
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=
_10
REACT_APP_FIREBASE_APP_ID=
_10
REACT_APP_FIREBASE_MEASUREMENT_ID=

Step 2

layout.jsx

_10
import { AuthProvider } from "contexts/firebaseContext";
_10
_10
const RootLayout = ({ children }) => {
_10
return <AuthProvider>{children}</AuthProvider>;
_10
};
_10
_10
export default RootLayout;

Step 3

useAuth.js

_10
import { AuthContext } from "contexts/firebaseContext";
_10
_10
const useAuth = () => useContext(AuthContext);
_10
export default useAuth;

Step 4

page.jsx

_18
import useAuth from "hooks/useAuth";
_18
_18
const Login = () => {
_18
const { signInWithEmail, signInWithGoogle } = useAuth();
_18
_18
const onLogin = async () => {
_18
await signInWithEmail("example@email.com", "pass123"); // Login crediential
_18
};
_18
_18
return (
_18
<Box>
_18
<Button onClick={onLogin}>Login</Button>
_18
<Button onClick={signInWithGoogle}>Login with Google</Button>
_18
</Box>
_18
);
_18
};
_18
_18
export default Login;

profile.jsx

_18
import useAuth from "hooks/useAuth";
_18
_18
const Profile = () => {
_18
const { user, isAuthenticated, logout } = useAuth();
_18
_18
if (isAuthenticated && user) {
_18
return (
_18
<Box>
_18
<Typography>Email : {user.email}</Typography>
_18
<Button onClick={logout}>logout</Button>
_18
</Box>
_18
);
_18
}
_18
_18
return <Redirect to="/login" />;
_18
};
_18
_18
export default Profile;

How to delete from app ?

  • Delete the firebaseContext.jsx file from src/contexts folder
  • If you use this, you should also remove the AuthContext file from the src/hooks/useAuth.js file.
  • Remove the CONFIG OPTIONS from the .env file as well.
  • Remove the dependency firebase

Reference