Skip to content

Greg Jopa

Render SVG Charts Server-side with D3.js

JavaScript, Node.js

Update: This blog post is really old. Here's a more recent post about this topic:
Render D3.js charts server-side with Node version 12+

D3 Bar Chart

It's common to use d3.js to render svg charts on the client-side. With the d3 node module you can render svg charts on the server-side as well. The d3 node module uses jsdom to simulate the browser's Document Object Model (DOM) which allows for d3 selectors to work on the server-side.

Running D3 on the server with Node.js is pretty easy. You can reuse most of your client-side d3 code on the server. The only tricky part is integrating d3 widgets into your server-side views.


Getting started with running D3 on Node.js

Install the d3 node module using npm: npm install d3. The d3 node module uses jsdom which requires a C++ compiler. Read more about this dependency here:

After you get d3 installed you can require it like any other node module:

1var d3 = require('d3');

Reusable Chart Pattern

I recommend using the reusable chart design pattern for your charts: This modular pattern works great on the client and on the server. Since the reusable chart pattern is just a function you can assign it directly to module.exports:

1var barChart = module.exports = function() { ...

D3 View Helper

My demo app uses the express.js web framework with the ejs templating engine. I want to be able to integrate my D3 chart widgets into my view templates. I accomplished this by appending my chart widget to the jsdom and then getting it's outerHTML value and rendering it in my ejs template:


1var getBarChart = function (params) {
3 var chart = barChart()
4 .data(
5 .width(params.width)
6 .height(params.height)
7 .xAxisLabel(params.xAxisLabel)
8 .yAxisLabel(params.yAxisLabel);
11 // append to jsdom
12'body').append('div').attr('id', params.containerId).call(chart);
14 var selector = '#' + params.containerId;
16 // get html string "<div id="bar-chart-small"><svg class="svg-chart"> ..."
17 var svg =;
19 // remove from jsdom
22 return svg;


1<!-- ejs template -->
2<h1>D3 Server-side Demo</h1>
4 barChartHelper.getBarChart({
5 data: fixtureData,
6 width: 400,
7 height: 300,
8 xAxisLabel: '2012',
9 yAxisLabel: 'Views',
10 containerId: 'bar-chart-small'
11 })

To see this code in action download my d3-server-side-demo express.js app here: