Skip to content

hspotted/dataverse-dev-client

@hspotted/dataverse-dev-client

⚠️ DEVELOPMENT-ONLY PACKAGE

Do not statically import this package from production-safe application code. Do not bundle it into customer production builds. Do not put secrets in this package or in Vite environment variables. See Production Bundle Safety for details.


What This Package Is

A strongly-typed TypeScript client for accessing the Microsoft Dataverse Web API from a local development machine, using delegated user authentication through MSAL Browser (public client / SPA flow).

It is designed for React/Vite SPAs that normally run inside Microsoft Dynamics 365 model-driven apps as iframe/web resources, where local development against the real Dataverse environment requires authentication.


What This Package Is Not

  • Not a production Dataverse client (use Xrm.WebApi inside Dynamics 365)
  • Not a Node.js backend client
  • Not a mock/stub library
  • Not a general-purpose OData library
  • Not a confidential client (no client secrets)

Why It Exists

When developing a React/Vite SPA that runs inside Dynamics 365, you need to test against real data. From localhost, Dynamics 365's Xrm.WebApi is unavailable. This package fills that gap using MSAL Browser delegated authentication.


Consumer Modes

Mode Implementation
local + mocks Your own mock services
local + Dataverse real ✅ This package
production inside Dynamics Xrm.WebApi

Installation

Install as a devDependency:

npm install --save-dev @hspotted/dataverse-dev-client

Required Entra ID App Registration

You need a Single-page application (SPA) registration in Microsoft Entra ID:

  1. Create an app registration (type: SPA, no client secret)
  2. Add redirect URI: http://localhost:5173
  3. Add delegated API permission: Dynamics CRM → user_impersonation
  4. Grant admin consent if required

See docs/entra-app-registration.md for complete instructions.


Environment Variables

Create .env.dataverse (add to .gitignore):

VITE_APP_RUNTIME=dataverse
VITE_DATAVERSE_URL=https://yourorg.api.crm4.dynamics.com
VITE_TENANT_ID=00000000-0000-0000-0000-000000000000
VITE_CLIENT_ID=00000000-0000-0000-0000-000000000000
VITE_REDIRECT_URI=http://localhost:5173

Create .env.production:

VITE_APP_RUNTIME=dynamics

Minimal Usage

// ✅ Correct — dynamic import guarded by DEV check
export async function createLocalDataverseServices() {
  if (!import.meta.env.DEV) {
    throw new Error(
      "Local Dataverse services can only be created in development mode.",
    );
  }

  const { createDataverseDevClient } =
    await import("@hspotted/dataverse-dev-client");

  return createDataverseDevClient({
    dataverseUrl: import.meta.env.VITE_DATAVERSE_URL,
    tenantId: import.meta.env.VITE_TENANT_ID,
    clientId: import.meta.env.VITE_CLIENT_ID,
    redirectUri: import.meta.env.VITE_REDIRECT_URI,
  });
}
// ❌ Forbidden — static import will always be bundled
import { createDataverseDevClient } from "@hspotted/dataverse-dev-client";

Repository Usage

import type { DataverseEntityDescriptor } from "@hspotted/dataverse-dev-client";

type Account = { accountid: string; name: string; emailaddress1?: string };

const AccountDescriptor: DataverseEntityDescriptor<Account> = {
  logicalName: "account",
  entitySetName: "accounts",
  primaryIdAttribute: "accountid",
  primaryNameAttribute: "name",
};

// Retrieve a single record
const account = await client.repository.retrieve(AccountDescriptor, id, {
  select: ["accountid", "name"],
});

// Retrieve multiple records
const accounts = await client.repository.retrieveMultiple(AccountDescriptor, {
  select: ["accountid", "name"],
  filter: "statecode eq 0",
  top: 50,
});

// Create a record
await client.repository.create(AccountDescriptor, { name: "Contoso" });

// Update a record
await client.repository.update(AccountDescriptor, id, {
  name: "Contoso Updated",
});

// Delete a record
await client.repository.delete(AccountDescriptor, id);

Custom API / Action Usage

// Unbound action
await client.operations.executeUnboundAction("my_CustomAction", {
  Key: "value",
});

// Bound action
await client.operations.executeBoundAction("accounts", accountId, "SendEmail");

// Unbound function
const result = await client.operations.executeUnboundFunction("WhoAmI");

// Bound function with parameters
await client.operations.executeBoundFunction(
  "accounts",
  accountId,
  "CalculateRollupField",
  {
    FieldName: "revenue",
  },
);

Metadata Usage

// Single entity definition
const definition = await client.metadata.getEntityDefinition("account");
console.log(definition.EntitySetName); // "accounts"

// All entity definitions
const all = await client.metadata.getEntityDefinitions();

// Attributes
const attrs = await client.metadata.getAttributes("account");

Diagnostics

const who = await client.diagnostics.whoAmI();
console.log("User ID:", who.UserId);

const ok = await client.diagnostics.testConnection();
if (!ok) console.warn("Could not connect to Dataverse.");

Consumer Vite Integration

Add scripts for each dev mode:

{
  "scripts": {
    "dev:mock": "vite --mode development",
    "dev:dataverse": "vite --mode dataverse",
    "build": "vite build --mode production"
  }
}

See docs/consumer-integration.md for the full service factory pattern.


Production Bundle Safety

After building your app, verify this package did not leak into production:

Select-String -Path "dist\**\*" -Pattern "@azure/msal-browser"
Select-String -Path "dist\**\*" -Pattern "login.microsoftonline.com"
Select-String -Path "dist\**\*" -Pattern "MsalDataverseAuthProvider"

If any of these match, you have a static import somewhere that needs to be changed to a dynamic import. See docs/production-bundle-safety.md.


Security Model

  • Public client (SPA) authentication only — no client secrets
  • Tokens managed exclusively by MSAL Browser — never manually stored
  • No token logging anywhere in this package
  • No Authorization header in thrown errors
  • sessionStorage cache by default (cleared when browser tab closes)
  • See SECURITY.md and docs/threat-model.md

About @azure/msal-browser as a Dependency

@azure/msal-browser is included as a regular dependency (not peerDependency) because:

  1. This package is consumed only as a devDependency — no production bundle concern.
  2. It simplifies consumer setup; consumers don't need to install MSAL separately.
  3. MSAL version compatibility is fully controlled here, preventing silent breakage.

Publishing

See docs/publishing.md.

Remove "private": true from package.json only when consciously ready to publish. Configure npm Trusted Publishing (OIDC) to avoid storing long-lived tokens.


API Reference

createDataverseDevClient(options)

Factory function. Returns { authProvider, webApi, repository, operations, metadata, diagnostics }.

DataverseRepository

CRUD operations: retrieve, retrieveMultiple, retrieveMultiplePage, create, createAndReturn, update, delete.

DataverseWebApiClient

Low-level HTTP: get, post, patch, delete, send.

DataverseOperationClient

Actions & functions: executeUnboundAction, executeBoundAction, executeUnboundFunction, executeBoundFunction.

DataverseMetadataClient

Metadata: getEntityDefinition, getEntityDefinitions, getAttributes.

DataverseDiagnostics

Diagnostics: whoAmI, testConnection.

DataverseQueryBuilder

Fluent query: .select(), .filter(), .orderBy(), .top(), .expand(), .build().


Troubleshooting

Error Cause Fix
invalid_resource Wrong Dataverse URL or scope format Check VITE_DATAVERSE_URL; ensure it resolves to the correct API host
invalid_grant Expired session or account mismatch Clear session storage and try again
AADSTS50011 Redirect URI mismatch Match VITE_REDIRECT_URI exactly in Entra ID app registration
CORS error Incorrect Dataverse URL or API path Verify the URL includes /api/data/v9.2/
user_impersonation not found Permission not added or no admin consent Add delegated permission in Entra ID
User lacks access Missing Dataverse security role Assign appropriate security role to the user in Dataverse
Popup blocked Browser blocked the login popup Set loginMode: "redirect" in options
Package in production bundle Static import used Change to dynamic import() guarded by import.meta.env.DEV
MsalDataverseAuthProvider: "tenantId" is required Missing env variable Check .env.dataverse exists and Vite mode is correct

License

MIT

About

Development-only Dataverse Web API client for local React/Vite apps using MSAL Browser delegated authentication

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors