Advertisement
  1. Code
  2. JavaScript
  3. Node

Adding Social Sharing in a Node.js Single-Page Application

Scroll to top

Single-Page Applications (SPAs) are powered by client-side rendering templates, which give the end user a very dynamic experience. Recently, Google announced that they crawl web pages and execute JavaScript as a normal user would, resulting in sites powered by SPA frameworks (Angular, Ember, and Vue, to name a few) being crawled without Google penalty.

Beyond search, other web crawlers are important to your site’s visibility—namely rich social-sharing robots that rely on meta tags are still blind to JavaScript.

In this tutorial, we will build an alternate route and rendering module for your Express and Node.js server that you can use with most SPA frameworks and that will enable your site to have rich sharing on Twitter, Facebook and Pinterest.

A Word of Warning

This tutorial deals exclusively with web robots that extract social sharing information. Do not attempt this technique with search engine web crawlers. Search engine companies can take this kind of behavior seriously and treat it as spam or fraudulent behavior, and as such your rankings may quickly tank.

Similarly, with rich social-sharing information, make sure you are representing content in a way that aligns what the user sees with what the robot reads. Failing to keep this alignment could result in restrictions from social media sites.

Rich Social Sharing

If you post an update in Facebook and include a URL, a Facebook robot will read the HTML and look for OpenGraph meta tags. Here is an example of the Envato Tuts+ homepage:

Envato Tuts+ Social Share ScreenshotEnvato Tuts+ Social Share ScreenshotEnvato Tuts+ Social Share Screenshot

Inspecting the page, in the head tag, here are the relevant tags that generate this preview:

1
2
3
4

Pinterest uses the same protocol as Facebook, OpenGraph, so their sharing works much the same.

On Twitter, the concept is called a “card”, and Twitter has a few different varieties depending on how you want to present your content. Here is an example of a Twitter card from GitHub:

Screenshot of Twitter Card generated by a GitHub pageScreenshot of Twitter Card generated by a GitHub pageScreenshot of Twitter Card generated by a GitHub page

And here is the HTML that generates this card:

1
2
3
4
5
6

Note: GitHub is using a similar technique to what is described in this tutorial. The page HTML is slightly different in the tag with the name attribute set to twitter:description. I had to change the user agent as described later in the article to get the correct meta tag.

The Rub With Client-Side Rendering

Adding the meta tags is not a problem if you want just one title, description or image for the entire site. Just hard-code the values into the head of your HTML document. Likely, however, you are building a site that is much more complex and you want your rich social sharing to vary based on URL (which is probably a wrapper around the HTML5 History API which your framework is manipulating).

The first attempt might be to build your template and add the values to the meta tags as you would with any other content. Since, at this time, the bots that extract this information do not execute JavaScript, you’ll end up with your template tags instead of your intended values when trying to share.

To make the site readable by bots, we’re building a middleware that detects the user agent of the social sharing bots, and then an alternate router that will serve up the correct content to the bots, avoiding using your SPA framework.

The User Agent Middleware

Clients (robots, web crawlers, browsers) send a User Agent (UA) string in the HTTP headers of every request. This is supposed to identify the client software; while web browsers have a huge variety of UA strings, bots tend to be more or less stable. Facebook, Twitter and Pinterest publish the user agent strings of their bots as a courtesy.

In Express, the UA string is contained in the request object as user-agent. I’m using a regular expression to identify the different bots I’m interested in serving alternate content. We’ll contain this in a middleware. Middlewares are like routes, but they don’t need a path or method and they (generally) pass the request on to another middleware or to the routes. In Express, routes and middlewares are sequential, so place this above any other routes in your Express app.

1
2
app.use(function(req,res,next) {
3
  var
4
    ua = req.headers['user-agent'];
5
6
  if (/^(facebookexternalhit)|(Twitterbot)|(Pinterest)/gi.test(ua)) {
7
    console.log(ua,' is a bot');
8
  } 
9
10
 next();
11
});

The regular expression above looks for “facebookexternalhit”, “Twitterbot” or “Pinterest” at the start of the UA string. If it exists, it will log the UA to the console.

Here is the whole server:

1
2
var
3
  express   = require('express'),
4
  app       = express(),
5
  server;
6
7
app.use(function(req,res,next) {
8
  var
9
    ua = req.headers['user-agent'];
10
11
  if (/^(facebookexternalhit)|(Twitterbot)|(Pinterest)/gi.test(ua)) {
12
    console.log(ua,' is a bot');
13
  } 
14
15
  next();
16
});
17
18
app.get('/',function(req,res) {
19
  res.send('Serve SPA');
20
});
21
22
server = app.listen(
23
  8000,
24
  function() {
25
    console.log('Server started.');
26
  }
27
);

Testing Your Middleware

In Chrome, navigate to your new server (which should be http://localhost:8000/). Open DevTools and turn on ‘Device Mode’ by clicking the smartphone icon in the upper left part of the developer pane.

Screenshot of Chrome DevTools showing the location of Device ModeScreenshot of Chrome DevTools showing the location of Device ModeScreenshot of Chrome DevTools showing the location of Device Mode

On the device toolbar, put “Twitterbot/1.0” into the UA edit box.

Screenshot of Chrome DevTools illustrating the location of the input box for user agentsScreenshot of Chrome DevTools illustrating the location of the input box for user agentsScreenshot of Chrome DevTools illustrating the location of the input box for user agents

Now, reload the page.

At this point, you should see “Serve SPA” in the page, but looking at the console output of your Express app, you should see:

Twitterbot/1.0 is a bot

Alternate Routing

Now that we can identify bots, let’s build an alternate router. Express can use multiple routers, often used to partition routes out by paths. In this case, we’re going to use a router in a slightly different way. Routers are essentially middlewares, so they except req, res, and next, just like any other middleware. The idea here is to generate a different set of routes that has the same paths.

1
2
nonSPArouter = express.Router();
3
nonSPArouter.get('/', function(req,res) {
4
  res.send('Serve regular HTML with metatags');
5
});

Our middleware needs to be changed as well. Instead of just logging that the client is a bot, we will now send the request to the new router and, importantly, only pass it along with next() if the UA test fails. So, in short, bots get one router and everyone else gets the standard router that serves the SPA code.

1
2
var
3
  express   = require('express'),
4
  app       = express(),
5
  
6
  nonSPArouter      
7
            = express.Router(),
8
  server;
9
10
nonSPArouter.get('/', function(req,res) {
11
  res.send('Serve regular HTML with metatags');
12
});
13
14
app.use(function(req,res,next) {
15
  var
16
    ua = req.headers['user-agent'];
17
18
  if (/^(facebookexternalhit)|(Twitterbot)|(Pinterest)/gi.test(ua)) {
19
    console.log(ua,' is a bot');
20
    nonSPArouter(req,res,next);
21
  } else {
22
    next();
23
  }
24
});
25
26
app.get('/',function(req,res) {
27
  res.send('Serve SPA');
28
});
29
30
server = app.listen(
31
  8000,
32
  function() {
33
    console.log('Server started.');
34
  }
35
);

If we test using the same routine as above, setting the UA to Twitterbot/1.0 the browser will show on reload:

Serve regular HTML with metatags

While with the standard Chrome UA you’ll get:

Serve SPA

Meta Tags

As we examined above, rich social sharing relies on meta tags inside the head of your HTML document. Since you’re building a SPA, you may not even have a templating engine installed. For this tutorial, we’ll use jade. Jade is a fairly simple tempting language where spaces and tabs are relevant and closing tags are not needed. We can install it by running:

npm install jade

In our server source code, add this line before your app.listen.

app.set('view engine', 'jade');

Now, we’re going to input the information we want to serve to the bot only. We’ll modify the nonSPArouter. Since we’ve set up the view engine in app set, res.render will do the jade rendering.

Let’s set up a small jade template to serve to the social sharing bots:

1
2
doctype html
3
html
4
  head
5
    title= title
6
    meta(property="og:url"  name="twitter:url" content= url)
7
    meta(property="og:title" name="twitter:title" content= title)
8
    meta(property="og:description" name="twitter:description" content= descriptionText)
9
    meta(property="og:image" content= imageUrl)
10
    meta(property="og:type" content="article")
11
    meta(name="twitter:card" content="summary")
12
  body
13
    h1= title
14
    img(src= img alt= title)
15
    p= descriptionText

Most of this template is the meta tags, but you can also see that I included the information in the body of the document. As of the writing of this tutorial, none of the social sharing bots seem to actually look at anything else beyond the meta tags, but it’s good practice to include the information in a somewhat human readable way, should any sort of human checking be implemented at a later date.

Save the template to your app’s view directory and name it bot.jade. The filename without an extension (‘bot’) will be the first argument of the res.render function.

While it’s always a good idea to develop locally, you’re going to need to expose your app in its final location to fully debug your meta tags. A deployable version of our tiny server looks like this:

1
2
var
3
  express   = require('express'),
4
  app       = express(),
5
  
6
  nonSPArouter      
7
            = express.Router(),
8
  server;
9
10
nonSPArouter.get('/', function(req,res) {
11
  var
12
    img   = 'placeholder.png';
13
    
14
  res.render('bot', { 
15
    img       : img,
16
    url       : 'https://bot-social-share.herokuapp.com/',
17
    title     : 'Bot Test', 
18
    descriptionText 
19
              : 'This is designed to appeal to bots',
20
    imageUrl  : 'https://bot-social-share.herokuapp.com/'+img
21
  });
22
});
23
24
app.use(function(req,res,next) {
25
  var
26
    ua = req.headers['user-agent'];
27
28
  if (/^(facebookexternalhit)|(Twitterbot)|(Pinterest)/gi.test(ua)) {
29
    console.log(ua,' is a bot');
30
    nonSPArouter(req,res,next);
31
  } else {
32
    next();
33
  }
34
});
35
36
app.get('/',function(req,res) {
37
  res.send('Serve SPA');
38
});
39
app.use('/',express.static(__dirname + '/static'));
40
app.set('view engine', 'jade');
41
server = app.listen(
42
  process.env.PORT || 8000,
43
  function() {
44
    console.log('Server started.');
45
  }
46
);

Also note that I’m using the express.static middleware to serve the image from the /static directory.

Debugging Your App

Once you’ve deployed your app to somewhere publicly accessible, you should verify that your meta tags are working as desired.

First up, you can test with the Facebook Debugger. Input your URL and click Fetch new scrape information.

You should see something like:

Screenshot of the Facebook open graph debuggerScreenshot of the Facebook open graph debuggerScreenshot of the Facebook open graph debugger

Next, you can move on to testing your Twitter card with the Twitter Card Validator. For this one, you need to be logged in with your Twitter account.

Screenshot of the Twitter Card ValidatorScreenshot of the Twitter Card ValidatorScreenshot of the Twitter Card Validator

Pinterest provides a debugger, but this example will not work out-of-the-box because Pinterest only allows “rich pins” on URLs other than your homepage.

Next Steps

In your actual implementation, you’ll need to handle integrating your data source and routing. It’s best to look at the routes specified in your SPA code and create an alternate version for everything you think may be shared. After you’ve established the routes that will be likely to be shared, set up meta tags in your primary template that function as your fallback in the situation that someone shares a page you didn’t expect.

While Pinterest, Facebook and Twitter represent a large chunk of the social media market, you may have other services that you want to integrate. Some services do publish the name of their social sharing robots, while others may not. To determine the user agent, you can console.log and examine the console output—try this first on a non-production server as you may have a bad time trying to determine the user agent on a busy site. From that point, you can modify the regular expression in our middleware to also catch the new user agent.

Rich social media shares can be a great way to pull people into your fancy single-page-application-based website. By selectively directing robots to machine-readable content, you can provide just the right information to the robots.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.