Rich Social Sharing In SPA With AWS Cloudfront And Lambda Function

 

What Is Rich Social Sharing?

When you add your website link inside a Facebook, Twitter, LinkedIn, WhatsApp etc., social media post Then it specifies the image of the website and it shows the title of the link and describes the website link.

When you share the application link in facebook then it looks like the below image
What is Rich social sharing?

While working on simple static HTML pages we can easily show the rich social sharing: Open graph protocol. We need to include meta tags

<meta property="og:title" content="Rich social sharing in SPA with aws cloudfront lambda edge function">

<meta property="og:description" content="About rich social sharing ...">

<meta property="og:image" content="facebook.png">

Single Page Applications

While working on SPA like Angular, React js etc We need to include this meta tags content dynamically

Then the initial html looks like this

<meta property="og:title" content="{{title}}" />

<meta property="og:description" content="{{description}}" />

<meta property="og:image" content="{{image}}" />

When you want to share a SPA on Facebook or LinkedIn etc Then you will face a problem because social media networks only read the HTML content, but do not execute the javascript code so we don’t get the dynamic data on the social network post.

So after sharing such SPA with dynamic data to social media networks then the card will be broken.

So, to get rich social content in single-page applications, I will create a Lambda edge function that modifies the HTML content based on the User-Agent.

Implementation

Requirements to implement the Lambda Edge function

  • You must have an AWS account with the required permissions
  • Your Web application must be delivered via CloudFront

Steps to Associate the lambda edge function with CloudFront distribution

  • Create IAM user for Lambda function with required permissions.
  • Create Lambda Edge function and create a version
  • Whitelist the User-Agent header in CloudFront behavior
  • Cloudfront configuration
  • Associate the Lambda edge function with CloudFront distribution behavior

Let’s Start

Create Aws Account

To create an AWS account, Visit a below link

Create AWS account

After creating an account, Make sure you must have access to region – us-east-1 (N. virginia) because Lambda function association only accepts the function created in the us-east-1 region.

Cloudfront Distribution

For CloudFront distribution for web hosting, we are considering you already created your S3 bucket and associated it with the Cloudfront URL

You can use the link below for more details on how to create S3 bucket and associate with Cloudfront distribution for hosting SPA
https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/

Create IAM user

Create I am a user and add permission policies which required to access the Lambda function association with CloudFront distribution

Create IAM user

Create Lambda Edge Function

Create lambda Edge function

Create a Lambda function by clicking on the create function button.
While creating a Lambda edge function, make sure you are in an us-east-1 region because the Lambda association functions in CloudFront distribution only accept the functions created in region us-east-1 (N. virginia).

After clicking on create function button, we will get the following page

Create lambda Edge function

  • Add the Name of the function
  • Select the Node.js 10.x language for your function.
  • Select the Execution role “Use an existing role” and select the created IAM User

Click on the create function button.

Now you have created the Lambda Edge function with the required user permissions.

Now let’s start the function coding.

var https = require("https");

var $url = require("url");

("use strict");

exports.handler = function(event, context, callback) {

  console.log("loading script....");

  const cf = event.Records[0].cf;

  const request = cf.request;

  const response = cf.response;

  const userAgent = request.headers["user-agent"][0].value;

  const webHost = your_web_host;

  let indexData = "";

  function done(error, data) {

if (data) {

   response.status = 200;

   response.statusDescription = "OK";

   response.body = data;

   response.headers = {...response.headers,

   'cache-control': [{

             key: 'Cache-Control',

             value: 'public,max-age=86400'

         }],

         'content-type': [{

             key: 'Content-Type',

             value: 'text/html'

         }]}

   callback(null, response);

} else {

   console.log("done: error");

   callback(null, { statusCode: "400", body: "Function error" });

}

  }

  function replaceMetaData(indexData, metaData, webHost, path) {

var url = webHost + path;

const htmlCode =

`<!DOCTYPE html>

  <html lang="en">

    <head>

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

      <meta property="og:type" content="website" />

      <meta property="og:title" content="${metaData.name}" />

      <meta property="og:description" content="${metaData.description}" />

      <meta property="og:image" content="${metaData.image}"/>

      <meta

        property="og:url"

        content="${url}"

      />

      <title>App name</title>

      <base href="/" />

      <meta name="viewport" content="width=device-width, initial-scale=1" />

    </head>

  </html>`;

done(null, htmlCode);

  }

  function checkAPIresponseData(data) {

if (data) {

   let metaBindingData = {

     name: data.name,

     image: data.image,

     description: data.image

   };

   replaceMetaData(indexData, metaBindingData, webHost, request.uri);

   }else{

     callback(null, response);

   } else {

   done(true);

}

  }

  function apiCall(id) {

https

   .get(Service API URL, res => {

     res.setEncoding("utf8");

     var apiResponseData = "";

     res.on("data", resData => {

       apiResponseData += resData.toString("utf8");

     });

     res.on("end", function() {

       checkAPIresponseData(JSON.parse(apiResponseData));

     });

   })

   .on("error", function(e) {

     done(true);

   });

  }

  let checkUserAgent = 0;

  // user agent is known social bot

  if (

userAgent.match(

   /baiduspider|twitterbot|Whatsapp|facebookexternalhit|googlebot|bingbot|yandex|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator/i

)

  ) {

checkUserAgent = 1;

  }

  // rendered page is requested by special query string

  if (request.querystring.match(/_escaped_fragment_/)) {

checkUserAgent = 1;

  }

// request targets non-html files

  if (

request.uri.match(

   /\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)/i

)

  ) {

checkUserAgent = 0;

  }

  if (checkUserAgent === 1) {

if (request.uri.startsWith("/users")) {

   let strParts = request.uri.split("/");

   let id = strParts[strParts.length - 1];

   apiCall(id);

}

else {

   callback(null, response);

}

  } else {

callback(null, response);

  }

};

In the above function we are changing the HTML body response on the basis of user agent.Code Explanation

If the request is from a social network, we check the web host url in the request. uri
In my case, it is “/users,” so based on this, I am calling the backend server to get the dynamic data.
After getting that dynamic data, we can change the meta tag values and send back the response with an updated HTML content body.

Then Deploy the Lambda function and then create a version of it.

Now we are clear upto the functionality; Now how to call the Lambda function for every request to check whether it is from a social network or not, we have to associate this Lambda function with CloudFront distribution.

Cloudfront Distribution

In CloudFront distribution, go to the behavior and click on => Edit button

Cloudfront_distribution

Then select the WhiteList on – Cache Based on Selected Request

Then select the WhiteList on -Cache Based on Selected Request

Then add a custom “User-Agent” header inside a WhiteList Headers.

Then Goto

  • Lambda Function Associations

Select “Origin Response” Event

Then add the Lambda function ARN with the new version

Lambda function ARN with new version

Then save the changes.

Wait for a few minutes to update the changes.

Conclusion

We have learned how to implement rich social share in a single-page application using CloudFront and Lambda edge function.

Happy Coding 🙂

Kumarswami

Tech Expert

Kumarswami Boga is a full-stack web application developer with 1.5 years of experience. He is eager to learn new technologies and passionate about his work. His area of expertise in HTML, CSS, javascript, and frontend frameworks reactjs, angularjs for backend creating rest API in Django-rest-framework.

The founder's survey report on "What Matters For Startup" is released - Get your copy and learn the trends of successful companies :)

Download Free eBook Now!

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

"Mindbowser was very helpful with explaining the development process and started quickly on the project."

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

"The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs."

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

"They're very tech-savvy, yet humble."

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

"Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier"

author
Katie Taylor
Founder, Child Life On Call
coma

“As a founder of a budding start up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity."

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give