This guide will help you get up and running with the iTwins Client library, from installation through your first API calls.
- Prerequisites
- Installation
- Authentication Setup
- Your First iTwin Query
- Environment Configuration
- Development Setup
- Testing Setup
- Next Steps
Before getting started, ensure you have:
- Node.js 18+ and a package manager (npm, yarn, or pnpm)
- TypeScript 4.5+ (if using TypeScript)
- Valid iTwin Platform credentials - see iTwin Developer Portal
Install the iTwins Client:
# Using npm
npm install @itwin/itwins-client
# Using yarn
yarn add @itwin/itwins-client
# Using pnpm
pnpm add @itwin/itwins-clientThe iTwins Client requires an access token string. You'll need to set up authentication with the iTwin Platform:
- Register your application at the iTwin Developer Portal
- Get your client credentials (client ID, client secret, redirect URIs)
- Implement authentication flow using one of the iTwin.js authentication packages
import { TestUtility } from "@itwin/oidc-signin-tool";
// For testing/development - use appropriate auth for production
const userCredentials = {
email: "your-test-email@example.com",
password: "your-password",
};
const accessToken: string = await TestUtility.getAccessToken(userCredentials);Once you have authentication set up, making your first API call is straightforward:
import { ITwinsClient } from "@itwin/itwins-client";
import type { BentleyAPIResponse, MultiITwinMinimalResponse } from "@itwin/itwins-client";
async function getMyITwins(): Promise<void> {
// Initialize the client
const client = new ITwinsClient();
// Get your access token (implementation depends on your auth setup)
const accessToken: string = await getAccessToken(); // Your auth implementation
// Make your first API call
const response: BentleyAPIResponse<MultiITwinMinimalResponse> =
await client.getITwins(accessToken, {
subClass: "Project",
top: 10
});
// Check for errors
if (response.error) {
console.error("API Error:", response.error.message);
return;
}
// Success! Use the data
const iTwins = response.data!.iTwins;
console.log(`Found ${iTwins.length} iTwins:`);
iTwins.forEach(itwin => {
console.log(`- ${itwin.displayName} (${itwin.id})`);
});
}
// Run your first query
getMyITwins().catch(console.error);The iTwins Client supports different deployment environments (development, QA, production):
// Development environment
globalThis.IMJS_URL_PREFIX = "dev-";
// QA environment
globalThis.IMJS_URL_PREFIX = "qa-";
// Production (default)
globalThis.IMJS_URL_PREFIX = undefined;
// Now all client instances will use the configured environment
const client = new ITwinsClient();// Custom base URL for specific deployments
const client = new ITwinsClient("https://your-custom-api.bentley.com/itwins");// Bridge from process.env in Node.js applications
globalThis.IMJS_URL_PREFIX = process.env.IMJS_URL_PREFIX;The iTwins Client supports configurable redirect limits for federated architecture scenarios where API endpoints may redirect to different services:
// Set maximum redirect limit (default is 5)
globalThis.IMJS_MAX_REDIRECTS = 10;
// Or use environment variable
globalThis.IMJS_MAX_REDIRECTS = parseInt(process.env.IMJS_MAX_REDIRECTS || "5");
// Create client with custom max redirects via constructor
const client = new ITwinsClient(10);Why Redirects? In federated architecture, the iTwin Platform may redirect requests to specialized services (e.g., repository services on different domains). The client automatically follows these redirects while enforcing security validation.
Security Notes:
- Only HTTPS redirects to trusted Bentley domains (
*.api.bentley.com) are allowed - Redirect loop protection prevents infinite redirect chains
- Default limit of 5 redirects is suitable for most scenarios
- Increase only if you encounter legitimate multi-hop redirect scenarios
Error Handling:
- 508 Loop Detected: Redirect limit exceeded, possible redirect loop
- 502 Bad Gateway: Invalid redirect (missing Location header or untrusted domain)
- 403 Forbidden: Redirects not allowed for this endpoint
const response = await client.getRepositoryResourceByUri(accessToken, iTwinId, resourceUri);
if (response.error) {
if (response.status === 508) {
console.error("Too many redirects - possible redirect loop");
} else if (response.status === 502) {
console.error("Invalid redirect:", response.error.message);
}
}If you're contributing to the iTwins Client or building from source:
git clone https://github.com/iTwin/itwins-client.git
cd itwins-client
pnpm install
pnpm build# Build the library
pnpm build
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Run linting
pnpm lint
# Build API documentation
pnpm docs
# Clean build artifacts
pnpm cleanFor integration testing, you'll need to configure test credentials and environments.
az login # Authenticate with Azure CLI
./setup-env.ps1 # Set up .env file with required variables
Create a .env file in the root directory with the following variables:
# Environment Configuration
IMJS_URL_PREFIX="" # Environment must be empty
# OIDC Configuration (required for authentication)
IMJS_OIDC_BROWSER_TEST_CLIENT_ID="spa-your-client-id-here"
IMJS_OIDC_BROWSER_TEST_REDIRECT_URI="http://localhost:3000/signin-callback"
IMJS_OIDC_BROWSER_TEST_SCOPES="itwin-platform"
IMJS_OIDC_AUTHING_BROWSER_TEST_SCOPES="itwin-platform"
# Test User Authentication (for testing only)
IMJS_ITWIN_TEST_USER="your-test-email@example.com"
IMJS_ITWIN_TEST_USER_PASSWORD="your-test-password"
# Test Data (required for integration tests)
IMJS_TEST_PROJECT_ID="your-test-project-itwin-id"
IMJS_TEST_ASSET_ID="your-test-asset-itwin-id"Your test user must have appropriate permissions:
- Project Administrator or ITwin Owner role on test iTwins
- Connect Services Admin role for creating iTwins (if testing CRUD operations)
- Access to both Project and Asset level iTwins for comprehensive testing
# Install dependencies
pnpm install
# Build the project
pnpm build
# Run integration tests
pnpm testThe browser E2E tests validate redirect behavior using real browser fetch implementations (Chromium, Firefox, WebKit).
# Run browser E2E tests
pnpm test:e2e
# Run with Playwright UI
pnpm test:e2e:uiFor more details about testing, see the test documentation and existing test files in src/test/integration/.
Now that you have the basics working, explore these areas:
- Complete Examples - Comprehensive usage examples
- Migration Guide - If upgrading from v1.x
- Migration Guide - If upgrading from v2.x
- iTwin Developer Portal - Platform documentation
- iTwins API Reference - REST API details
- iTwin.js Platform - Complete iTwin ecosystem
- GitHub Repository - Source code and issues
- Verify your access token is valid and not expired
- Check that your application has the correct scopes
- Ensure you're using the right environment (dev/qa/prod)
- Verify iTwin IDs are correct and accessible to your user
- Check that you have permissions to access the requested resources
- Ensure you're targeting the correct environment
- Review the
error.detailsarray for specific validation failures - Check required fields and data types in your requests
- Verify enum values match the expected API constants
- Check your internet connection and firewall settings
- Verify the API endpoint URLs are accessible
- Consider implementing retry logic for transient failures
- Check the GitHub Issues for known problems
- Review the Examples for working code patterns
- See the Contributing Guide for support resources
- Visit the iTwin Developer Portal for platform support
Ready to build amazing iTwin applications? Start with the examples