Express CDN Integration

Express is a popular web framework for Node.js. Express is light-weight, versatile and offers a solid set of functionality for all kinds of web apps. Express is based on a lean layer of essential web application features. express-simple-cdn is a Node.js module for Express that makes an Express CDN integration for static assets really easy. This tutorial explains how to use express-simple-cdn with KeyCDN.

express cdn

CDN integration with Express and EJS without NPM package

This example describes how preisheld.ch managed to integrate the CDN into their Node.JS app with Express and EJS as templating engine. There are two possible approaches without using an NPM plugin.

Approach 1: Return the full tag by a function

  1. Write a function in your app.js or wherever you handle your functions. First, define a variable with your CDN URL. Second, register that variable in a function with several attributes which returns the full tag of the requested asset. The advantage of this approach is, that you can use a defined tag structure for every asset.
    // Initialize Express in a variable in app.js
    var app = express();
    
    // Define Your CDN base path
    var CDN = "https://assets.preisheld.ch";
    
    // Register a local variable in your app which contains the CDN function
    app.locals.CDN = function(path, type, classes, alt) {
       if(type == 'js') {
          return "<script src='"+CDN+path+"' type='text/javascript'></script>"; 
       } else if (type == 'css') { 
          return "<link rel='stylesheet' type='text/css' href='"+CDN+path+"'/>"; 
       } else if (type == 'img') { 
          return "<img class='"+classes+"' src='"+CDN+path+"' alt='"+alt+"' />"; 
       } else { 
          return ""; 
       } 
    };

    Do not forget to export the module, in order to have access to the function:
    module.exports = app;

  2. In your template, e.g. index.ejs, call your function where you need your assets:
    // CSS
    <%- CDN('/stylesheets/main.min.css', 'css', '', ''); %>
    
    // image
    <%- CDN('/images/dummy-image.png', 'img', 'img-responsive', 'my picture'); %>
    
    // JavaScript
    <%- CDN('/javascript/load.js', 'js', '', ''); %>

Approach 2: Use a global variable

You can simply place a variable in you ejs template without any function. In this case, you need to pay a bit more attention, that your tags look always the same. If you are using a default class for all your images, approach 1 should be preferred.

  1. Define the variable which contains your CDN path:
    app.locals.CDN = "https://assets.preisheld.ch";
    module.exports = app;
  2. In your html / ejs template, place the variable before you relative path in the src attribute. As you put out a variable directly, use <%= %> instead of <%- %>
    <img class="img-responsive" src="<%= CDN %>/images/dummy-image.png" alt="my picture" />

Express CDN Integration with an NPM package

  1. This tutorial assumes that you’re also using Jade. Let’s get started with the installation of express-simple-cdn:
    $ npm install express-simple-cdn
  2. There are a number of configurations available. Add any of following to Express app.configure. You can define different CDN URLs  for production and dev environments using configurations for each environment. Call the module like this:
    var CDN = require('express-simple-cdn');
  3. The next step is to add a template variable to your CDN host options. This can be the kxcdn domain (e.g. yourzone-99ff.kxcdn.com) or your own zone alias (e.g. cdn.yourdomain.com):
    app.locals.CDN = function(path) { 
       return CDN(path, '//yourzone-99ff.kxcdn.com') 
    }; 
    // In Jade, script(src=CDN('/js/yourscript.js')) will become script(src='//yourzone-99ff.kxcdn.com/js/yourscript.js')
  4. (Optional) In case you’re using different file versions in the URL, the following configuration will ensure that the latest versions of your assets is loaded from KeyCDN after deploying updates when the useFileVersion is passed as true:
    server.locals.CDN = function (path, useFileVersion) { 
       if(useFileVersion === undefined || useFileVersion == false) 
          return CDN(path, config.CDNURL); 
       else 
          return CDN(path, config.CDNURL, config.CDNVersion); 
    };
  5. For all the code snippets above, here’s how the config of the CDN function in your Jade template should look like:
    // JS 
    script(src=CDN('/js/yourscript.js')) 
    
    // CSS 
    link(href=CDN('/css/yourcss.css'), rel='stylesheet') 
    
    // Images 
    img(src=CDN('/img/yourimage.png'))

    The creator of express-simple-cdn is jamies, the source code is available on Github.

Benefits of an Express CDN Integration

A CDN can help increase the delivery speed of your Express assets by caching them across multiple strategically placed edge servers. Website latency is in many cases decreased significantly for websites using a CDN compared to websites not using a CDN. There also exists many other benefits to implementing an Express CDN integration with KeyCDN such as: