Sample Firebase Cloud Functions (Node.js)

April 13, 2020
JSON, CROS, Firebase Functions Client, onRequest vs onCall, Authentication/User, Validation

Simple Function

exports.sendMessage = functions.https.onRequest((req, res) => {
  const name = req.query.name
  res.send(`Hello ${name}!`)
})

JSON Request and Respond

exports.sendMessage = functions.https.onRequest((req, res) => {
  const name = req.body.name
  res.json({
    message: `Hello ${name}!`
  })
})

CORS

const cors = require('cors')({origin: true})

exports.sendMessage = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
    const name = req.body.name
    res.json({
      message: `Hello ${name}!`
    })
  })
})

NOTE: Alternative CORS setup via Express.

Compatible with Firebase Functions

If your client is using Firebase Functions

onRequest

exports.sendMessage = functions.https.onRequest((req, res) => {
  const name = req.body.data.name
  res.json({
    data: {
      message: `Hello ${name}!`
    }
  })
})

onCall

exports.sendMessage = functions.https.onCall(async (data, context) => {
  const name = data.name
  return {
    text: `Hello ${name}!`
  }
})

Authenticated User

exports.sendMessage = functions.https.onCall(async (data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError("unauthenticated", "Request had invalid credentials.")
    // throw new functions.https.HttpsError('failed-precondition', 'Credentials are missing')
  }

  const name = data.name
  return {
    text: `Hello ${namel}!`,
    user: {
      uid: context.auth.uid,
      email: context.auth.token.email,
      name: context.auth.token.name
    }
  }
})

NOTE: Refer HttpsError and FunctionsErrorCode

Validation

exports.sendMessage = functions.https.onCall(async (data, context) => {
  const name = data.name
  if (!name) {
    throw new functions.https.HttpsError('invalid-argument', 'Name is required')
  }

  return {
    text: `Hello ${namel}!`
  }
})

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.