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

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

Getting Started with the Basic Example of Redux-Router

Recently, I decided to give redux-router a try and wanted to run the basic example. However, when I tried running the command: npm start I encountered an error message that said: node: bad option: -r Being new to the JavaScript modern ecosystem, I&apos ...

Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data. [ { Key: 1, exchnageArr: [ { name: ”FX” }, { name: ”MK” ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

Exploring the power of jQuery and Ajax together

Today seems to be one of those days where even the simplest tasks become a challenge. I'm sorry if this question has been asked before, but I'm struggling with a basic issue. I want to dynamically update text on a website using a text file, and w ...

What is the best way to display a popup window on top of the parent window?

How can I display a popup window on top of the parent window when a button is clicked? I have tried using the Window.Focus() method, but the popup window keeps going back behind the parent window. I would greatly appreciate any help on this. Thank you in ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to create an ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Looping through AJAX requests in JavaScript

I am attempting to make REST API requests in order to retrieve data and display it on a website. Although I have created a for loop to gather the data, I am encountering an issue where the data is not being displayed on the website. Upon checking with th ...

Attempting to remove an attribute or property in JavaScript will not yield the desired result

When I try to close the menu after opening it, the inline style won't get removed despite trying different methods. The CSS only has text properties for alignment and the class can-transform contains a media query. That's all the information I h ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Vue.js: Optimize Webpack bundle by excluding core-js

Below is the content of my vue.config.js file: module.exports = { configureWebpack: { externals: { "vue": "Vue", "core-js": "core-js", }, }, }; By using this configuration, I have successfully excluded the vue.js (Vue) library and ...

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...