/firebase-tutorials

How to restrict access to logged-in users in Firebase?

Discover how to set up Firebase authentication and restrict access to logged-in users with our step-by-step guide, including examples for web apps using React.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to restrict access to logged-in users in Firebase?

 

Step 1: Set up Firebase in Your Project

 

To get started with Firebase authentication in your project, you'll first need to set up Firebase. If you haven't already done so, follow these steps:

  1. Go to the Firebase console.
  2. Click on "Add project" and follow the instructions to create a new project.
  3. Once your project is created, click on the "Web" icon to add Firebase to your web application. You'll receive a configuration object that you will need to use in your project.

 

Step 2: Install Firebase SDK

 

Add Firebase to your project by installing the Firebase SDK. If you are using npm, you can do this with the following command:

npm install firebase

 

Step 3: Initialize Firebase in Your Application

 

In your application, initialize Firebase using the configuration details provided in the Firebase console. Create a firebase.js or firebaseConfig.js file and add the following code:


import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER\_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

Remember to replace the placeholders with your actual Firebase project config values.

 

Step 4: Set Up Authentication in Firebase Console

 

Make sure to enable the authentication methods you want to use:

  1. In the Firebase console, select "Authentication" from the left navigation.
  2. Click "Get Started" and then "Sign-in Method".
  3. Enable your preferred sign-in providers (e.g., Email/Password, Google, Facebook, etc.).

 

Step 5: Implement Login/Signup Functionality

 

Create a simple authentication flow in your application using Firebase's authentication services. Here's an example using Email/Password authentication:


import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "./firebaseConfig";

// Signup function
const signupUser = async (email, password) => {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    console.log("User signed up:", userCredential.user);
  } catch (error) {
    console.error("Error signing up:", error.message);
  }
};

// Login function
const loginUser = async (email, password) => {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    console.log("User logged in:", userCredential.user);
  } catch (error) {
    console.error("Error logging in:", error.message);
  }
};

Integrate these functions into your frontend as needed.

 

Step 6: Restrict Access to Logged-in Users Only

 

Now you need to restrict access to certain parts of your application to only logged-in users. You can achieve this by checking the authentication state in your components or application.

Here's an example using React:


import React, { useEffect, useState } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./firebaseConfig";

function App() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });

    return () => {
      unsubscribe();
    };
  }, []);

  if (user) {
    return 

Welcome, {user.email}

; } else { return

Please Log In to access this page

; } } export default App;

This example listens for changes in authentication state using onAuthStateChanged and updates the UI accordingly.

 

Step 7: Test Your Implementation

 

Finally, test your application to ensure that only logged-in users can access restricted areas. Log in and log out using your implemented functions and confirm the different behaviors in your application.

By following these steps, you can effectively restrict access to logged-in users in your Firebase-enabled application.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022