⚠️ DEVELOPMENT-ONLY PACKAGEDo 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.
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.
- Not a production Dataverse client (use
Xrm.WebApiinside 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)
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.
| Mode | Implementation |
|---|---|
local + mocks |
Your own mock services |
local + Dataverse real |
✅ This package |
production inside Dynamics |
Xrm.WebApi |
Install as a devDependency:
npm install --save-dev @hspotted/dataverse-dev-clientYou need a Single-page application (SPA) registration in Microsoft Entra ID:
- Create an app registration (type: SPA, no client secret)
- Add redirect URI:
http://localhost:5173 - Add delegated API permission: Dynamics CRM → user_impersonation
- Grant admin consent if required
See docs/entra-app-registration.md for complete instructions.
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:5173Create .env.production:
VITE_APP_RUNTIME=dynamics// ✅ 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";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);// 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",
},
);// 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");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.");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.
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.
- 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
sessionStoragecache by default (cleared when browser tab closes)- See SECURITY.md and docs/threat-model.md
@azure/msal-browser is included as a regular dependency (not peerDependency) because:
- This package is consumed only as a
devDependency— no production bundle concern. - It simplifies consumer setup; consumers don't need to install MSAL separately.
- MSAL version compatibility is fully controlled here, preventing silent breakage.
See docs/publishing.md.
Remove
"private": truefrompackage.jsononly when consciously ready to publish. Configure npm Trusted Publishing (OIDC) to avoid storing long-lived tokens.
Factory function. Returns { authProvider, webApi, repository, operations, metadata, diagnostics }.
CRUD operations: retrieve, retrieveMultiple, retrieveMultiplePage, create, createAndReturn, update, delete.
Low-level HTTP: get, post, patch, delete, send.
Actions & functions: executeUnboundAction, executeBoundAction, executeUnboundFunction, executeBoundFunction.
Metadata: getEntityDefinition, getEntityDefinitions, getAttributes.
Diagnostics: whoAmI, testConnection.
Fluent query: .select(), .filter(), .orderBy(), .top(), .expand(), .build().
| 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 |
MIT