1Prereqs

Node.js LTS, npm, VS Code, Git, premium Power Apps license.

2Scaffold

npx degit github:microsoft/PowerAppsCodeApps/templates/vite my-app

3Init & auth

npm i -g @microsoft/power-apps-cli @microsoft/power-apps then pa app init (auto sign-in).

4Add Data

pa app add data-source --connector <id> --connection-id <id>

5Develop

pa app run starts the local host (tunnel + dev server) in one command. Hot reload, console, types.

6Build

npm run build → static dist/ bundle.

7Publish

pa app push uploads & registers app.

8Run & Share

Open in Power Apps, or pa app share for users/service principals.

overview What are Code Apps & when to choose them Source: learn.microsoft.com/power-apps/developer/code-apps/overview
Code Apps let pro-developers build Power Platform apps using any modern web stack (React/Vue/Angular/Svelte) authored in VS Code, packaged with Vite, and run inside the Power Apps player. Apps inherit Power Platform identity (Entra ID), connectors, governance (DLP, tenant policies), environments and sharing. Choose Code Apps when you need: complex UI (charts, maps, custom layouts), heavy client logic, npm libraries, true unit testing, Git workflows, or pixel-perfect design that Canvas can't easily match. Choose Canvas instead when makers need to compose with formulas. Choose Model-driven when Dataverse + standard pages are enough.
prereqs Install & Setup
Node.jsCurrent LTS — Node 20 reached end-of-life Apr 30, 2026; use 22 (maintenance) or 24 (active) — node --version
npmShips with Node — npm --version
VS CodeLatest stable build (code-insiders also fine)
Power Apps CLInpm install -g @microsoft/power-apps-cli @microsoft/power-apps — installs both the pa CLI and the client library
gitFor source control / sharing samples
LicensePower Apps Premium per-user OR Per-app plan (end users)
Tenant FlagAdmin must enable Code Apps per environment: Admin center → Environments → Settings → Product → Features
EnvironmentManaged environment recommended (DLP, governance)
⚠ If pa is unrecognized: npm install -g @microsoft/power-apps-cli. This replaced the old power-apps binary — see the pa CLI card.
pac code CLI Commands Legacy
initInitialize a Code app in the current Vite project
listList all code apps available in current environment
pushBuild & publish a new version of the app to the environment
runStart the local Power tunnel so the dev server can use connections
add-data-sourceWire a connector + connection-reference into the project & generate types
delete-data-sourceRemove a data source from the app
list-connection-referencesShow connection references in the current environment/solution
list-datasetsList datasets accessible via the provided connector
list-tablesList tables accessible via a connector/dataset
list-sql-stored-proceduresEnumerate stored procedures for a SQL connection/dataset
⚠ pac code still works but is no longer the recommended path as of the Feb 2026 GA — the pa CLI (next card) is now primary and gets new features first (refresh-data-source, share, solution list). Requires an active pac auth profile.
pa Power Apps CLI GA @microsoft/power-apps-cli v1.0+ · bin: pa
npm installnpm i -g @microsoft/power-apps-cli @microsoft/power-apps — installs the pa CLI and the client library (two packages now)
pa app initInitialize the code app & power.config.json — interactive, or pass --display-name / --environment-id
pa auth login / status / switch / logoutSign in, check active account, switch accounts, sign out — separate auth store from pac auth
pa connection createCreate an SSO-eligible connection without the maker portal — --connector <id> [--display-name <n>] [--json]
pa connector list / pa connection listList connectors in the environment / list your connections — [--search <text>] [--json]
pa solution listNew List Dataverse solutions (Id, name, version) — grab the solution ID for connection-ref data sources
pa app find-dataverse-api / add-dataverse-apiSearch, then add a Dataverse action/function as a typed service — --search "WhoAmI" / --api-name WhoAmI
pa app list-flows / add-flow / remove-flowList, add, or remove a solution-aware Power Automate flow (PowerApps-trigger only) — --flow-id/--flow-name
pa app refresh data-sourceNew Regenerate a data source's model/service files after a schema change — --name <dataSourceName>. No more delete-then-readd.
pa app shareNew Share a published app with users or a service principal — --principal <email/objectId> --access play|edit
pa app pushBuild & publish a new version — add --non-interactive for CI/CD via service principal
pa app runStart the local host (tunnel + dev server) in one command — opens a Local Play URL
pa telemetry enable/disable/statusManage CLI telemetry collection
⚠ Breaking change (GA, ~early 2026): the old power-apps binary is removed. Old flags renamed: -a/--api-id→--connector, -t→--table, -sp→--procedure, -n→--name. Commands moved from flat verbs to noun-verb groups: pa app, pa auth, pa connection, pa connector, pa solution, pa telemetry.
vs code Workflow, Extensions & Terminal Recipes
Recommended extensionsPower Platform Tools, ES7+ React snippets, ESLint, Prettier, GitLens, Tailwind CSS IntelliSense (if used), Error Lens
Open projectcode . in the project folder; trust workspace
Integrated terminalCtrl + ` opens PowerShell — run all pac & npm commands here
Sign in for the pa CLIpa auth login (optionally --account user@contoso.com)  → confirms via browser. This is a separate auth store from pac auth
Sign in for pac (admin/solution ops)pac auth create --environment "https://<org>.crm.dynamics.com"
Switch active pa accountpa auth switch --account user@contoso.com · check with pa auth status
Run app locallypa app run — one command starts the tunnel + dev server; opens a Local Play URL
Debug client codeUse VS Code's built-in JavaScript Debugger against the Local Play URL
Type-safe data callsAuto-generated TypeScript clients live under src/Services/ & src/Models/
Refresh data clientspa app refresh data-source --name <dataSourceName> any time the connector schema changes
Lint & formatnpm run lint · npm run format (add Prettier if not preset)
Push to environmentpa app push — first push creates app, subsequent pushes version it. Add --non-interactive for CI/CD
anatomy Project Structure
// Typical Vite + React Code App my-code-app/ ├─ power.config.json // app id, env, datasources ├─ package.json ├─ vite.config.ts // HMR + base path ├─ tsconfig.json ├─ index.html ├─ .env.local // local secrets, NEVER push └─ src/ ├─ main.tsx // React bootstrap ├─ App.tsx ├─ PowerProvider.tsx// optional: setConfig() for telemetry ├─ Models/ // generated DTOs ├─ Services/ // generated clients └─ components/ // your UI
📁 power.config.json is the single source of truth for environment + data sources. Commit it. Never commit .env.local.
auth Identity & Context (no init required since SDK v1.0)
IdentityApps run as the signed-in user via Microsoft Entra ID — no token plumbing needed
initialize() removed BreakingSDK v1.0+ (GA) removed initialize() entirely. Don't import it, don't gate rendering on it — make data calls and read context directly, from first render
Context entry-pointimport { getContext } from "@microsoft/power-apps/app";
User contextconst { user } = await getContext(); — fullName, objectId, tenantId, userPrincipalName
App contextconst { app } = await getContext(); — appId, environmentId, dataverseOrgUrl, appUrl, queryParams
Connection authAll connector calls use the connection-reference's stored credentials (no client secrets in code)
Sign-in UXPower Apps host shell handles SSO at runtime; local dev uses pa auth login + pa app run tunnel for connection brokering
Roles & sharingUse Power Apps sharing UI, or script it with pa app share --principal <email> --access play|edit; honor environment security roles for Dataverse
// src/PowerProvider.tsx — optional: only needed if you want setConfig() telemetry import { setConfig } from "@microsoft/power-apps/app"; import { useEffect } from "react"; export function PowerProvider({ children }: { children: React.ReactNode }) { useEffect(() => { // Opt in to logging session/network metrics to your own telemetry sink setConfig({ logger: { logMetric: sendToAppInsights } }); }, []); return <>{children}</>; // no loading gate needed — render immediately }
data sources Connectors You Can Use
DataverseTables, choices, lookups, FetchXML, $batch, Web API
SharePointLists, document libraries, list items
SQL Server (Azure)Tables, views, stored procedures (incl. params)
Office 365 UsersProfile, manager, photo
Office 365 OutlookMail, calendar, contacts
OneDriveFiles, folders
Microsoft TeamsChannels, messages, meetings
Power Automate flowsSolution-aware flows with a PowerApps trigger — pa CLI only, not in pac code (pa app add flow)
Dataverse actions/functionse.g. WhoAmI, AddToQueue — pa CLI only, not in pac code (pa app add dataverse-api)
Azure DevOpsWork items, repos, pipelines
MCS CopilotInvoke Copilot Studio agents
Custom ConnectorAny OpenAPI 2.0 connector you've built
1,500+ certifiedAnything in the Power Platform connector library
Excel Online Not yetExcel Online (Business) & Excel Online (OneDrive) connectors aren't supported by code apps yet
🔌 Wire a data source to a connection reference instead of a raw connection ID for environment-portable ALM: pa app add data-source --connector <id> --connection-ref <refLogicalName> --solution-id <id> — get the solution ID quickly with pa solution list.
add-data-source Wire a Connector — Step by Step
1. List connectionspa connection list  — get the Connection ID for each connection; pa connector list for connector IDs
2. List datasets (if any)pa connection list-datasets --connector <id> --connection-id <id>
3. List tables / sprocspa connection list-tables --connector <id> --connection-id <id> --dataset <ds> · list-procedures --connection-id <id> --dataset <ds>
4. Add it (direct)pa app add data-source --connector <id> --connection-id <id> --dataset <ds> --table <table>
4b. Add it (connection ref)pa app add data-source --connector <id> --connection-ref <refName> --solution-id <id> — environment-portable, recommended for ALM. Get the solution ID with pa solution list
5. OutputTabular (SQL/SharePoint) → src/Services/ + src/Models/. Nontabular (Office 365, Teams) → src/generated/services/ + src/generated/models/
6. Use itImport the service and call typed methods — no boilerplate auth code
7. Schema changed?New pa app refresh data-source --name <dataSourceName> — no more delete-then-readd
// Example: add Dataverse "accounts" table (direct connection) pa app add data-source \ --connector "shared_commondataservicepowerapps" \ --connection-id "<connection-id>" \ --table "accounts" // Example: add Dataverse table directly by connector name (no connection needed) pa app add data-source --connector dataverse --table accounts // Example: add SQL stored procedure pa app add data-source \ --connector "shared_sql" \ --connection-id "<connection-id>" \ --dataset "server.database.windows.net,mydb" \ --procedure "[dbo].[GetTopOrders]" // Example: add via connection reference (portable across Dev/Test/Prod) pa app add data-source \ --connector "shared_sharepointonline" \ --connection-ref "new_sharepointconnref" \ --solution-id "<solution-id>" // Refresh after a schema change — regenerates model/service files in place pa app refresh data-source --name "accounts"
SDK @microsoft/power-apps — API Cheatsheet
getContext()Since v1.0, no init needed. Returns { app, user, host } — replaces the old initialize()/getCurrentUser()/getEnvironment() trio
setConfig(options)Opt in to a custom logger (logMetric) for session/network telemetry
navigate(url, options)Programmatic navigation that respects the Power Apps shell
showAlert(message)Display a host-styled alert/notification
context.app.*appId, environmentId, dataverseOrgUrl, appUrl, queryParams
<Connector>Service.getAll()List records — typed
<Connector>Service.getById(id)Fetch a single record
<Connector>Service.create(record)Insert with strongly-typed DTO
<Connector>Service.update(id, patch)Partial update
<Connector>Service.delete(id)Delete by primary key
<Connector>Service.query(opts)Typed OData-style query: filter, top, orderBy
invokeAction(name, params)Call a connector custom action / stored proc
uploadFile(file)Stream blob/file content (SharePoint, OneDrive)
// Typed Dataverse call — fully generated import { AccountsService } from "./Services/AccountsService"; import type { Account } from "./Models/Account"; const top5: Account[] = await AccountsService.query({ top: 5, orderBy: "revenue desc", filter: "statecode eq 0", });
dev Local Run & Debug
💡 If a connector returns 401/403 locally, re-run pa auth login and restart pa app run.
deploy Build & Publish
  1. Ensure pa auth status shows the right account/environment.
  2. npm run build — Vite emits dist/.
  3. pa app push — uploads the bundle & registers a new app version. Add --solution-id <id> to add it to a solution on push.
  4. App appears in Power Apps maker portal under Apps → Code apps.
  5. Share like any Power App via the maker portal, or script it: pa app share --principal <email> --access play.
  6. For ALM, add the code app to a solution and use pipelines/PAC build tools.
  7. CI/CD: share edit access to a service principal once, then run pa app push --non-interactive from the pipeline (set PA_CLI_USE_SP_AUTH=true + client ID/secret/tenant env vars).
  8. Subsequent pa app push = new published version (auto-bumped).
🚀 First push prompts for app display name & description. Re-running push updates the existing app — no second prompt. A service principal can publish updates but can't run the first pa app init/push — a maker account creates the app once, then shares it.
power.config.json The Manifest That Glues It Together
// Truncated example — generated & updated by `pa app` commands { "version": "1.0", "appId": "00000000-0000-0000-0000-000000000000", "appName": "InventoryHub", "environment": { "id": "<environment-id>", "url": "https://orgXYZ.crm.dynamics.com" }, "dataSources": [ { "name": "accounts", "connector": "shared_commondataservicepowerapps", "connectionReferenceId": "<conn-ref-id>", "table": "accounts" } ], "runtime": { "sdkVersion": "1.3.1" } }
Commit itYes — required for teammates & CI builds
Hand-edit?Avoid; use pa app add/remove/refresh data-source to keep types in sync
Multi-envUse solution + connection references (--connection-ref/--solution-id) so the same code moves across Dev/Test/Prod without edits
SecretsNever store secrets here — use .env.local + connector auth
ALM Solutions, Pipelines, Source
limits Known Limitations GA
governance Managed Platform Capability Support
Sharing limitsCode apps follow canvas app sharing limits
DLP enforcementData Loss Prevention policy enforced at app launch
App QuarantineAdmins can quarantine a code app like any other app
Conditional AccessCan be applied per individual app on a managed environment
Consent dialogEnd users see a fine-grained connector permission consent dialog; admins can suppress it (incl. custom OAuth connectors)
Tenant isolationRespected the same as other Power Platform apps
Azure B2B guestsGuests can access shared code apps cross-tenant, same as canvas apps
Health metricsOperational health available in both admin center & maker portal
tips Patterns & Pro-Moves
State managementStart with React Context + hooks; reach for Zustand or Redux Toolkit only when state truly is global & complex.
UI libraryFluent UI v9 integrates cleanly with Power Apps look-and-feel; shadcn/ui & MUI also work.
RoutingUse react-router-dom with HashRouter — avoids server config inside the Power Apps shell.
Formsreact-hook-form + Zod for typed validation; pair with Fluent inputs.
Tables / gridsTanStack Table for headless control; AG Grid Community if you need rich grids.
ChartsRecharts or Apache ECharts; both tree-shake well in Vite.
Icons@fluentui/react-icons matches host shell.
Loading UXSuspense + skeleton screens; show a banner while initialize() resolves.
Error boundaryWrap the app in a single ErrorBoundary that surfaces showAlert.
TelemetryUse Application Insights JS SDK; instrument route changes & service calls.
TestingVitest + React Testing Library; mock services from src/Services/.
AccessibilityTarget WCAG 2.2 AA; Fluent UI components are accessible by default.
Localizationi18next + react-i18next work out-of-the-box.
PerformanceCode-split with dynamic import(); pre-fetch heavy routes on hover.
Env switchingTwo accounts — DEV & UAT; pa auth switch --account <user> before pa app push.
Multiple data sourcesRerun pa app add data-source per connector; generated services tree-shake away unused calls.
snippets Copy-Paste Recipes
// 1. Bootstrap App.tsx with PowerProvider import { PowerProvider } from "./PowerProvider"; import { AppShell } from "./AppShell"; export default function App() { return ( <PowerProvider> <AppShell /> </PowerProvider> ); } // 2. Fetch records + loading + error states import { useEffect, useState } from "react"; import { AccountsService } from "./Services/AccountsService"; import type { Account } from "./Models/Account"; export function AccountList() { const [rows, setRows] = useState<Account[]>([]); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(true); useEffect(() => { AccountsService.query({ top: 50, orderBy: "name asc" }) .then(setRows) .catch(e => setError(e.message)) .finally(() => setBusy(false)); }, []); if (busy) return <p>Loading…</p>; if (error) return <p>{error}</p>; return <ul>{rows.map(r => <li key={r.id}>{r.name}</li>)}</ul>; } // 3. Create with form submit async function addAccount(name: string, revenue: number) { const created = await AccountsService.create({ name, revenue }); return created.id; } // 4. Call a SQL stored procedure import { SqlActions } from "./Services/SqlActions"; const result = await SqlActions.getTopOrders({ top: 10 }); // 5. Show host alert + safe nav import { showAlert, navigate } from "@microsoft/power-apps/app"; await showAlert("Saved successfully"); navigate("/orders"); // 6. vite.config.ts — relative base required for Power Apps host import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], base: "./", // ← critical build: { outDir: "dist", sourcemap: true }, });
troubleshoot Common Errors & Fixes
"pa: command not found"npm install -g @microsoft/power-apps-cli. The old power-apps binary was removed at GA.
401 on connector calls (local)Tunnel auth expired. Stop pa app run, run pa auth login, restart.
Blank page after pushForgot base: "./" in vite.config.ts. Rebuild and push.
"PowerSDK undefined" / data calls fail on loadSDK v1.0+ needs no init — if you still have an initialize() import or a loading gate from an old project, remove it; call getContext()/services directly.
Types out of syncpa app refresh data-source --name <name> for that data source (no more delete+re-add).
"Connection reference not found"You're on the wrong env. pa auth status → switch with pa auth switch --account <user>.
"App not visible in maker portal"Push completed but you filtered Code apps off. Maker → Apps → filter "Code apps".
Slow first load in productionBundle too big. Run vite build --report, code-split heavy routes.
CORS errors locallyAlways call connectors through generated services — never raw fetch to a connector URL.
Local dev blocked / blank tunnelBrowser's Local Network Access prompt (Chrome/Edge) blocking public→localhost calls. Approve the permission prompt or check enterprise policy.
Service principal push failsThe app was never shared to the SPN. A maker must run pa app share --principal <enterprise-app-object-id> --access edit first — use the Enterprise Application object ID, not the App Registration object ID.
"Premium connector blocked"User lacks Premium licence OR DLP policy blocks the connector class.
"Solution import fails"Connection references unmapped. Map them in the solution import wizard.
HMR not refreshingCheck for syntax errors in console; restart pa app run.
license Governance Cheats
VS Code Shortcuts You'll Actually Use
Ctrl+`Toggle integrated terminal
Ctrl+Shift+PCommand palette
Ctrl+PQuick open file
Ctrl+Shift+FSearch across workspace
F12Go to definition
Shift+F12Show all references
F2Rename symbol (TS-aware)
Ctrl+.Quick fix / refactor
Alt+Shift+FFormat document
Ctrl+BToggle sidebar
Ctrl+\Split editor
F5Start debugging (with launch.json)
FAQ Quick Answers
Do I need Dataverse?No. You can use SharePoint, SQL, or any connector — Dataverse is just one option.
Can I use Next.js / Remix?Code Apps target a static client bundle; SSR frameworks aren't supported. Use Vite + React/Vue/Svelte/Angular SPA mode.
Can I use Tailwind CSS?Yes — install tailwindcss, init config, import in index.css. Works seamlessly with Vite.
Call Azure Functions / APIs directly?Yes — via a custom connector wrapper. Direct fetch works for public APIs, but loses governance.
Embed in a model-driven page?Use an iframe with the code app's URL, or embed via a PCF host control.
How do I version & rollback?Each pa app push creates a new version; previous versions are retained & restorable from the maker portal.
Does it work on mobile?Yes, in the Power Apps mobile player — design responsively. Native shell APIs (camera, GPS) limited via SDK; use the device's web APIs or connectors.
Users without licenses?No run without licensing — Premium licensing applies to all runtime users, even to try the app.
Is the source code visible?The compiled JS bundle is downloaded to the client (like any web app). Keep secrets server-side or in connector auth.
Migrate from Canvas?No automatic migration. Rebuild the UI in React; reuse connectors via pa app add data-source.
resources Official Links — bookmark these
OverviewCode Apps concept, prerequisites, limitations (GA)
Quickstart (pa CLI)Current end-to-end first-app walkthrough using the pa CLI
Power Apps CLI Command ReferenceFull pa command & parameter reference (replaces the old npm-quickstart doc)
CLI Environment VariablesEvery PA_CLI_* variable and its matching flag
Connect your code app to dataDirect-connection vs connection-reference data source flows
Add a Dataverse action/functionpa app find-dataverse-api / add-dataverse-api
Add Power Automate flowspa app list-flows / add-flow / remove-flow
Create a connection from the CLIpa connection create for SSO-eligible connectors
Sign in & manage accountspa auth login/status/switch/logout deep-dive
Publish with a service principalCI/CD via pa app push --non-interactive
Get context datagetContext() — app/user/host properties
SDK v1.0 Migration GuideRemoving initialize(), adopting setConfig()
Code Apps ArchitectureHow the runtime, auth, and connector layer fit together
System Limits & ConfigurationCapacity, quotas, and config boundaries
pac code Reference (legacy)Still works, no longer recommended
@microsoft/power-apps on npmClient library package + changelog (v1.3.x)
@microsoft/power-apps-cli on npmThe pa CLI package + changelog
Connector Library1,500+ connectors you can wire via pa app add data-source
DLP PoliciesHow DLP applies to connectors used in code apps
ALM GuidanceSolutions, pipelines, source control patterns
Sharing AppsShare & secure published apps
Fluent UI v9Microsoft design system — recommended pairing
Vite DocsBuild tool used under the hood
React DocsReference for the default scaffolded UI library
Power Platform AdminTenant enablement, environments, monitoring
Official Samples & Templates (GitHub)Samples, starter templates, and issue tracker from the product team