Blog post preview
November 26, 2026

How to easily route diagram links around nodes (and stop links from colliding)

If you’ve worked with node-based editors, you know how impractical it’s to have links going straight through nodes. Connections are impossible to follow; the diagram looks cluttered, and fixing it would be a massive undertaking.

To create a connection (link) that avoids every node in its path, the router has to know about the whole graph, not just the two nodes a link connects. It also has to recompute routes fast enough to keep up while a user drags things around.

The new @joint/router-avoid package solves this problem elegantly. It’s open source, works with both JointJS for React and vanilla JointJS, and needs only a few lines of setup. In this article, you’ll find out how it works, how to add it to your app, and how to configure it for large, production-grade diagrams.

Try the demo yourself: https://changelog.jointjs.com/gallery/router-avoid/

Why links overlap in most diagramming libraries

Most diagramming libraries route links outside of the diagram context. The link “considers” its source position and target positions and draws connections with right or orthogonal angles between them. It doesn’t know which nodes sit in the way, and it doesn’t know that another link already runs through exactly the same space.

This might not be noticeable on small, tidy diagrams, but it causes major problems in production-grade apps that rely on diagrams, such as workflow and AI pipeline builders, BPMN modelers, network topology viewers, electrical schematics, and data lineage graphs. These kinds of diagrams are dense, users rearrange them constantly, and a link that crosses a node often obscures the actual connection.

If the library, as it’s most often the case, doesn’t handle this for you, you need to write your own pathfinding over a grid, or pull in some third-party add-on, and hope it keeps up with your diagram size. Whichever you pick, you end up maintaining complex routing code that has nothing to do with your core product.

Meet @joint/router-avoid

The @joint/router-avoid library routes JointJS links with libavoid, a mature C++ library for obstacle-avoiding orthogonal connector routing, compiled to WebAssembly via libavoid-js. That gives you a well-established routing engine running in the browser at near-native speed.

Instead of computing one link at a time, the package maintains a single incremental router for the whole graph, where all elements are obstacles, and all links are connectors. In practice, this means that:

  • Links route around every element in their path, including elements they aren’t connected to.
  • Links that share a corridor are spaced apart instead of being drawn on top of each other.
  • Rerouting is incremental, so moving a node reroutes only the links it affects.
  • Routing works perfectly with ports, so a link to a port on a node’s left side approaches it from the left.
  • You can configure the package to run in a Web Worker to keep the UI responsive on massive diagrams.

Routes are written straight onto each link’s vertices and anchors. They’re stored in the graph JSON like any other link attribute, so a saved diagram keeps its routes even where the router isn’t loaded, such as in a read-only viewer.

The package is open source and requires JointJS 4.3 or newer.

Adding obstacle-avoiding routing to your app

The router-avoid package is available on NPM, so you can easily add it to your app:

npm add @joint/router-avoid

There’s one extra setup step. The routing engine ships as a libavoid.wasm binary, and it has to be served next to your bundle. Copy node_modules/libavoid-js/dist/libavoid.wasm into your output directory with your bundler’s copy plugin (for example, vite-plugin-static-copy or copy-webpack-plugin), or point the router at it with the libavoidFilePath option.

const avoidRouter = await initAvoidRouter(graph, {
   libavoidFilePath: '/assets/libavoid.wasm'
});

JointJS for React

With JointJS for React, you need to wrap the setup in a hook and call it from a component inside your GraphProvider. The useGraph() hook hands you the underlying dia.Graph, and the useEffect starts the router on mount and tears it down on unmount:

import { useEffect } from 'react';
import { GraphProvider, Paper, useGraph } from '@joint/react';
import { initAvoidRouter, type RouterService } from '@joint/router-avoid';

function useAvoidRouter() {
   const { graph } = useGraph();

   useEffect(() => {
       let router: RouterService | null = null;
       let cancelled = false;

       async function setup() {
           const created = await initAvoidRouter(graph, {
               shapeBufferDistance: 20,
               idealNudgingDistance: 10
           });
           if (cancelled) {
               created.destroy();
               return;
           }
           router = created;
           router.start();
       }

       setup();

       return () => {
           cancelled = true;
           router?.destroy();
       };
   }, [graph]);
}

function Diagram() {
   useAvoidRouter();
   return <Paper style={{ width: '100%', height: 600 }} renderElement={renderNode} />;
}

export function App() {
   return (
       <GraphProvider initialCells={initialCells}>
           <Diagram />
       </GraphProvider>
   );
}

The flag cancelled covers React’s Strict Mode, which mounts effects twice in development, so you never end up with two routers fighting over the same links.

JointJS

import { dia, shapes } from '@joint/core';
import { initAvoidRouter } from '@joint/router-avoid';

const graph = new dia.Graph({}, { cellNamespace: shapes });
const paper = new dia.Paper({
   el: document.getElementById('paper'),
   model: graph,
   cellViewNamespace: shapes
});

const avoidRouter = await initAvoidRouter(graph, {
   shapeBufferDistance: 20,
   idealNudgingDistance: 10
});

avoidRouter.start();

initAvoidRouter() loads the libavoid WebAssembly module and registers the graph’s content, and start() attaches the listener that keeps everything routed as cells are added, moved, resized, and reconnected.

You also don’t need to set a router attribute on links; they are routed automatically:

graph.addCell(new shapes.standard.Link({
   source: { id: a.id },
   target: { id: b.id }
}));

Routes are computed asynchronously, and each link gets a temporary right-angle route so nothing renders in a broken state; libavoid’s route replaces it as soon as it’s ready.

Ports: links that enter from the correct side

In workflow builders and schematics, positions of links on nodes carry real meaning. Inputs come in on one side, outputs leave from the other, and a link that has an input on the right side looks like a bug.

This is where many routing plugins and add-ons fall short. Pathfinding-based "smart link/edge" packages typically find a path between two nodes that avoids the nodes in the way, but they don't know which side of the node the link should enter from. The route clears every obstacle and still arrives at an input from above, or doubles back on itself at the last moment. To fix that, you’d have to write the direction logic yourself, for all ports.

With the avoid router, you don't have to set anything up. Each port becomes a pin when its element is registered, and the router reads which side of the node the port sits on, so a link to a port on the left edge always arrives from the left. The side comes from the port's actual position rather than its group name, so it works with any port layout. Elements without ports get a single pin in the center that accepts links from any direction.

Note that pins are built when an element is first registered, so if your app adds ports to an existing node at runtime, call start() again to rebuild them.

Tuning the routes

Two options control how routes look:

Option What it does Default
shapeBufferDistance Space kept between links and the sides of elements. Larger values keep routes further from nodes. 10
idealNudgingDistance Space between parallel links that share a corridor. Larger values spread them out more. 5

Deciding what counts as an obstacle

By default, every element in a diagram is an obstacle, and every link is routed. The real-world apps usually need exceptions; for example, links don’t have to avoid a sticky note, a background lane, or a legend. The trackElement option lets links pass straight through those:

const avoidRouter = await initAvoidRouter(graph, {
   trackElement: ({ element }) => element.get('type') !== 'app.Note'
});

The trackLink option handles the same challenge for links. If you return false, the link will keep its own router and connector attributes, so you can mix avoid-route links with ones that use a built-in router:

const avoidRouter = await initAvoidRouter(graph, {
   trackLink: ({ link }) => !link.get('manual')
});

Built for large diagrams

The @joint/router-avoid package is built for production-grade diagrams, optimized for performance, and offers additional options to help you get the most out of your apps.

Move routing off the main thread

You can easily move the routing off the main thread to a Web Worker by setting the worker: true option:

const avoidRouter = await initAvoidRouter(graph, {
   worker: true
});

avoidRouter.start();

The API and events stay exactly the same. The Worker batches changes in a short quiet window (100 ms by default), so a drag gesture that fires a change on every pointer move will produce one routing pass instead of dozens. A longer debounceTime batches changes more aggressively, while debounceTime: 0 routes every change immediately.

With the Vite dev server, exclude the package from dependency pre-bundling, as otherwise esbuild will inline it and break the worker script reference: optimizeDeps: { exclude: ['@joint/router-avoid'] }. The Angular CLI has a known limitation that it can’t load the worker script from a dependency, so you will need to use the main-thread mode there. Worker mode also requires the ESM build, not UMD.

Route once for read-only diagrams and exports

For read-only diagrams like dashboards, reports, generated diagrams, or exports, you need routes computed only once, and running a listener is not necessary. That’s precisely what routeAll() method handles:

const avoidRouter = await initAvoidRouter(graph);

const { status } = await avoidRouter.routeAll();
if (status === 'cancelled') return; // links are still on interim routes

await save(graph.toJSON());

The status resolves to done if every route was applied, or to cancelled when the process is interrupted.

Route containers independently

The routeSubgraph() method routes only the cells you pass in. That way you can route parts of a diagram independently. You can use this for grouped layouts like subprocesses, clusters, or swimlanes. Simply route each container’s internal links around its own children, then route the links between containers with each container as a single obstacle:

// Each container's own content, in isolation.
await avoidRouter.routeSubgraph(containerA.getEmbeddedCells());
await avoidRouter.routeSubgraph(containerB.getEmbeddedCells());

// Then the links between the containers, treating each as one box.
await avoidRouter.routeSubgraph([containerA, containerB, ...containerLinks]);

Note that this doesn’t attach an event listener, so nothing will be rerouted after an element is moved, so you’ll need to make the paper read-only, or rerun the passes after a change.

The details that matter in production

To use a router in a production-grade application, you might need info on its current state, a way to handle links it can’t route, and more.

Events you can build UI on

The service emits events for each routing cycle. For every link:routing event, you’ll get exactly one follow-up event, link:routed or link:routing:cancelled. The idle event fires when the entire graph has finished routing, making it a good time to handle actions like fitting the paper to its content or starting an export:

avoidRouter.on('idle', () => {
   paper.fitToContent({ useModelGeometry: true, padding: 20 });
});

Sensible fallbacks

Some links can’t be routed by libavoid, such as a link whose end is being dragged across blank paper. Instead of leaving it broken, the router applies a built-in right-angle route and tells you why through link:routed, with a reason as unconnected, unsupported, or untracked. If you’d rather handle those links yourself, the interceptUnroutableLink option of the initAvoidRouter lets you claim the link, skipping the built-in rightAngle fallback route.

Keep routing out of undo history

When a user is dragging an element, the router may update a link many times, and if every update was saved, undoing would take dozens of steps. You can use setRouteAttributes to control how routes are saved and keep in-between routing updates out of the undo history:

const avoidRouter = await initAvoidRouter(graph, {
   setRouteAttributes: ({ link, attributes, routing }) => {
       // `routing` is true while libavoid is still working on this link.
       link.set(attributes, { silentUndo: routing });
   }
});

With undo and redo in JointJS+, this means that the intermediate routes computed during a drag will not be in the history, so the undo stack will only keep the relevant user edits. Without setRouteAttributes, the router will write routes itself and tag each write with an option flag (avoidRouter by default, available as avoidRouter.changeFlag), so your own change listeners can tell routed updates from user edits.

When to use it, and when built-in routers are enough

JointJS also ships per-link routers like manhattan and rightAngle, and they’re still the right choice in some cases. Here’s a simple  framework you can use to pick:

Use @joint/router-avoid Use a built-in router when
Links share corridors. Parallel links are spaced apart, so every link stays easy to follow. Most links need their own routing rules. You keep full per-link control over the router and its options.
Nodes are moved around a lot. Links route around every node in their path, and each move reroutes only the links it affects, so the diagram stays tidy as it changes. Users draw their own waypoints. Hand-placed vertices stay exactly where the user put them.
Graphs are large or edited heavily. Routing can run in a Web Worker, so dragging stays smooth. You don’t want extra assets. There's no WebAssembly file (about 475 KB, or 170 KB gzipped) to copy and serve.

You don’t have to choose one for the whole app either. With trackLink, a single diagram can route most links with libavoid and leave a few on a built-in router.

Drawing boxes and lines is the easy part of a diagramming app. Routing, layout, validation, and interaction take most of the development time, and in JointJS they’re features you configure rather than code you write and maintain.

Getting started

The fastest way you can test it out and see the difference yourself is to add the router to a diagram you already have. Install the package, serve libavoid.wasm, and initialize the router on your diagram:

npm add @joint/router-avoid

The standalone link routing guide has interactive examples for every feature covered here, from spacing and ports to Worker routing and per-container passes. If you work with an AI coding agent, set up the JointJS MCP Server so your agent has direct access to up-to-date JointJS docs, including this package.

Happy diagramming!

‍

FAQ

Authors
Blog post author
Zoran Jambor
Developer Advocate at JointJS. Founder of CSS Weekly. Interested in developer tooling and workflows.
No items found.
Stay in the loop

Speed up your development with a powerful library