Sample Firebase Cloud Functions (Node.js)

Apr 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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.