logo

G2

  • Chart Gallery
  • Docs
  • Examples
  • Theme
  • Ecosystem
  • Productsantv logo arrow
  • 5.3.3
  • Get Started
  • Introduction
    • What is G2
    • Using in Frontend Frameworks
    • Experimental Spec API
  • Chart API
  • Core Concepts
    • Chart
      • Components of G2 Charts
      • How to Use Charts
    • Mark
      • Overview
      • area
      • box
      • boxplot
      • cell
      • chord
      • density
      • gauge
      • heatmap
      • image
      • interval
      • line
      • lineX
      • lineY
      • link
      • liquid
      • sunburst
      • point
      • polygon
      • range
      • rangeX
      • rangeY
      • rect
      • shape
      • text
      • vector
      • connector
      • wordCloud
    • View
    • Data
      • Overview
      • custom
      • ema
      • fetch
      • filter
      • fold
      • inline
      • join
      • kde
      • log
      • map
      • pick
      • rename
      • slice
      • sort
      • sortBy
    • Encode
    • Scale
      • Overview
      • band
      • linear
      • log
      • ordinal
      • point
      • quantile
      • quantize
      • sqrt
      • threshold
      • time
      • pow
    • Transform
      • Overview
      • bin
      • binX
      • diffY
      • dodgeX
      • flexX
      • group
      • groupColor
      • groupX
      • groupY
      • jitter
      • jitterX
      • jitterY
      • normalizeY
      • pack
      • sample
      • select
      • selectX
      • selectY
      • sortColor
      • sortX
      • sortY
      • stackEnter
      • stackY
      • symmetryY
    • Coordinate
      • Overview
      • fisheye
      • parallel
      • polar
      • theta
      • transpose
      • radial
      • cartesian3D
      • helix
    • Style
    • Animate
      • Overview
      • fadeIn
      • fadeOut
      • growInX
      • growInY
      • morphing
      • pathIn
      • scaleInX
      • scaleInY
      • scaleOutX
      • scaleOutY
      • waveIn
      • zoomIn
      • zoomOut
    • State
    • Interaction
      • Overview
      • brushAxisHighlight
      • brushHighlight
      • brushXHighlight
      • brushYHighlight
      • brushFilter
      • brushXFilter
      • brushYFilter
      • chartIndex
      • elementHighlight
      • elementHighlightByColor
      • elementHighlightByX
      • elementSelect
      • elementSelectByColor
      • elementSelectByX
      • legendFilter
      • legendHighlight
      • poptip
      • scrollbarFilter
      • sliderFilter
      • fisheye
    • Composition
      • Overview
      • facetCircle
      • facetRect
      • repeatMatrix
      • spaceFlex
      • spaceLayer
      • timingKeyframe
    • Theme
      • Overview
      • academy
      • classic
      • classicDark
    • Events
    • Color Mapping
  • Chart Component
    • Title
    • Axis
    • Legend
    • Scrollbar
    • Slider
    • Tooltip
    • Data Label
  • Extra Topics
    • Graph
      • forceGraph
      • pack
      • sankey
      • tree
      • treemap
    • Geo
      • geoPath
      • geoView
    • 3D
      • Draw 3D Chart
      • point3D
      • line3D
      • interval3D
      • surface3D
    • Plugin
      • renderer
      • rough
      • lottie
      • a11y
    • Package on demand
    • Set pattern
    • Server-Side Rendering (SSR)
    • Spec Function Expression Support (Available in 5.3.0)
  • Whats New
    • New Version Features
    • Migration from v4 to v5
  • Frequently Asked Questions (FAQ)

Server-Side Rendering (SSR)

Previous
Set pattern
Next
Spec Function Expression Support (Available in 5.3.0)

Resources

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-互动图形解决方案
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Server-Side Rendering (SSR) refers to rendering charts in non-browser environments, as opposed to Client-Side Rendering (CSR). This typically occurs in backend languages like Node.js, Python, Java, PHP, etc., producing static images without interactivity or animations. Common use cases include:

  • Pre-rendering images on the backend to improve page load speed
  • Batch processing scripts for easier distribution
  • Server-side visualization services
  • Generating images for screenshot comparison in unit testing
  • ...

Using in Node.js

Frontend data visualization libraries are built upon browser DOM Canvas APIs. To render charts in Node.js, we need to replace the DOM Canvas with Node Canvas. In the Node.js ecosystem, node-canvas provides a Cairo-based implementation of the Canvas2D API that aligns with browser standards.

By leveraging node-canvas and AntV's G2 (which supports custom Canvas objects), we can switch to Node.js rendering engines for server-side chart generation.

Implementation with node-canvas + G2

Online Example - Note: jsdom-based solutions can only generate SVG. For PNG-like formats, use node-canvas.

Firstly, create two node-canvases, one for rendering the scene and the other for measuring text width:

const { createCanvas } = require('canvas');
const nodeCanvas = createCanvas(width, height);
const offscreenNodeCanvas = createCanvas(1, 1);

Then create a canvas renderer and canvas:

import { Canvas } from '@antv/g';
import { Renderer } from '@antv/g-canvas';
const renderer = new Renderer();
// Omitting the removal of DOM-related plugin code.
const gCanvas = new Canvas({
width,
height,
canvas: nodeCanvas,
renderer,
offscreenCanvas: offscreenNodeCanvas,
});

Next, create a G2 Chart as usual and render it. After completion, use the createPNGStream method provided by node-canvas to create a ReadableStream containing the PNG encoding. Similarly, createJPEGStream and createPDFStream are also available for exporting JPEG and PDF, respectively.

function writePNG(nodeCanvas) {
return new Promise<string>((resolve, reject) => {
const f = path.join(os.tmpdir(), `${Math.random()}.png`);
const out = fs.createWriteStream(f);
const stream = nodeCanvas.createPNGStream();
stream.pipe(out);
out.on('finish', () => resolve(f)).on('error', reject);
});
}

Using G2 SSR Open-Source Project

We've packaged the SSR solution into a ready-to-use library: @antv/g2-ssr.

const chart = await createChart({
width: 640,
height: 480,
imageType: 'png', // or 'jpeg'
// Other G2 configurations (refer to G2 docs)
type: 'interval',
data: [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
],
encode: {
x: 'genre',
y: 'sold',
color: 'genre',
},
});
// Export
chart.exportToFile('chart'); // -> chart.png
chart.toBuffer(); // -> get buffer

Renders in ~400ms with browser-equivalent quality:

Example chart generated by G2 SSR

AI MCP Integration

We've open-sourced an AI-oriented visualization solution leveraging this SSR capability: mcp-server-chart. It interprets AI model outputs and user intent to generate visualizations, currently supporting 15+ chart types and relational diagrams.

mcp-server-chart preview

Use in other server-side locales

Because the code of G2 is written and developed in JavaScript, it cannot be used directly in Python, Java, PHP and other language environments. However, you can install the Node.JS environment in the service and then use the corresponding back-end language command line API to drive the above-mentioned Node.JS code to perform SSR.

Refer to python calls node js, other languages ​​are similar.