Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers.

Essentially, I aim to perform a POST action to an external server operating on an arduino whenever a new value is added to my database.

I have gone through the documentation and come across examples of cloud functions responding to an HTTP post request (HTTP cloud functions); however, I am unable to locate any instances of posting to an external server. Can this be done?

Answer №1

Important: The request package is no longer supported, as indicated on the npm page request-npm. It's recommended to explore other alternatives like axios

You can achieve this by utilizing the request module:

// Importing the module
var request = require('request');

// Making the request
request('put your external URL here', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Add your desired actions for handling the request here
    }
})

NOTE: This method will only function with premium plans. Utilizing non-Google APIs is not feasible with the free Spark plan, as detailed in the Firebase pricing guidelines:

The Spark plan permits outbound network requests solely to Google-owned services. Inbound invocation requests fall within the quota limits. On the Blaze plan, Cloud Functions offer a perpetual free tier. The initial 2,000,000 invocations, 400,000 GB-sec, 200,000 CPU-sec, and 5GB of Internet egress traffic are provided at no cost each month. Charges apply for usage exceeding this complimentary allotment. Pricing is determined by the total number of invocations and compute time. Compute time varies based on the allocated memory and CPU for a function. Usage restrictions are enforced through daily and 100s quotas. For further details, refer to Cloud Functions Pricing.

Answer №2

To get started, make sure you have the necessary package installed. Navigate to the Firebase-Functions directory in your Terminal and enter the following command:

npm install request

Alternatively, you can also use:

npm install request-promise

Feel free to test it out using this sample: https://www.npmjs.com/package/request

Answer №3

Don't forget to add the module to the functions directory!

cd functions
npm install --save request

Answer №4

If you are looking to make a post request with a JSON body, here is a helpful function that can assist you. (I wish I had known about this sooner)

export function sendPostRequestWithJsonBody(url: string, body: any): Promise<ReqResponse> {

  const request = require('request');

  const options = {
    url: url,
    json: true
  };
  return new Promise(function (resolve, reject) {
    request(options, function (error, response) {
      if (error) {
        console.log(error);
        reject({ error: error });
      }
      resolve(body);
    });
  });
}

Answer №5

axios is a fantastic library for managing network requests. Here are some of its key features:

  • Can make XMLHttpRequests from the browser
  • Allows for http requests from node.js
  • Supports the Promise API
  • Enables interception of both request and response
  • Ability to transform request and response data
  • Supports cancellation of requests
  • Automatically transforms JSON data
  • Includes client-side protection against XSRF attacks
  • 67k+ stars on github
  • Check out the github documentation for more information

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

What is the best way to convert the information from a <SelectInput /> component or similar components into another language?

Within my React admin v3 application, When retrieving data from the servers for my entity, I receive a unique identifier called a slug. This slug is a special key that needs to be translated on the client side. Here is an example of my <CallMeBackCre ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

Optimal approach for verifying the POST request payload

My RESTful API has a POST endpoint for user creation, and I am looking to implement data validation before inserting it into the database. There are two approaches I'm considering: Approach 1: Incorporating model validation in the controller and repe ...

Transforming screen recording video chunks from blob into multipart for transmission via Api as a multipart

Seeking guidance in Angular 8 - looking for advice on converting screen recorded video chunks or blogs into a multipart format to send files via API (API only accepts multipart). Thank you in advance! ...

JavaScript encoding the text

Looking for a straightforward JavaScript function to encrypt text data from a textarea using a key (the key being the user's password stored as a hashed session variable, outputted by PHP into a field). The objective is to have the content of the tex ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Generating HTML elements on the server-side vs. retrieving data as JSON and dynamically creating elements using JavaScript

Looking to implement an AJAX search feature that will retrieve and display topics from a forum, including just the topic link and subject. My question is: Which method would be more efficient and quicker? Retrieve the threads list as a JSON string, co ...

Plunker fails to run simple AngularJS demo

I'm having trouble figuring out why this basic example isn't functioning as expected on Plunker. http://plnkr.co/edit/EfNxzzQhAb8xAcFZGKm3?p=preview var app = angular.module("App",[]); var Controller = function($scope){ $scope.message ="Hel ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: The challenge I am facing involves updating the language of the chips based on the selection made in a dropdown menu. A ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Using the KnockOut js script tag does not result in proper application of data binding

Being new to knockout js, I found that the official documentation lacked a complete html file example. This led me to write my own script tags, which initially resulted in unexpected behavior of my html markups. Strangely enough, simply rearranging the pos ...

"What is the best way to use jQuery to create a toggle effect where one button controls the state

I'm looking to improve the efficiency of my code, but I'm not sure where to start in terms of making it more concise and organized. Any suggestions on how to streamline this code and keep it neat would be greatly appreciated. $(document).ready(fu ...

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

use two separate keys for grouping in JavaScript

My current approach involves using the reduce method to organize the data based on the Id of each query. var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descricao: "Creme", }, {Id: "545", valor: "2 ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

jquery: conditions fail to execute

Looking at the code snippet provided, it appears quite straightforward. The intention is to display an alert labeled "Trigger 2" if the variable "ret" returns a value of "fail". However, there seems to be a glitch with the IF statement causing it to trigge ...

Struggling with properly navigating a JSON file in my JavaScript code... specifically trying to access and retrieve the "responseObject.weather[i].weatherresponseObject.weather[i].description" data

Struggling with extracting data from a PHP file in JSON format to display on an HTML file using JavaScript. I seem to be encountering issues with accessing responseObject.weather[i].weatherresponseObject.weather[i].description, and I suspect it might be d ...