Cloud Functions for Firebase: 'Error: could not handle the request'

firebase-functions deploy
firebase-functions examples
firebase cloud functions tutorial
firebase cloud functions python
firebase cloud functions http request
firebase console
firebase cloud functions write to database
firebase cloud functions pricing

I feel like pulling my hair out; this is either super simple and i'm having brain freeze or it is not that simple.

What I want

I am trying to unshorten a shortened URL using firebase, when a user goes to: myapp.firebaseappurl.com/url/SHORTENEDLINK SO wont let me add a shortened URL

I would like the output to be:

{
  "url": "https://stackoverflow.com/questions/45420989/sphinx-search-how-to-use-an-empty-before-match-and-after-match"
}
What I have tried

firebase.json file:

{
  "hosting": {
    "public": "public",
    "rewrites": [ {
    "source": "/url/:item",
      "destination": "/url/:item"
    } ]
  }
}

index.js file:

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

exports.url = functions.https.onRequest((requested, response) => {

    var uri = requested.url;
    request({
        uri: uri,
        followRedirect: true
      },
      function(err, httpResponse) {
        if (err) {
          return console.error(err);
        }
        response.send(httpResponse.headers.location || uri);
      }
    );

});
Result

When I go to myapp.firebaseappurl.com/url/SHORTENEDLINK I get the following:

Error: could not handle the request

You are seeing Error: could not handle the request since there probably was an exception and it timed out.

Check your logs using:

firebase functions:log

Refer docs for more details

Here's how I got URL unshortening to work

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

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const http = require('http');
const urlP = require('url');

const unshorten = (url, cb) => {
  const _r = http.request(
    Object.assign(
      {},
      urlP.parse(url),
      {
        method: 'HEAD',
      }
    ),
    function(response) {
      cb(null, response.headers.location || url);
    }
  );
  _r.on('error', cb);
  _r.end();
};

const resolveShortUrl = (uri, cb) => {
  unshorten(uri, (err, longUrl) => {
    if (longUrl === uri) {
      cb(null, longUrl);
    } else {
      resolveShortUrl(longUrl, cb);
    }
  });
};

exports.url = functions.https.onRequest((requested, response) => {
  var uri = requested.query.url;
  resolveShortUrl(uri, (err, url) => {
    if (err) {
      // handle err
    } else {
      response.send({ url });
    }
  });
});

You can follow the hello world example straight away and use the above code as your function.

Above code uses HEAD requests to peek into 'Location` field of the headers and decides if the url can be further unshortened.

This is lighter as HEAD requests ask for no body (thereby avoiding body parsing). Also, no third party lib required!

Also note that the url passed as a query param. So the request would be

http://<your_firebase_server>/url?url=<short_url>

Saves you the trouble of URL re-writes. Plus semantically makes a little more sense.

Cloud Functions for Firebase, Develop a backend without servers. Create functions that are triggered by Firebase products Duration: 2:23 Posted: Mar 9, 2017 Use Cloud Functions directly from Firebase to extend your application functionality without spinning up a server. Run your code in response to user actions, analytics, and authentication events to keep your users engaged with event-based notifications and offload CPU- and networking-intensive tasks to Google Cloud.

Did you tried using { source: '/url/**' } syntax?

You can use something like this;

{
  "hosting": {
    "public": "public",
    "rewrites": [ {
    "source": "/url/**",
    "function": "/url"
    }]
  }
}

and then you can parse the url from the request.

 exports.url = functions.https.onRequest((req, res) => { 
   // parse the url from the req and redirect to the correct link
 });

Get started: write, test, and deploy your first functions, Initialize Firebase SDK for Cloud Functions � Run firebase login to log in via the browser Duration: 9:28 Posted: May 21, 2020 Google Cloud Platform, GCP, has an article addressing this question, Google Cloud Functions and Firebase. Google Cloud Functions and Firebase. Google Cloud Functions is Google's serverless compute solution for creating event-driven applications. It is a joint product between the Google Cloud Platform team and the Firebase team.

You should try this in the firebase.json, its worked for me:

"source": "/**",

I also tried "source": "/url/**" but its not worked.

What can I do with Cloud Functions?, Cloud Functions gives developers access to Firebase and Google Cloud events, along with scalable computing power to run code in response� Cloud Functions allows you to easily have code that runs in the cloud without a server. We'll show you how to build functions that react to Firebase Auth, Cloud Storage and Firebase Realtime Database events. Let's start with Auth. When using the Firebase SDK for Cloud Functions your code will live under the functions directory.

I think your code is fine. What you're doing incorrectly is that you're using Express-js notations in your firebase.json's rewrites node. (the :item part). These don't work in the Firebase Realtime Database.

So, instead of doing that, change your firebase.json to the following :-

 {
  "hosting": {
    "public": "public",
    "rewrites":  {
    "source": "YOUR SHORTENED URL",
    "destination": "YOUR ORIGINAL URL"
  } 
  }
}

This is also the advocated approach in the Cloud Functions for Firebase's URL Shortener sample.

Getting Started with Cloud Functions for Firebase using TypeScript , Cloud Functions for Firebase lets you automatically run backend code in response to events Duration: 9:28 Posted: Apr 3, 2018 Cloud Functions for Firebase Sample Library. This repository contains a collection of samples showcasing some typical uses of Cloud Functions for Firebase. What's Cloud Functions for Firebase? Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code.

First make sure you are receiving the request properly with the shortened url.

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

const express = require('express');
var express_app = express();
express_app.use(body_parser.text({type: ()=>true}));
express_app.all('*', (req, res) => {
    console.log(req.path);
    res.send(JSON.stringify(req.path));
});
exports.url = functions.https.onRequest(express_app);

Now when you visit myapp.firebaseappurl.com/url/SHORTENEDLINK you should see the SHORTENEDLINK in plain text. When that's working, try the redirect.

const functions = require('firebase-functions');
const express = require('express');
const request = require('request');
var express_app = express();
express_app.use(body_parser.text({type: ()=>true}));
express_app.all('*', (req, res) => {
    var url = req.path;
    request({
        uri: uri,
        followRedirect: true
      },
      function(err, httpResponse) {
        if (err) {
          return console.error(err);
        }
        res.send(httpResponse.headers.location || uri);
      }
    );
});
exports.url = functions.https.onRequest(express_app);

Also it's good practice to npm install with --save so they end up in the packages.json. While firebase copies your node_modules folder, most other SaaS platforms run npm install.

Google Cloud Functions and Firebase, Firebase gives mobile developers access to a complete range of fully managed mobile-centric services including analytics, authentication and� The Cloud Functions module provides the functionality to directly trigger deployed HTTPS callable functions, without worrying about security or implementing a HTTP request library. Functions deployed to Firebase have unique names, allowing you to easily identify which endpoint you wish to send a request to. To learn more about deploying

firebase/functions-samples: Collection of sample apps , What's Cloud Functions for Firebase? Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. Cloud� You might have heard that Cloud Functions supports Node.js 10 since May 18, 2020 and has deprecated Node.js 8 since June 5, 2020.And in the Firebase console, you’ll notice this message: Node.js

firebase/firebase-functions: Firebase SDK for Cloud Functions, Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. The Firebase SDK for Cloud Functions integrates the� Cloud Functions is a Google Cloud feature that allows functions to run in the cloud. In this article I’ll show you the use of Cloud Functions in Firebase, creating an e-mail sending function that…

Cloud Functions for Firebase, Trigger Cloud Functions based on Auth, Cloud Storage and Cloud Firestore events. Add Firebase Cloud Messaging support to your web app. What you'll need.

Comments
  • add method : 'POST' to the request
  • Why? The passed parameter is in the URL, so it's a GET request, right?
  • @mohamadrabee - Also, just tried it to see if that was it. Nope. Didnt work.
  • sorry my mistake
  • can you share your package.json? did you have 'request' in the dependencies
  • I thought a rewrite is needed to tell my firebase hosting which function to run based on which url?
  • Try this us-central1-helloworld-9d223.cloudfunctions.net/… url>
  • @JamesG Did you get a chance to try the solution?
  • This will not be dynamic. I want to be able to pass to the function the url as a parameter. Any thoughts?
  • @Rohan The sample is meant only for goo.gl urls. Besides, url resolution can be done using HEAD requests which are more light weight compared to GET
  • @JamesG Yes, it won't be dynamic. But you can simply save the original URL in your specified location whenever you shorten it. And for accessing the original URL, you can just add code inside your Cloud functions file to read it from the specified location during the HTTP trigger and use it as the URL for the your response. This of course won't be dynamic. But, you won't have to unshorten the url on the fly and you also won't have to include a third party application.