Adding Drift chat widget to a Nuxt.js app

Here's the steps and the code to add the drift.js widget to a nuxt.js application.

Adding Drift chat widget to a Nuxt.js app

I've been using Drift on one of my sideprojects, mydevportfol.io. I find it's great to have conversations with my users, so when it came to my other side project referextra.com and needing a chat widget, Drift was a natural choice.

But, Referextra is both a server-side-generated nuxt app for the marketing site, and a single-page Vue app for the actual web app side of things. In this post, I'll document the steps I needed to take to add Drift to my nuxt.js server-side rendered marketing site.

The following steps assume you've already got a Drift account, and you've gotten to the screen where they give you the code to copy-paste into the HEAD of your pages.

Adding Drift.js chat widget to Nuxt.js apps

  1. Create a drift.js file in your /plugins directory
  2. Copy-paste the code below into your new drift.js file you just created, replacing YOUR-DRIFT-CODE with your drift code, obviously...
  3. Finally, add the following line to your nuxt.config.js file
    plugins: [{src:"~plugins/drift.js", mode:'client'}]
export default () => {
  !function() {
    var t = window.driftt = window.drift = window.driftt || [];
    if (!t.init) {
      if (t.invoked) return void (window.console && console.error && console.error("Drift snippet included twice."));
      t.invoked = !0, t.methods = [ "identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on" ],
      t.factory = function(e) {
        return function() {
          var n = Array.prototype.slice.call(arguments);
      return n.unshift(e), t.push(n), t;
    };
      }, t.methods.forEach(function(e) {
        t[e] = t.factory(e);
      }), t.load = function(t) {
        var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement("script");
      o.type = "text/javascript", o.async = !0, o.crossorigin = "anonymous", o.src = "https://js.driftt.com/include/" + n + "/" + t + ".js";
      var i = document.getElementsByTagName("script")[0];
      i.parentNode.insertBefore(o, i);
    };
  }
  }();
  drift.SNIPPET_VERSION = '0.3.1';
  drift.load('YOUR-DRIFT-CODE');
  
};

Notes

mode:client tells nuxt not to render this code on the server. This is because it uses the window object, and will throw an error on the server, where window does not exist.

Resources