Skip to main content

JavaScript Inference API

The ONNX Runtime JavaScript API enables inference in web browsers and Node.js applications. This guide covers both environments with real code examples.

Installation

Node.js

Web / Browser

React Native

Quick Start

Node.js

Web / Browser

ES6 Modules

InferenceSession

Creating a Session

From URL (Web):
From ArrayBuffer:
From Uint8Array:
With session options:

Session Properties

Running Inference

Basic inference:
Multiple inputs:
Request specific outputs:
With run options:

SessionOptions

Configure session behavior:

Tensor

Create and manipulate tensors: Create from typed array:
Create from regular array:
Tensor properties:
Common tensor shapes:

Execution Providers

Web Execution Providers

WebGPU (GPU acceleration in browser):
WebNN (Neural Network API):
WebAssembly (CPU):

Node.js Execution Providers

CPU:
CUDA (with onnxruntime-node-gpu):
DirectML (Windows):
CoreML (macOS):

Complete Examples

Node.js Image Classification

Web Browser Image Classification

TypeScript Example

Environment Configuration

Web Environment

Node.js Environment

Error Handling

Supported Data Types

Performance Tips

WebGPU provides the best performance in modern browsers. Always include it as the first execution provider.
SIMD provides significant speedups. Enable it with ort.env.wasm.simd = true.
Creating sessions is expensive. Create once and reuse for multiple inferences.
Reuse typed arrays for inputs when possible to reduce memory allocation overhead.
Set graphOptimizationLevel: 'all' for maximum optimization.

Next Steps

Model Optimization

Optimize models for web and Node.js

Execution Providers

Configure hardware acceleration