Setup Firebase in Next.js Project

In this tutorial, I will show you how to set up Firebase in a Next.js project. It’s actually pretty simple.

Setup Next.js Project

First, create a new Next.js project:

npx create-next-app myproject

You can verify that everything is working okay by quickly running npm run dev.

Then, install the Firebase package into your new project:

npm install firebase

Setup Firebase Project

Now, head over to the Firebase website to set up a new Firebase project:

Then, select the option to add Firebase to your web app:

Next, register your app with a name and copy the code that is created for you. This code will initialize Firebase in your project.

Add Firebase config to Next.js Project

In your project, create a new file to hold the Firebase configuration code:

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "..."
};

export const firebaseApp = initializeApp(firebaseConfig);

Now, you can import the Firebase app into other files within your project and thus access Firebase in your project.

Import the app const from the Firebase config file you just created:

import firebaseApp from '../firebase_config';

Working with Firestore

Firestore is a powerful Cloud, NoSQL database within Firebase. There is a good chance you will use it in your web application.

To setup Firestore within your project, add the following code to your Firebase config file:

First, import the getFirestore function at the top:

import { getFirestore } from "firebase/firestore";

Then, create a database using the function, passing in your firebaseApp from before:

const db = getFirestore(firebaseApp);

Lastly, export the database along with your firebase app:

export { firebaseApp, db }

Now, you can work with Firestore in your project. Here’s an example:

import { firestore } from '../firebase_config';
import { useState } from 'react';

import { collection, QueryDocumentSnapshot, DocumentData } from "@firebase/firestore";

const todosCollection = collection(firestore,'todos');

const [todos,setTodos] = useState<QueryDocumentSnapshot<DocumentData>[]>([]);

This was just a very simple, bare-bones introduction to using Firebase in Next.js. Hope it helped.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s