If you have to choose Nextjs for server rendering a page with the data in firebase/firestore, we need a firebase initialisation script for that. So we will now see how to do this.
Install firebase
Choose your preferred package manager yarn or npm and install the firebase package to the project.
$ yarn add firebase
or
$ npm i firebase
Get the configuration from the firebase project
Since we are creating a web based project, the configuration is a json object with the keys. You can find it here. https://firebase.google.com/docs/web/setup#config-object
Firebase initialization in the project
Create directory /db
and add a new file firestore.init.js
.
import firebase from "firebase/app";
import "firebase/firestore";
export function firebaseInit() {
try {
var config = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appId: "app-id",
measurementId: "G-measurement-id"
};
firebase.initializeApp(config);
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error("Firebase initialization error", err.stack);
}
}
return firebase;
}```
Accessing data in the page
We have an awesome and easy way for creating dynamic pages in Nextjs. We will make a page for displaying user details for routes in the format /user/:name
So add a new file in the pages folder.
# We will create a new file in pages directory.
$ touch [name].js
We do this because every route like /user/Jane
, /user/Joe
will redirect here.
So to get data from api in Next.js use the getInitialprops.
import { firebaseInit } from "../db/firestore.init";
...
//end of Home component
// adding getInitalprops to functional Home component
Home.getInitialProps = async function(router) {
console.log(router.query.name);
const queryText = router.query.name;
const db = await firebaseInit();
let data = [];
const querySnapshot = await db
.firestore()
.collection("user")
.where("name", "==", queryText)
.get();
querySnapshot.forEach(doc => {
data.push(doc.data());
});
return { user: data.length ? data[0] : {} };
};
Here the firebaseInit()
function is initialised in the getInitialProps
. We then queried the firestore database and that data is returned from getInitialProps
. Then this data is available as user
in our Home component props.
const {user} = props;
return <div className="username"> {user.name}</div>
That's it folks. Hurray!
We are ready to deploy.