
Next.js is a popular React framework for building server-rendered and statically generated web applications. It's a perfect match for Firebase, a powerful backend-as-a-service (BaaS) platform.
With Next.js, you can create a robust and scalable application that integrates seamlessly with Firebase. By combining these two technologies, you can build a full-stack application that's both fast and efficient.
Firebase provides a suite of services, including authentication, real-time database, and cloud functions, which can be easily integrated into a Next.js application. This integration enables you to build a feature-rich application with minimal backend code.
A unique perspective: Next Js Build
Setting Up
To set up your Next.js app with Firebase, start by setting up your development environment and creating a GitHub repository. You can find the codelab source at https://github.com/firebase/friendlyeats-web, which contains sample projects for multiple platforms. The repository you'll need is the nextjs-start directory.
First, create a new directory in your repository and copy the nextjs-start folder into it. You can then set up authentication by navigating to the Firebase console, clicking Get started, and enabling Google as an authentication provider. You'll also need to enter a memorable name for your project and select your email address as the support email.
To get started with authentication, you'll need to create a new directory called auth in your src > firebase directory. This is where you'll add all your Firebase authentication-related code.
Worth a look: Host Next Js on Firebase
Set Up

To set up your development environment, start by copying the nextjs-start folder into your own repository from the Firebase CLI. This will give you the app's starter codebase.
You'll find the repository at https://github.com/firebase/friendlyeats-web. Take note of the directories, as you'll need them later.
Next, create a new file called firebase.js in your app's src directory. Paste in your config code to get started.
To set up authentication, create a new directory called auth in your src > firebase directory. Then, create a signup.js file with the following code, which uses the Firebase createUserWithEmailAndPassword() method to sign up new users.
Here's a step-by-step guide to setting up authentication in Firebase:
- In the Firebase console, navigate to Authentication.
- Click Get started.
- In the Additional providers column, click Google > Enable.
- In the Public-facing name for project text box, enter a memorable name, such as My Next.js app.
- From the Support email for project drop-down, select your email address.
- Click Save.
Before you start implementing Firebase services, make sure to give your project a name in the Firebase console. This will help you identify your project later on.
To use Firebase services like Authentication, Firestore, or Firebase Storage, you'll need to install the necessary packages. For instance, to use Firestore, install the @firebase/firestore package using npm install. Then, create a firestore.js file in your utils directory and export the Firestore instance.
You might like: Nextjs Useeffect
Run Our Local

To run our local app, navigate to http://localhost:3000 and you should see the form. Any data input and submitted via the form will be added to the "items" collection in Firestore.
Next, we need to set up a few more features, so let's start by creating the ListItems component.
To do this, we'll make some code changes to our project.
Additional reading: Form Submit Nextjs
Firebase Services
To implement Firebase services in your Next.js app, you can use various services like Authentication, Firestore, or Firebase Storage.
First, you need to include the Firestore SDK in your project by running npm install @firebase/firestore.
Next, create a firebase.js file in your app and paste in your config code. You can then create and export a Firestore instance by importing the getFirestore function from the @firebase/firestore package and your firebase app.
Here's a step-by-step guide to creating a Firestore instance:
- Include the Firestore SDK: npm install @firebase/firestore
- Create and export a Firestore instance: create a firebase.js file and paste in your config code
In your firebase.js file, you'll need to import the getFirestore function and your firebase app, then create a Firestore instance by calling getFirestore with your app instance.
For example, you might have a firebase.js file that looks something like this:
```javascript
import { getFirestore } from "firebase/firestore";
import firebaseApp from './firebaseConfig';
const db = getFirestore(firebaseApp);
export default db;
```
For your interest: Firebase Auth Nextjs
Firestore Integration

Firestore Integration is a crucial part of building a Next.js application with Firebase. You can listen for real-time updates in your web app by using Cloud Firestore snapshot listeners.
To configure your client component to hydrate server-rendered markup, follow these steps: replace the getRestaurantsSnapshot() function in the src/lib/firebase/firestore.js file with the provided code. This will enable real-time updates in your web app.
Create a commit with a message like "Listen for real-time restaurant updates" and push it to your GitHub repository. After that, open the App Hosting page in the Firebase console and wait for your new rollout to complete.
You can add documents to Firestore by creating a file called addData.js inside the firestore directory and adding the provided code. This function can be used from any component to add data to your database.
To integrate Firebase into your Next.js application, create a file named firebaseConfig.js within a directory like lib/ or utils/. Insert your Firebase configuration keys into this file, using the keys from the Firebase SDK.

Here's a summary of the steps to integrate Firebase into your Next.js application:
You can also create a Next.js component to add data to Firestore by creating a simple form component that allows users to input data. Add the AddItem component to one of your pages, for example in app/page.js.
Check this out: Next Js Fetch Data save in Context and Next Route
Hosting and Deployment
With Next.js and Firebase, hosting and deployment is a breeze. You can serve static content with the standard deployment command.
To host your Next.js app on Firebase, you can use the next.config.js file to configure hosting behavior. This will allow you to customize how your app behaves when hosted on Firebase.
After initializing Firebase, you can view your deployed app on its live site, making it easy to see the fruits of your labor.
Additional reading: Next Js Deploy
Serve Static Content
Serving static content is an essential part of hosting and deployment. After initializing Firebase, you can serve static content with the standard deployment command.
You can view your deployed app on its live site. This is a great way to test and showcase your app's functionality.
To serve static content, you'll need to use the standard deployment command provided by Firebase.
Configure Hosting Behavior

To configure hosting behavior, you'll want to consider a few key things. You can start by configuring hosting behavior with next.config.js, but be aware that this will trigger the creation of a function in Cloud Functions for Firebase, even if you're not using Server-Side Rendering (SSR).
The next step is to add your Firebase configuration to your web app code. This involves navigating to your Project settings in the Firebase console and clicking "Add app" to register a new web app. You'll then need to copy the firebaseConfig variable and its properties, and fill in the environment variable values with the configuration values from the Firebase console.
You can find the correct config code in Firebase, which should look like a snippet with various properties and values. Make sure to pick a sensible location in your app for this code, such as a components folder or src folder.
Redirects, rewrites, and headers are also important to consider when configuring hosting behavior. The Firebase CLI respects these configurations in next.config.js, converting them to their equivalent Firebase Hosting configuration at deploy time. If a Next.js redirect, rewrite, or header cannot be converted, it will fall back and build a function, even if you're not using image optimization or SSR.
On a similar theme: What Is .next Folder in Next Js
Here's a quick rundown of the steps to add Firebase configuration to your web app code:
- Navigate to your Project settings in the Firebase console.
- Click "Add app" to register a new web app.
- Copy the firebaseConfig variable and its properties.
- Ffill in the environment variable values with the configuration values from the Firebase console.
- Save the file.
Next.js Configuration
To get started with Next.js and Firebase, you'll need to configure your project properly. To do this, you'll need to add your Firebase configuration to your web app code. This involves navigating to your Project settings in the Firebase console and registering a new web app.
To add your Firebase configuration, follow these steps: In the Firebase console, navigate to your Project settings.In the SDK setup and configuration pane, click "Add app" and click on the code brackets icon to register a new web app.At the end of the web app creation flow, copy the firebaseConfig variable, and copy its properties and their values.
You'll also need to configure Hosting behavior with next.config.js. Using Next.js Image Optimization is supported, but it will trigger creation of a function (in Cloud Functions for Firebase), even if you’re not using SSR.
Folder Structure
In a Next.js project, the folder structure is organized in a way that makes sense for a web app. The project has a clear separation of concerns.
The `src` folder contains the main application code, including React components for filters, headers, restaurant details, and reviews in `src/components`. Utility functions that aren't necessarily bound to React or Next.js are found in `src/lib`.
The `src/lib/firebase` folder contains Firebase-specific code and configuration. This is where you'll find all the Firebase-related code for your project.
Static assets like icons are stored in the `public` folder. This is a good place to keep any images, CSS files, or other static resources that don't need to be compiled.
The `src/app` folder is where you'll find the routing configuration for your Next.js App Router. An API route handler is located in `src/app/restaurant`.
Here's an overview of the key folders in the project:
The project also includes important configuration files like `next.config.js` and `jsconfig.json`. These files contain settings for Next.js and the JavaScript language service, respectively.
State Read on Server

In Next.js configuration, it's essential to read authentication state on the server. This allows you to mirror the client's authentication state on the server.
We'll use FirebaseServerApp to achieve this. Open src/lib/firebase/serverApp.js, and replace the getAuthenticatedAppForUser function.
Serve Fully Dynamic Content (SSR)
To serve fully dynamic content, you'll want to use Server-Side Rendering (SSR), which is supported by Next.js. This allows you to render your application on the server, rather than just on the client-side.
The Firebase CLI will detect when you're using getServerSideProps, and in such cases, it will deploy functions to Cloud Functions for Firebase to run dynamic server code. You can view information about these functions in the Firebase console.
You can verify that your server-side rendering is working correctly by disabling JavaScript in the DevTools, refreshing the page, and seeing that your content still loads. This shows that the restaurant information is being returned in the server response.
Here's a quick rundown of what to check:
Re-enabling JavaScript will allow your client-side JavaScript code to hydrate the restaurant information, but you'll still see that the content loads initially from the server response.
Config to Code
To get your Firebase configuration up and running in your Next.js app, you'll need to add it to your web app code. In the Firebase console, navigate to your Project settings, and in the SDK setup and configuration pane, click "Add app" and click on the code brackets icon to register a new web app.
To do this, you'll need to copy the firebaseConfig variable and its properties and values. Then, open the apphosting.yaml file in your code editor and fill in the environment variable values with the configuration values from the Firebase console. Replace the existing properties with those that you copied, and save the file.
You can also store your Firebase configuration in environment variables to enhance security. Modify your Firebase config to utilize process.env, and place the environment variables in your .env.local file located at the project root.
To utilize Firebase services in your Next.js app, you can implement various services like Authentication, Firestore, or Firebase Storage. For instance, to use Firestore, you'll need to include the Firestore SDK and create and export a Firestore instance.

Here's a step-by-step guide to creating a Firestore instance:
- Include the Firestore SDK by running `npminstall @firebase/firestore` in your terminal.
- Create a new file called `firestore.js` in the `utils` folder and export a Firestore instance using the `getFirestore` function from the `@firebase/firestore` package.
When working with Firebase configurations, it's essential to get the correct config code from Firebase. You can find this config snippet in the Firebase console, and it should look like a JavaScript object with various properties and values.
Pick a sensible location in your app to store this config code, such as a components folder or the src folder. Avoid storing it in your pages folder, as this can make it harder to manage and update your configuration.
Intriguing read: Next Config Js
Firebase SDKs
Firebase SDKs can be a bit tricky to set up, but don't worry, I've got you covered. You'll need to import Firebase into your project, and that's where things can get a bit messy.
To import Firebase correctly, you'll need to add the line `firebase.initializeApp(firebaseConfig)` and also `firebase.analytics()` if you want analytics to work. However, this will break your app when building, and you'll get errors like 'window is undefined'.
You can fix this by checking if the window object is available before running the analytics code. This is a simple check that will ensure your app doesn't break when building.
Here's a table summarizing the steps to import Firebase correctly:
Optional, but a good practice is to check if a product is supported in the current environment using `isSupported()` before using it. This will prevent runtime errors and make your code more robust.
Database Communication
Database Communication is a crucial aspect of building a Next.js application with Firebase. To communicate with our database, we'll be using Firestore.
We'll create a new Firebase > Firestore directory to hold all our Firestore-related code. This will keep things tidy and organized.
To listen for restaurant updates, we can use Cloud Firestore snapshot listeners. This allows us to configure our client components to hydrate server-rendered markup.
Here are the steps to configure the src/components/RestaurantListings.jsx file to hydrate server-rendered markup:
- In the src/components/RestaurantListings.jsx file, we need to invoke the getRestaurantsSnapshot() function, which provides a callback mechanism so that the callback is invoked every time a change is made to the restaurant's collection.
- We replace the getRestaurantsSnapshot() function with the following code in the src/lib/firebase/firestore.js file:
- Create a commit with commit message "Listen for realtime restaurant updates" and push it to your GitHub repository.
- Open the App Hosting page in the Firebase console and wait for your new rollout to complete.
- In the web app, select > Add sample restaurants. If your snapshot function is implemented correctly, the restaurants appear in real-time without a page refresh.
To add data to Firestore, we can create a file called addData.js inside the firestore directory and add the following code:

This function can be used from any component to add data to our database.
We can also get a document from our Firestore database by creating a getData.js file in the Firestore directory and adding the following code:
This function can be used in any component to retrieve data from our database.
In a Next.js application, we can interact with Firestore within a component. To demonstrate this, we'll create a simple form component that lets users input data, which will then be saved to Firestore.
Testing and Setup
To set up Firebase in your Next.js project, you'll need to create a Firebase account and enable the necessary features. You can do this by going to the Firebase console and following the steps outlined in the article.
The first step is to create a Firebase app. This involves adding a project, giving it a name, and enabling analytics. You'll also need to create a web app and copy the configuration file, which you'll use later in the process. To add authentication and Cloud Firestore to your app, simply choose the products you need and follow the prompts.
To use Firebase with Next.js, you'll need to install the Firebase SDK and create a .env file in your project's root directory. This file should contain your Firebase configuration files, which you can copy from the Firebase console. You can see an example of what this file should look like in the article.
Verify Changes
Verify changes by creating a commit with a commit message "Show signin state" and pushing it to your GitHub repository. This is the first step in the verification process.
To verify the new authentication behavior, open the App Hosting page in the Firebase console and wait for your new rollout to complete. This ensures that your changes are live and ready for testing.
Once your rollout is complete, you can verify the changes by checking the authentication behavior on your application. This is a crucial step in ensuring that your changes are working as expected.
Here are the steps to verify changes:
- Create a commit with a commit message "Show signin state" and push it to your GitHub repository.
- Open the App Hosting page in the Firebase console and wait for your new rollout to complete.
- Verify the new authentication behavior.
Verify Image Upload Functionality
To verify the image-upload functionality, you'll want to follow these steps. Create a commit with a commit message "Allow users to change each restaurant's photo" and push it to your GitHub repository.
First, open the App Hosting page in the Firebase console and wait for your new rollout to complete. This step is crucial to ensure that the changes you've made are live and accessible.
Once your rollout is complete, log in to the web app and select a restaurant. You should see the option to upload an image from your filesystem.
Click on the image upload option, and your image will be uploaded to Cloud Storage. The image will appear immediately after you upload it.
To confirm that the image was uploaded correctly, navigate to Cloud Storage for Firebase. From there, navigate to the folder that represents the restaurant, and you should see the image you uploaded.
Here's a summary of the steps to verify image upload functionality:
- Create a commit with a commit message "Allow users to change each restaurant's photo" and push it to your GitHub repository.
- Wait for your new rollout to complete on the App Hosting page in the Firebase console.
- Log in to the web app, select a restaurant, and upload an image from your filesystem.
- Navigate to Cloud Storage for Firebase and the folder that represents the restaurant to confirm the image upload.
Check Its Working

Verify changes to ensure your Next.js app is working as expected. Create a commit with a meaningful message and push it to your GitHub repository. Open the App Hosting page in the Firebase console and wait for your new rollout to complete.
To verify authentication behavior, open the web app and refresh the page. If authentication updates occur during the page lifecycle, the onAuthStateChanged handler should handle them.
Verify that restaurant listings load at server run time by disabling JavaScript in DevTools and refreshing the web app. The restaurant listings should still load, and the information should be returned in the server response.
Verify the image-upload functionality by creating a commit, pushing it to your GitHub repository, and waiting for the rollout to complete. Log in to the web app, select a restaurant, click to upload an image, and verify that it appears immediately after upload.
Security and Authentication
To enhance security, store your Firebase configuration in environment variables. This is done by modifying your Firebase config to utilize process.env and placing the relevant information in your .env.local file located at the project root.
To implement secure authentication, use the GoogleAuthProvider and signInWithPopup functions from the Firebase API. These functions create a Google authentication provider instance and start a dialog-based authentication flow.
The Firebase API provides several functions for authentication, including auth.signOut, which signs out the user. This function is already invoked in the src/components/Header.jsx file, which also calls the signInWithGoogle and signOut functions.
Implement Sign-In and Sign-Out
Implementing sign-in and sign-out functions is crucial for any application that requires user authentication. This involves creating a secure way for users to log in and out of the system.
To start, you'll need to replace the existing onAuthStateChanged, signInWithGoogle, and signOut functions in the src/lib/firebase/auth.js file with the following code. This code uses the Firebase API to create a Google authentication provider instance and starts a dialog-based authentication flow.
The Firebase API used in this code includes:
The signInWithGoogle function is already invoked in the src/components/Header.jsx file, along with the signOut function. This indicates that the code is set up to handle user authentication and sign-out functionality.
Save User-Submitted Reviews

To save user-submitted reviews, you can use Firestore, a NoSQL document database provided by Google Cloud. This allows you to store and manage data in real-time.
The process involves inserting a new Firestore document representing the new review and updating the existing Firestore document that represents the restaurant with updated figures for the number of ratings and the average calculated rating.
To do this, you'll need to replace the addReviewToRestaurant() function with the following code:
- Insert a new Firestore document representing the new review.
- Update the existing Firestore document that represents the restaurant with updated figures for the number of ratings and the average calculated rating.
This ensures that user-submitted reviews are properly stored and updated in the database, allowing for accurate calculations and analysis.
Secure Config with Env Variables
Secure Config with Env Variables is a crucial step in enhancing security for your Firebase project. Store your Firebase configuration in environment variables to keep it secure.
You can modify your Firebase config to utilize process.env to achieve this. Place these in your .env.local file located at the project root.
To do this, you'll need to add your Firebase configuration to your web app code. This involves copying the firebaseConfig variable from the Firebase console and filling in the environment variable values with the configuration values.
Here's a step-by-step guide to help you through the process:
- In the Firebase console, navigate to your Project settings.
- In the SDK setup and configuration pane, click "Add app" and click on the code brackets icon to register a new web app.
- At the end of the web app creation flow, copy the firebaseConfig variable, and copy its properties and their values.
- Open the apphosting.yaml file in your code editor, and fill in the environment variable values with the configuration values from the Firebase console.
- In the file, replace the existing properties with those that you copied.
- Save the file.
By following these steps, you'll be able to securely store your Firebase configuration in environment variables.
Optional Features
Integrating with the Firebase JS SDK is an optional feature for Next.js Firebase developers.
Not all products are supported in all environments, so it's essential to check if a product is supported before using it.
You can use the isSupported() method to guard against runtime errors and ensure a smooth development experience.
Featured Images: pexels.com


