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.


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

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">


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

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

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

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

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





      <title>App name</title>

      <base href="/" />

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



done(null, htmlCode);


  function checkAPIresponseData(data) {

if (data) {

   let metaBindingData = {


     image: data.image,

     description: data.image


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


     callback(null, response);

   } else {




  function apiCall(id) {


   .get(Service API URL, res => {


     var apiResponseData = "";

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

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


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




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




  let checkUserAgent = 0;

  // user agent is known social bot

  if (


   /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 (




  ) {

checkUserAgent = 0;


  if (checkUserAgent === 1) {

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

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

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



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


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.


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

Happy Coding 🙂


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.

Upcoming Webinar On "How To Achieve Project Success With Your Outsourced Team!"

Register Now

Get in touch for a detailed discussion.

Hear From Our 100+ Customers

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


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

Shaz Khan
CEO, BuyNow WorldWide

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

Kristen M.
Founder & CEO, TotTech

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

Chacko Thomas
Co-Founder, TEAM8s

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

Dave Dubier
Founder & CEO, MangoMirror

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

Hieu Le
Executive Director of Product Development, Innovation Lab

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.

Alex Gobel
Co-Founder, Vesica

Mindbowser is professional, efficient and thorough. 

MacKenzie R
Consultant at XPRIZE

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

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

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.

Bennet Gillogly
Co-Founder, Flat Earth

They're very tech-savvy, yet humble.

Uma Nidmarty
CEO, GS Advisorate, Inc.

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

Katie Taylor
Founder, Child Life On Call

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.

Radhika Kotwal
Founder of Courtyardly

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

Michael Wright
Chief Executive Officer, SDOH2Health LLC

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.

David Cain
CEO, thirty2give

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

Bart Mendel
Founder, Mindworks

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

George Hodulik
CEO, Stealth Startup, Ex-Google