Firebase

Read data from Realtime Database.

Firebase
import db from '../../lib/db-admin';

export default (req, res) => {
  if (!req.query.id) {
    return res.status(400).json({
      error: 'Missing "id" query parameter'
    });
  }

  const ref = db.ref('table').child(req.query.id);

  return ref.once('value', (snapshot) => {
    res.status(200).json({
      total: snapshot.val()
    });
  });
};
// lib/db-admin.js

const admin = require('firebase-admin');

try {
  admin.initializeApp({
    credential: admin.credential.cert({
      client_email: process.env.FIREBASE_CLIENT_EMAIL,
      private_key: process.env.FIREBASE_PRIVATE_KEY,
      project_id: 'your-project-id'
    }),
    databaseURL: 'https://your-project-id.firebaseio.com'
  });
} catch (error) {
  /*
   * We skip the "already exists" message which is
   * not an actual error when we're hot-reloading.
   */
  if (!/already exists/u.test(error.message)) {
    console.error('Firebase admin initialization error', error.stack);
  }
}

module.exports = admin.database();

Usage

First, create a Firebase account.

  1. If you do not have a Firebase account, create one first.
  2. Create a new project.
  3. Navigate to "Database" and click "Create Database". <Image alt={Create Firebase Database} src={/static/images/real-time-post-views/firebase/step1.png} width={1000} height={534} />
  4. Start in test mode and click next. <Image alt={Create Firebase Database} src={/static/images/real-time-post-views/firebase/step2.png} width={1000} height={533} />
  5. Choose your database location and click done. <Image alt={Create Firebase Database} src={/static/images/real-time-post-views/firebase/step3.png} width={1000} height={532} />
  6. In the top left, click on "Project Settings". <Image alt={Create Firebase Database} src={/static/images/real-time-post-views/firebase/step4.png} width={979} height={386} />
  7. Navigate to "Service Accounts" tab and click "Generate new private key". Save the .json file. You will need this later. <Image alt={Create Firebase Database} src={/static/images/real-time-post-views/firebase/step5.png} width={1000} height={535} />

You have successfully set up a real-time database, as well as generated credentials for your serverless function to connect to Firebase.

To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable. Learn how to add environment variables in Vercel.