Read data from Firebase database as an admin

Let's assume that you want:

  1. Only the admin to read from the database in Firebase.
  2. Prevent the users to delete data as well.

You'll need to write the following rules in Firebase:

    "rules": {
        ".read":  false,
        ".write": "!data.exists()"

Even if ".read": false, the admin has always access to read from the database.

Trigger a function after data creation

If you want to trigger a function after a user creates new data, you can use the onCreate() function. If you combine this function with the admin SDK, you'll be able to read from the database:

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

// Initialize as admin

// We read the data from /orders/{orderId} as admins
exports.newDataCreation = functions.database.ref('/orders/{orderId}').onCreate(async (snapshot, context) => {       
    // If you try to read data such as
    // const { tee, mode, size } = snapshot.val();
    // You'll get permission denied error. Rules will prevent you to read data as a normal user 
    // You'll need to read data as admin
    let data = await admin.database().ref('/orders/' + context.params.orderId).once('value');
    const { tee, model, size } = await data.val();

Note: to get the full path of the new data, you can use the context.params object.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.