This project serves as a guide to get started with Next.js and Firebase, demonstrating how to set up authentication with email/password and error handling with React Hot Toast.
Ensure you have Node.js installed on your local machine. If not, download it from Node.js official website.
- Install
Next.jsand create a new app inside current folder with out giving a project name:
-
`npx create-next-app@latest .`will create a Next.js app and will require project name:
-
`npx create-next-app@latest`will create a new Next.js app inside a folder named
my-app. It will prompt you to enter the name of the project, this can be anything you want.
-
Install
Tailwind CSSwhen prompted in the CLI -
Install
ESLint -
Choose
Apprecommend option, notsrcfolder option -
After installation is complete, run
npm update -
Run
npm run devto start the development server. Make sure you usenvm use v18to use the correct node version.
IMPORTANT NOTE
When installing packages, make sure to shut down the server and restart it again. This will ensure that the packages are installed correctly and you don't run into any errors.
REMOVE the following files from the project:
- Open the
appfolder, go topage.jsinside thereturnstatement, collapse themaintag element and delete all of it. Add adivand ah1, give it any title you want - Open the
publicfolder delete thenext.svg&vercel.svgimages - In the tailwind.config.js file, delete the
backgroundImageobject - In the
appfolder, delete theglobals.cssstyles but keep the 3@tailwindimports
ADD the following files to the project:
- In the
global.cssaddhtml, body, :root {height: 100%;}& ALL thebtnclasses - Open the
layout.jsfile and update the metadata with your own information. You can also import any google fonts you like. For this project I usedMontserrat
- Open your CLI and run
npm i react-hot-toastornpm install react-hot-toastoryarn add react-hot-toastto install React Hot Toast - Import the
Toastercomponent fromreact-hot-toast, within theappfolder, open thelayout.jsfile, at the top of the fileimport { Toaster } from 'react-hot-toast'
When you are using Link in Next.js 13 you need to import it from next/link, be sure to NOT include in a tag just pass the href prop to the Link component.
This is a custom component that will be used for the sign up and sign in pages. It will be located in the components folder. Add this component to your files to handle the form layout.
Click to expand
Firebase is a BaaS - Backend-as-a-Service. It provides a lot of services like authentication, database, storage, hosting, etc. We will be using Firebase for authentication and database.
- Go to Firebase Console and click on ADD PROJECT to create a new project. You can name it anything you want.
- Enable analytics if you want to track your app usage (optional)
- Click on Continue
- On the homepage click on the Web Icon to create a new web app
- Give it a name and click on Register app
- Click on Box for Firebase Hosting and click on Next
- In your CLI run
npm i firebaseornpm install firebaseoryarn add firebaseto install Firebase SDK -
Copy the firebaseConfig objectand paste it in a safe place, You will NEED this later! - Install the
Firebase CLIrun the command in CLInpm install -g firebase-tools - Deploy your app to Firebase Hosting, run the command in CLI
firebase loginand login to your account - Run
firebase experiments:enable webframeworksto enable the Next.js support - Run the command in CLI
firebase initand select the following options:
Hosting: Configure and deploy Firebase Hosting sites
Use an existing project
Select the project you created
Answer Following Questions in CLI
- On the Project Overview page, You will use
Authenticationservices, so click on Build then Authentication finally Get Started. This is where the users that sign up for our app will be stored - In the Authentication settings,
Choose Sign-in-method - add Email/Password
Remeber the firebaseConfig object you copied earlier? We will be using it now to set up Firebase in our Next.js app.
- Create a
.envfile at the root of the project and add the following environment variables:
NEXT_PUBLIC_FIREBASE_API_KEY="api-key"
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN="auth-domain"
NEXT_PUBLIC_FIREBASE_PROJECT_ID="project-id"
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET="storage-bucket"
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID="sender-id"
NEXT_PUBLIC_FIREBASE_APP_ID="app-id"
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID="analytic-id"
- Add the
.envto.gitignore, if you pushed up your code to GitHub, you don't want to expose yourAPI keys. If you did run the commandgit rm -r --cached .envto remove all the .env files from cache - Close down server and run
npm run devagain to restart the server - Create a folder at the root level, name it
firebaseand create aconfig.jsfile inside it
CONGRATS You have successfully set up Firebase in your Next.js app!
- Create a
authfolder inside thefirebasefolder, then create asignup.jsxandsignin.jsxfile
We want to know when users are logged in or logged out. We can create protected pages and only display certain contents to the logged in user. Firebase provides a method to listen for auth state changes onAuthStateChanged(). Making the user data available globally is a good idea, we can do this utilizing the React Context API allowing us to share state with other components.
- In the
rootdirectory, create a foldercontext, then create aAuthContext.jsxfile inside it
To access the values passed to the AuthContext.Provider, we are exporting useAuthContext, now we can use the user value.
In order to use the useAuthContext hook, we need to wrap the AuthContext.Provider around all the components in the layout.js file located in the app directory, Wrap the { children } prop with AuthContext.Provider
Now we can create protected routes and only display certain contents to the logged in user!
- Open the
appfolder and create a new folderadminand add apage.jsxfile inside it. This will be a protected page that only logged in users can access
In Next.js 13, you create pages within the app directory. Each page has it's own folder with a page.js or page.jsx file.
For Route Groups and Private Folders you can create a folder with ( ) and add a page.js or page.jsx file inside of it. This will allow for Group routes without affecting routing.
For this project I created a (site) folder with a page.jsx to show the Sign Up page first.
- Delete the current
page.jsfile that is in theappdirectory - Inside the
appdirectory, create a(site)folder with apage.jsxfile inside it - Next, create a
signinfolder inside the(site)folder and add apage.jsxfile. - Create a
componentsfolder in the root directory and add aFormControls.jsxfile inside it. This way we can reuse the form controls for both the sign up and sign in pages - Import the
FormControlscomponent into the Sign-Up page located in the(site)folderpage.jsxfile & the Sign-In page located in the(site)/signinfolder within thepage.jsxfile
Congrats! You have successfully created a protected page & setup Firebase Authentication in your Next.js app! This is completing the basics of creating a simple login with just a email and password
Click to expand
Add seamless notifications to your React app with ease.
- Run one of these commands in your CLI
npm i react-hot-toastornpm install react-hot-toastoryarn add react-hot-toast - Import
Toasterfromreact-hot-toastin theappfolder,layout.jsfile, your import should look like thisimport { Toaster } from 'react-hot-toast' - Add the
Toastercomponent below theAuthContext.Providercomponent in thelayout.jsfile - In the
(site)folderpage.jsxfile,import { toast } from 'react-hot-toast' - Add the following code to the error and success handlers:
toast.error("Sign up failed!")&toast.success("Sign up successful!") - Next, add them to
signinfolder,page.jsxfile
If you see the messages appear in the browser, you have successfully set up React Hot Toast!
The project was inspired by the article on setting up Next.js & Firebase. Although several modifications have been made, it's important to give due credit.