Skip to content

Greg Jopa

Render D3.js Charts Server-side

JavaScript, Node.js, D3.js

D3 Bar Chart

The D3.js library can be used on the client-side or the server-side. This post will explain how to use JSDOM to render a D3 chart visualization on the server-side with Node.js.

D3 Server-side Demo

Setting up D3 on the Server-side

First install D3 with npm npm install d3. The D3 library was re-written in version 4 to be modular so if you're using D3 version 4 or greater you have two options:

  1. require the whole D3 library: const d3 = require('d3');
  2. require just the modules you need. Ex:
1const d3 = Object.assign({},
2 require('d3-selection').
3 require('d3-scale'),
4 require('d3-axis'),
5 require('d3-array')
6);

The d3-selection module depends on the DOM for operations like selecting elements and setting attributes. Luckily we can use JSDOM to get d3-selection working in Node-land.

1const jsdom = require('jsdom');
2const { JSDOM } = jsdom;
3// create a new JSDOM instance for d3-selection to use
4const document = new JSDOM().window.document;
5
6d3.select(document.body)
7 .append('div')
8 // and so on

JSDOM is commonly used for unit testing modules that rely on the DOM. That way you can unit test client-side code without a browser. The d3-selection library uses JSDOM for unit testing so reference those tests for more examples.

Demo App

The demo app I put together creates a helper for server-side rendering bar charts with D3. Here's an example of the helper in action:

1barChartHelper.getBarChart({
2 data: fixtureData,
3 width: 400,
4 height: 300,
5 xAxisLabel: '2012',
6 yAxisLabel: 'Views',
7 containerId: 'bar-chart-small'
8})

At the time of this writing it's using D3 version 5 and Node.js version 12. Check out the source code on GitHub: https://github.com/gregjopa/d3-server-side-demo