Firebase

Read data from Realtime Database.

F
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()
    });
  });
};
import db from '../../lib/db-admin';

exports.handler = async (event, context, callback) => {
  const { id } = event.queryStringParameters;
  if (!id) {
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: 'Missing "id" query parameter'
      })
    };
  }

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

  return ref.once('value', (snapshot) => ({
    statusCode: 200,
    body: JSON.stringify({
      total: snapshot.val()
    })
  }));
};

Library#

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#

1

Create Firebase Account

First, create a Firebase account.

2

Retrieve Service Account

  1. Create a new project.
  2. Navigate to "Database" and click "Create Database". Create Firebase Database
  3. Start in test mode and click next. Create Firebase Database
  4. Choose your database location and click done. Create Firebase Database
  5. In the top left, click on "Project Settings". Create Firebase Database
  6. Navigate to "Service Accounts" tab and click "Generate new private key". Save the .json file. You will need the client_email and private_key from the file. Create Firebase Database

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

3

Add Environment Variables

To securely access the API, we need to include the secrets with each request. We also do not want to commit secrets to git. Thus, we should use environment variables.

  • Netlify: Settings -> Build & deploy -> Environment -> Environment variables.
  • Vercel: Settings -> General -> Environment Variables.

Alternatively, you can add the enviornment variables to your vercel.json or netlify.toml file.

New functions in your inbox

Get access to functions when they're added.