{"id":23174209,"url":"https://github.com/jamezmca/react-firebase-auth-db-template","last_synced_at":"2025-05-13T00:38:58.410Z","repository":{"id":217563791,"uuid":"744228811","full_name":"jamezmca/react-firebase-auth-db-template","owner":"jamezmca","description":"How to setup authentication + database setup with React.js \u0026 Firebase","archived":false,"fork":false,"pushed_at":"2024-01-17T02:21:56.000Z","size":62,"stargazers_count":10,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-01T05:11:20.531Z","etag":null,"topics":["authentication","backend","database","development","firebase","frontend","full-stack","reactjs","setup","software-development","website"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jamezmca.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-16T21:47:12.000Z","updated_at":"2025-02-23T12:00:48.000Z","dependencies_parsed_at":null,"dependency_job_id":"d9d53004-5a4b-4715-8b20-88ed27cb782c","html_url":"https://github.com/jamezmca/react-firebase-auth-db-template","commit_stats":null,"previous_names":["jamezmca/react-firebase-auth-db-template"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamezmca%2Freact-firebase-auth-db-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamezmca%2Freact-firebase-auth-db-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamezmca%2Freact-firebase-auth-db-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamezmca%2Freact-firebase-auth-db-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jamezmca","download_url":"https://codeload.github.com/jamezmca/react-firebase-auth-db-template/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253850767,"owners_count":21973666,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","backend","database","development","firebase","frontend","full-stack","reactjs","setup","software-development","website"],"created_at":"2024-12-18T05:19:36.592Z","updated_at":"2025-05-13T00:38:58.382Z","avatar_url":"https://github.com/jamezmca.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Authentication + Database Speed Run [React.js \u0026 Firebase]\n\nLet this guide be the auth + database speed run from the heavens to get your ideas underway ASAP, today. We’ll be developing this full stack system with React.js on the frontend, although the process is analogous for Next.js apps too, and Firebase on the backend because they handle all the heavy logic lifting and they have a phenomenal free tier for both authentication and with the Firestore NoSQL database. You can deploy your projects live today, for free, and you won’t incur any costs until you’re already making absolute bank!\n\n## Chapter 1 — Project Initialization\n\nSquare one, al principio, we begin by creating a React.js project with [Vite](https://vitejs.dev/guide/). It’s a rudimentary process; you simply run this command in your terminal!\n\n`npm create vite@latest my-fullstack-react-app -- --template react`\n\nPhew, that was easy. Now we can go ahead and open our project inside of your code editor!\n\nThen we'll quickly need to install firebase as an NPM dependancy for our project by running the following command in our terminal:\n\n`npm i firebase`\n\nThe next task on our list is to create the following files:\n\n1. `/firebase.js`\n2. `/src/context/AuthContext.jsx`\n3. `/.env`\n4. `/src/components/Login.jsx`\n5. `/src/components/Dashboard.jsx`\n\n### 1.0 Firebase.js\n\nThe `firebase.js` file can contain the following code:\n\n```\nimport {initializeApp} from 'firebase/app'\nimport {getAuth} from 'firebase/auth'\nimport {getFirestore} from 'firebase/firestore'\n\n// Your web app's Firebase configuration\nconst firebaseConfig = {\n  apiKey: import.meta.env.VITE_APIKEY,\n  authDomain: import.meta.env.VITE_AUTHDOMAIN,\n  projectId: import.meta.env.VITE_PROJECTID,\n  storageBucket: import.meta.env.VITE_STORAGEBUCKET,\n  messagingSenderId: import.meta.env.VITE_MESSAGINGSENDERID,\n  appId: import.meta.env.VITE_APPID\n};\n\n// Initialize Firebase\nconst app = initializeApp(firebaseConfig);\n\nexport const auth = getAuth(app)\nexport const db = getFirestore(app)\n```\n\nThis code initializes Firebase in our React.js codebase in addition to also initializing and then exporting our Firebase authentication \u0026 database so that they may be accessed elsewhere within our projects.\n\n### 2.0 AuthContext.jsx\n\nThe `AuthContext.jsx` component is ever so slightly more complex:\n\n```\nimport React, { useContext, useState, useEffect } from 'react'\nimport { auth, db } from '../../firebase'\nimport { signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, onAuthStateChanged } from 'firebase/auth'\n\nconst AuthContext = React.createContext()\n\nexport function useAuth() {\n    // create a useAuth hook to access the context throughout our app\n    return useContext(AuthContext)\n}\n\nexport function AuthProvider({ children }) {\n    // create the auth wrapper component for our application\n    // could optionally define a userData state and add to context\n    const [currentUser, setCurrentUser] = useState(null)\n    \n\n    function signup(email, password) {\n        return createUserWithEmailAndPassword(auth, email, password)\n    }\n\n    function login(email, password) {\n        return signInWithEmailAndPassword(auth, email, password)\n    }\n\n    function logout() {\n        return signOut(auth)\n    }\n\n    useEffect(() =\u003e {\n        const unsubscribe = onAuthStateChanged(auth, user =\u003e {\n            // This is where you could fetch generic user data from firebase\n            setCurrentUser(user)\n        })\n        return unsubscribe\n    }, [])\n\n    const value = {\n        currentUser,\n        signup,\n        logout,\n        login\n    }\n\n    return (\n        \u003cAuthContext.Provider value={value}\u003e\n            {children}\n        \u003c/AuthContext.Provider\u003e\n    )\n}\n```\n\nThis component has two functions, one that creates an auth hook that we can use to access the auth state throughout our application, and the second is an auth wrapper component with which we will encapsulate our entire application.\n\nWe also define some logic that monitors the auth state, so that our application is responsive to the users different authentication states. Three functions are defined to demonstrate the primary authentication methods, however more can be created in the same vein. Finally, we pass both the auth status and methods down as a context to our entire app, allowing them to be accessed from within any component.\n\n\u003e The users login state is cleverly stored in cookies so even if the page is refreshed, the authentication state can be maintained for a period of time without the user having to sign in again!\n\n### 3.0 Environment Variables\n\nTo keep our application secure, we save our keys within a `.env` file. The file can be initialized as follows:\n\n```\nVITE_APIKEY=\nVITE_AUTHDOMAIN=\nVITE_PROJECTID=\nVITE_STORAGEBUCKET=\nVITE_MESSAGINGSENDERID=\nVITE_APPID=\n```\n\nWe will soon fill out the actual key values in here to then be accessed within the `firebase.js` file.\n\n### 4.0 Login.jsx\n\nNow we need to initialize a Login component to handle the users sign-in and sign-up functionalities:\n\n```\nimport React, { useState } from 'react'\nimport { useAuth } from '../context/AuthContext'\n\nexport default function Login() {\n    const [createAccount, setCreateAccount] = useState(false)\n    const [userCreds, setUserCreds] = useState({ email: '', password: '' })\n\n    const { signup, login } = useAuth()\n\n    function updateEmail(e) {\n        setUserCreds({ ...userCreds, email: e.target.value })\n    }\n\n    function updatePassword(e) {\n        setUserCreds({ ...userCreds, password: e.target.value })\n    }\n\n    function handleSubmit(e) {\n        e.preventDefault()\n        // prevents signup if form not completed\n        if (!userCreds.email || !userCreds.password) { return }\n\n        if (createAccount) {\n            // recommended to add password regex check in here\n            console.log('Registering')\n            signup(userCreds.email, userCreds.password)\n        } else {\n            console.log('Logging in')\n            login(userCreds.email, userCreds.password)\n        }\n    }\n\n    return (\n        \u003cdiv\u003e\n            \u003cinput placeholder='Email' value={userCreds.email} onChange={(e) =\u003e {\n                updateEmail(e)\n            }}\u003e\u003c/input\u003e\n            \u003cinput placeholder='Password' type='password' value={userCreds.password} onChange={(e) =\u003e {\n                updatePassword(e)\n            }}\u003e\u003c/input\u003e\n            \u003cbutton onClick={handleSubmit}\u003e\n                \u003cp\u003eSubmit\u003c/p\u003e\n            \u003c/button\u003e\n            \u003cbutton onClick={() =\u003e setCreateAccount(!createAccount)}\u003e\n                \u003cp\u003e{createAccount ? 'Sign In' : 'Sign Up'}\u003c/p\u003e\n            \u003c/button\u003e\n        \u003c/div\u003e\n    )\n}\n```\n\nAnd we cleverly access both methods by calling the `useContext()` hook and destructuring the methods from within! In the component JSX we create two input fields for the email and password respectively, a button to submit the form, and a button to swap between the registration and login states.\n\n### 5.0 Dashboard.jsx\n\nAnd finally, we can display a dashboard component for anyone who is logged in :P\n\n```\nimport React from 'react'\nimport { doc, increment, serverTimestamp, setDoc } from \"firebase/firestore\";\nimport { useAuth } from '../context/AuthContext'\nimport { db } from '../../firebase';\n\nexport default function Dashboard() {\n    const { logout, currentUser } = useAuth()\n\n    async function handleIncrement() {\n        const userRef = doc(db, 'users', currentUser.uid);\n        await setDoc(userRef, { counter: increment(1), timestamp: serverTimestamp() }, { merge: true });\n    }\n\n    return (\n        \u003cdiv\u003e\n            \u003cp\u003e hello world \u0026 welcome to the dashboard\u003c/p\u003e\n            \u003cbutton onClick={handleIncrement}\u003eIncrement database\u003c/button\u003e\n            \u003cbutton onClick={logout}\u003eLogout\u003c/button\u003e\n        \u003c/div\u003e\n    )\n}\n```\n\nThe dashboard also has an increment counter to demonstrate how we can modify information in the database specific to the user by connecting the two via the users ID. Additionally, it contains a logout function for when the user wishes to logout from their account.\n\nYou can read more about CRUD operations with Firebase/Firestore here:\n\n* https://firebase.google.com/docs/firestore/manage-data/add-data\n\n\n### Chapter 2 — Modifying App.jsx \u0026 Main.jsx\n\nWith all our components and files created, we can quickly make a modification to our `app.jsx` component so that it renders the login component for unauthenticated users, and the dashboard for those logged in already.\n\n```\nimport { useAuth } from './context/AuthContext'\nimport Login from './components/Login'\nimport Dashboard from './components/Dashboard'\n\nfunction App() {\n  const { currentUser } = useAuth()\n  return (\n    \u003cdiv\u003e\n      {currentUser ? (\n        \u003cDashboard /\u003e\n      ) : (\n        \u003cLogin /\u003e\n      )}\n    \u003c/div\u003e\n  )\n}\n\nexport default App\n```\n\nThis very simple app component accesses the currentUser state using the auth context and conditionally renders either our dashboard or login component depending on whether or not a user is found!\n\nOur `main.jsx` receives a very simple update, simply wrapping the app in the new context:\n\n```\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App.jsx'\nimport { AuthProvider } from './context/AuthContext.jsx'\n\nReactDOM.createRoot(document.getElementById('root')).render(\n  \u003cReact.StrictMode\u003e\n    \u003cAuthProvider\u003e\n      \u003cApp /\u003e\n    \u003c/AuthProvider\u003e\n  \u003c/React.StrictMode\u003e,\n)\n\n```\n\n## Chapter 3 — Initializing Firebase\n\nFinally, we can provision some firebase resources to manage our authentication and database utilities within the cloud (not to mention it’s free for a solid amount of usage)!\n\nIf we visit the following page and click \u003ckbd\u003e**Get Started**\u003c/kbd\u003e, we’ll be taken to our developer console:\n\n* https://firebase.google.com/\n\nFrom here, we’ll hit \u003ckbd\u003e**Add Project**\u003c/kbd\u003e, give our project a name, optionally opt for googles analytics, and finally be taken through to the dashboard for our new project. It should look a bit as follows!\n\n\n![Firebase Project Dashboard](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*JWhmL6jR5iHTgaQDgLgMjA.png)\n\nNow we can finish the setup by following these steps:\n\n1. From here, we’ll first select Authentication.\n\n![Select authentication!](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*feoEuhfGUA1JDYbXZhgibA.png)\n\n2. Hit \u003ckbd\u003e**Get Started**\u003c/kbd\u003e on the following page.\n\n3. Select Email/Password to enable authentication with email and password.\n\n![Select Email/Password](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*9a9q6tFbp-yziGBl8aqAzw.png)\n\n4. Enable Email/Password and hit save.\n\n![Enable Email/Password](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*eWgqbZWqMjQY-THOFboHuQ.png)\n\nThat should do it to configure Firebase authentication. Now we initialize the database!\n\n5. Select Cloud Firestore from the home dashboard.\n\n![Back to homepage then select Cloud Firestore](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*Z5riX6ACBqgcdQrE5MZaLw.png)\n\n6. From here we’ll create a database. The only thing you need to consider is your location database if you’re extremely concerned about latency. Then hit \u003ckbd\u003e**Next**\u003c/kbd\u003e.\n\n![Optionally update location](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*vfjlRhtRaV2op6_l8IzSMA.png)\n\n7. Now we set the database to Test Mode to ensure that the read and write options are open.\n\n![Start database in test mode](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*LPgIWtkef_BNtHYYdC8cJw.png)\n\n8. And now, back to the dashboard to configure our Firebase project for a web application. Select the web option.\n\n![Back to home page then enable firebase for web app](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*EMUWOmXql_VQaXlpuXfGag.png)\n\n9. From here, create an app name and hit \u003ckbd\u003e**Register app**\u003c/kbd\u003e.\n\n![Name your web app](https://miro.medium.com/v2/resize:fit:2000/format:webp/1*Os94H4ju0yx0kbsWrQU8Bg.png)\n\n10. And finally, you’ll be directed to the config screen that will present you with all your valuable keys to be inserted into your `.env` file in the React codebase.\n\n![Enter your keys into the .env file](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*LCJKqy_wA7pf0jxjRNi2vA.png)\n\n## Chapter 4 — Update Your `.ENV` File\n\nNow that we have access to the keys required for our project, we can enter them into our `.env` file so that it looks as follows:\n\n```\nVITE_APIKEY=AIzaSyA3uUJXfR1241241KvUZWi3QnuUel3Y_euSnyg\nVITE_AUTHDOMAIN=test123–22ba3.firebaseapp.com\nVITE_PROJECTID=test123–22ba3\nVITE_STORAGEBUCKET=test123–22ba3.appspot.com\nVITE_MESSAGINGSENDERID=176123123817312\nVITE_APPID=1:176123123817312:web:89asdklj8123klj8asdf6623c4ffc5\n```\n\n\u003e For any opportunist out there, I’m afraid the project has been deleted which will invalidate these keys :P\n\n## Chapter 5 — Run Your App\n\nAnd finally, our project is ready for action. We can run our app using the following terminal command:\n\n`npm run dev`\n\nAnd boot it up on http://localhost:5173 !\n\nFrom there you should be able to register an account, and once logged in, hit the increment button. To confirm your application is working, inspect the Firestore console from the Firebase home page and you should see your user data incremented along with a timestamp.\n\nAnd that’s it! Congratulations on completed the React.js + Firebase Authentication \u0026 Database speed run. May your full stack projects be secure and manage loads of user data :P","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamezmca%2Freact-firebase-auth-db-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjamezmca%2Freact-firebase-auth-db-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamezmca%2Freact-firebase-auth-db-template/lists"}