Search code examples
firebaseseogoogle-cloud-functionsfirebase-hosting

How to use Cloud Functions for Firebase to prerender pages for SEO?


The Cloud Functions for Firebase documentation here states that this can be done using cloud functions -

Prerendering for single page apps to improve SEO. This allows you to create dynamic meta tags for sharing across various social networks.

There are 2 questions I have:

  • Can someone explain with an example how pre-rendering is achieved?

  • How does this work in conjunction with Firebase Hosting? So let's say I have a webpage at xyz.com/salon/43 and in Firebase hosting I have a salon.html which is served in response to this request. Now in order to be able to prerender should I move from hosting to a cloud function which renders the webpage? In other words do I go from

    "rewrites": [{
        "source": "/salon/*",
        "destination": "/salon.html"}]
    

    to

    "rewrites": [{
        "source": "/salon", "function": "salon"}]
    

Solution

  • Two tasks: - Add the function to your hosting rewrite as in your example - Write the function to generate an html page

    This tutorial provides a great example, with the following function as an example from a longer snippet:

    const admin = require('firebase-admin');
    
    function buildHtmlWithPost (post) {
      const string = '<!DOCTYPE html><head>' \
        '<title>' + post.title + ' | Example Website</title>' \
        '<meta property="og:title" content="' + post.title + '">' \
        '<meta property="twitter:title" content="' + post.title + '">' \
        '<link rel="icon" href="https://example.com/favicon.png">' \
        '</head><body>' \
        '<script>window.location="https://example.com/?post=' + post.id + '";</script>' \
        '</body></html>';
      return string;
    }
    
    module.exports = function(req, res) {
      const path = req.path.split('/');
      const postId = path[2];
      admin.database().ref('/posts').child(postId).once('value').then(snapshot => {
        const post = snapshot.val();
        post.id = snapshot.key;
        const htmlString = buildHtmlWithPost(post);
        res.status(200).end(htmlString);
      });
    };