← All articles

Server side rendering of a Three.js scene

Updated on . Tested with three.js r187, R3F 9 and drei 10.

Sometimes you need a three.js screenshot rendered server side. This could be when a shopper orders a chair in the fabric they picked and the order email needs a picture of it, or when every configuration needs its own share image. Many use Puppeteer or Playwright to capture their three.js page, but there are other methods that can be faster and more reliable.

An armchair with orange fabric beside a light oak side table and a white vase, in a room corner with a light blue wall, rendered on the server

The most basic way to render a three.js scene on your server, is the following:

  1. Build a page with your three.js scene and a function that renders one configuration.
  2. Open that page with Playwright.
  3. Wait until all the models and the HDRI have loaded.
  4. Call the function from step 1 with page.evaluate() for each configuration, and send the image back.

Build a page that renders one configuration

Don't be scared! The page is an ordinary three.js page with one extra function, renderConfiguration, that the server calls.

type Configuration = {
  fabric: string;
  width: number;
  height: number;
  transparent?: boolean;
};
// Render one configuration and return it as a PNG data URL.
async function renderConfiguration(configuration: Configuration): Promise<string> {
  await sceneReady;

  fabric.color.set(configuration.fabric);
  // A transparent PNG swaps the room for a shadow floor here, shown further down.

  renderer.setSize(configuration.width, configuration.height, false);
  camera.aspect = configuration.width / configuration.height;
  camera.updateProjectionMatrix();

  // Render and read the canvas in the same task, before the browser clears it.
  renderer.render(scene, camera);
  return renderer.domElement.toDataURL('image/png');
}
window.renderConfiguration = renderConfiguration;

The page doesn't need an animation loop. It renders only when the server asks, so nothing else can draw over the canvas between render() and toDataURL(). If you export from the canvas in the same function as the render call, you don't need preserveDrawingBuffer: true. The screenshot article explains why a read in a later task comes back empty.

The image can be any size you ask for, even larger than a screen. Simply call renderer.setSize(width, height, false) with the size you want before you render.

Wait until the models have loaded

Do not render until the models, their textures, and the HDRI have all loaded. If you render too early, the image will miss whatever has not arrived yet. In this example, the chair was still loading.

The same room rendered before the chair had loaded. The side table and its shadow are there, and the chair is missing

Load everything in a single function. Keep the promise it returns. Then await that promise at the top of renderConfiguration.

// Everything the picture needs: the model, its textures and the HDRI.
async function loadScene() {
  const [gltf, environment] = await Promise.all([
    new GLTFLoader().loadAsync('/demo/models/modern_arm_chair_01/modern_arm_chair_01_2k.glb'),
    new HDRLoader().loadAsync('/hdri/studio.hdr'),
  ]);

  // Add the model and the HDRI to the scene here.

  await renderer.compileAsync(scene, camera);
}

const sceneReady = loadScene();

GLTFLoader.loadAsync resolves after the model's textures have loaded as well. renderer.compileAsync compiles the shaders before the first request, so the first image is not slower than the others.

Drive the page from Node with Playwright

Playwright opens the page in headless Chrome. page.evaluate() calls renderConfiguration and returns the data URL to Node.

npm install playwright
npx playwright install chromium
import { createServer } from 'node:http';
import { chromium } from 'playwright';
// channel: 'chromium' is Chrome's new headless mode, which can use the GPU.
const browser = await chromium.launch({ channel: 'chromium' });
const page = await browser.newPage();
page.on('pageerror', (error) => console.error('page error:', error.message));
await page.goto(PAGE_URL);
await page.waitForFunction(() => typeof window.renderConfiguration === 'function');

type Configuration = Parameters<Window['renderConfiguration']>[0];

async function renderPng(configuration: Configuration): Promise<Buffer> {
  const dataUrl = await page.evaluate((c) => window.renderConfiguration(c), configuration);
  return Buffer.from(dataUrl.split(',')[1], 'base64');
}

You can then put an HTTP endpoint in front of it and have your system asks for a picture by URL. Check every value that comes in from the URL before it reaches the page.

const server = createServer(async (request, response) => {
  const url = new URL(request.url ?? '/', 'http://localhost');
  const fabric = url.searchParams.get('fabric') ?? '#ec9d3c';
  if (!/^#[0-9a-f]{6}$/i.test(fabric)) {
    response.writeHead(400).end('fabric must be a color like #ec9d3c');
    return;
  }

  try {
    const png = await renderPng({ fabric, width: 1200, height: 750, transparent: url.searchParams.has('transparent') });
    response.writeHead(200, { 'Content-Type': 'image/png' });
    response.end(png);
  } catch (error) {
    response.writeHead(500).end(String(error));
  }
});
server.listen(3000);

http://localhost:3000/?fabric=%239cc3e0 now returns a PNG of the chair in light blue. The # of the color is written %23 in a URL.

Keep the browser open between pictures

Open Chrome one time when the server starts, then use that same page for every picture. Starting Chrome, loading the models, and compiling the shaders all take much longer than a single render, so a server that opens a new browser for each request will be slow.

The one open browser can take several requests at the same time. It finishes one picture before it starts exporting the next, and that way the colors never get mixed up. We sent six requests at once, and each picture came back in the right color.

Remember to close Chrome when the server stops, or it will keep running in the background.

// Close Chrome with the server, or it keeps running in the background.
process.on('SIGINT', async () => {
  server.close();
  await browser.close();
  process.exit(0);
});

Save a transparent PNG

To get a transparent background, create the renderer with alpha: true, set scene.background to null, and leave out the room.

const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
if (configuration.transparent) {
    scene.remove(room);
    scene.add(shadowFloor);
    scene.background = null;
  } else {
    scene.remove(shadowFloor);
    scene.add(room);
    scene.background = backgroundColor;
  }

You can still keep the shadow under the product. Add a floor with a ShadowMaterial. This material is invisible, but it shows the shadows that fall on it.

const shadowFloor = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.ShadowMaterial({ opacity: 0.3 }));
shadowFloor.rotation.x = -Math.PI / 2;
shadowFloor.receiveShadow = true;

A transparent PNG of the armchair with light blue fabric. Only the chair and its soft gray shadow are drawn

toDataURL('image/png') keeps the alpha channel. A JPEG does not have an alpha channel, so a transparent picture must stay a PNG or a WebP.

Protip: Use the GPU, not SwiftShader

Launch Chrome with channel: 'chromium' to use its new headless mode, which draws with the machine's GPU. Playwright's default headless browser drew with SwiftShader, a software renderer, which can be several times slower.

To see which one you got, read the renderer's name in the page.

// Which GPU the page draws with. SwiftShader means software rendering.
function graphicsCard(): string {
  const gl = renderer.getContext();
  const info = gl.getExtension('WEBGL_debug_renderer_info');
  return info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
}

Log it with console.log(graphicsCard()) and read it in Node with page.on('console', ...) and look for a name containing "SwiftShader".

In React Three Fiber

In React Three Fiber, register renderConfiguration from a component inside the same <Suspense> as your models. This way it only exists once they have loaded.

// Mounted next to the models inside one Suspense, so it runs only once they have loaded.
function ServerRender() {
  const { gl, scene, camera } = useThree();
  useEffect(() => {
    window.renderConfiguration = async ({ fabric: color, width, height }) => {
      fabric.color.set(color);
      gl.setSize(width, height, false);
      if (camera instanceof THREE.PerspectiveCamera) {
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
      }
      gl.render(scene, camera);
      return gl.domElement.toDataURL('image/png');
    };
  }, [gl, scene, camera]);
  return null;
}
<Canvas
      frameloop="never"
      dpr={1}
      shadows
      camera={{ position: [1.45, 1.05, 2.35], fov: 35 }}
      onCreated={({ camera }) => camera.lookAt(0.1, 0.42, -0.3)}
    >
      <Suspense fallback={null}>
        <Environment files="/hdri/studio.hdr" environmentIntensity={0.45} />
        <directionalLight position={[3, 2.6, 1.4]} intensity={3} castShadow />
        <Chair />
        <ServerRender />
      </Suspense>
    </Canvas>

React does not run the effects of a <Suspense> boundary while any child in it is still loading. Because of this, the server's waitForFunction waits for the models without any extra code. frameloop="never" stops R3F from drawing on its own. The same Node server works without changes.

How to make it look even better

The Three.js viewport and the same scene rendered, side by side: An armchair with orange fabric beside a light oak side table and a white vase, in the corner of a room with a light blue wall
The page the server renders, and the same scene rendered by Bakery3

If you would rather not run a browser on your server, and want a better picture at the same time, the Bakery3 API renders your three.js scene with realistic lighting and returns an image or a video. Call it from your configurator, in the shopper's browser, when they order or share. The picture comes back as a URL, and nothing runs on your server.

// An API key while you test. In production, use a token from your server instead:
// https://bakery3.com/docs#let-your-users-render-without-exposing-your-api-key
const bakery3 = createBakery3({ apiKey: 'bk_sk_…' });
bakery3.attach({ scene, camera, renderer });
async function renderWithBakery3(configuration: Configuration): Promise<string> {
  await sceneReady;
  fabric.color.set(configuration.fabric);
  const job = await bakery3.render({
    width: configuration.width,
    height: configuration.height,
    background: { type: 'color', color: '#ece8e1' },
  });
  const { url } = await job.result();
  return url;
}

If you need pictures with no shopper involved, such as a whole catalog of .glb files, renderBatch() takes a list of model URLs from Node and renders each one, as the catalog docs show. Render image lists every option for render(), Render video does the same for a clip, and the quickstart gets you a key.

Common questions

Can three.js run in Node.js without a browser?

Not with the modern WebGLRenderer on its own. Since three.js r163 it needs WebGL 2, and Node has no WebGL. headless-gl gives Node a WebGL 1 context and only marks its WebGL 2 support as experimental, so the dependable route is a headless browser such as Chrome driven by Playwright.

Why does my server render come back blank?

The canvas was read in a different task from the render, or before the models had loaded. Put renderer.render() and toDataURL() in the same function. Wait for the promise that loads the models and the HDRI before you render.

Do I need a GPU on the server to render three.js?

No. Without a GPU, headless Chrome draws three.js with SwiftShader, a software renderer, and the picture still comes out. It is slower, so a GPU is worth having when you render many pictures or large sizes.

Can I use Puppeteer instead of Playwright?

Yes. The page with renderConfiguration does not depend on the tool that opens it. Puppeteer also has page.goto, page.waitForFunction, and page.evaluate, so the Node side changes only in how you launch the browser.

How do I render a three.js scene larger than the screen?

Pass the size you want to renderer.setSize(width, height, false) before you render, and set the camera's aspect to match. The page is never shown, so the screen does not limit the size. The GPU's limit is gl.getParameter(gl.MAX_RENDERBUFFER_SIZE).

Can I render a video on the server?

Yes. Call the three.js page one time for each frame, move the camera or the animation one step between the calls, save every frame as a PNG and join them into a video with ffmpeg. Bakery3's renderVideo() does this in one call. It renders the whole clip with realistic lighting and returns an mp4, as Render video shows.