
Add Server Logic
- 111 installs
- 605 repo stars
- Updated August 4, 2026
- microsoft/power-platform-skills
Add Server Logic creates server-side JavaScript files (.js) and metadata YAML (.serverlogic.yml) that run securely on Power Pages runtime, with HTTP and Dataverse connectors, optional secret management, and client-side i
About
Add Server Logic enables developers to build secure, server-side JavaScript endpoints in Power Pages that run on the platform runtime, protected by web roles and table permissions. The skill orchestrates the full lifecycle: requirements gathering, documentation fetching, code implementation, Dataverse table permissions configuration, secret management (with optional Azure Key Vault), site settings configuration, client-side integration, and deployment. It handles single or multiple server logic files with proper error handling, logging, CSRF token management, and validate-and-execute patterns for business logic enforcement. Server Logic is a preview feature supporting ECMAScript 2023 with HTTP connectors for external APIs and Dataverse connectors for data operations, both synchronous.
- Server-side JavaScript execution hidden from browsers with web role and table permission controls
- Full lifecycle orchestration from requirements through deployment with user confirmations at key gates
- Automatic Dataverse custom action discovery and wrapping as secure portal-facing endpoints
- Azure Key Vault integration for secrets or direct environment variable storage with Dataverse backing
- Client-side integration wiring with validate-and-execute pattern enforcement and CSRF token handling
Add Server Logic by the numbers
- 111 all-time installs (skills.sh)
- +6 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #2,929 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/microsoft/power-platform-skills --skill add-server-logicAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 111 |
|---|---|
| repo stars | ★ 605 |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 4, 2026 |
| Repository | microsoft/power-platform-skills ↗ |
What it does
Create secure server-side JavaScript endpoints in Power Pages that call external APIs and Dataverse without exposing credentials to browsers.
Who is it for?
Developers building Power Pages sites who need to call authenticated external APIs, perform secure Dataverse operations, enforce business logic server-side, protect sensitive credentials, or wrap existing Dataverse custo
Skip if: Client-side frontend logic, UI components, form design, theme customization, or simple read-only data displays that do not require backend processing.
When should I use this skill?
User wants to add server-side code to a Power Pages site, create API endpoints that call external services, move logic from browser to server, enforce state machines or business rules server-side, or integrate with authe
What you get
User has deployed one or more server logic endpoints accessible via /_api/serverlogics/<name>, protected by web roles and table permissions, with secrets stored securely (Key Vault or env vars), table permissions configu
Files
Plugin check: Run node "${PLUGIN_ROOT}/scripts/check-version.js" — if it outputs a message, show it to the user before proceeding.Add Server Logic
Create and manage one or more Power Pages Server Logic files — server-side JavaScript that runs securely on the Power Pages runtime, hidden from the browser and protected by web roles and table permissions. Server Logic enables secure external API integrations, Dataverse operations, and custom business logic without exposing sensitive code or credentials to the client.
Core Principles
- Microsoft Learn is the source of truth: Always fetch the latest documentation before writing code. The Server Logic feature is in preview and the SDK may change — never rely on cached knowledge alone.
- No browser APIs, no dependencies: Server Logic runs in a sandboxed server environment with ECMAScript 2023 support. There is no
fetch,XMLHttpRequest,setTimeout, or any DOM API. No npm packages are available. - Five functions only: A server logic file can only export these top-level functions:
get,post,put,patch,del. The namedeleteis a reserved word in JavaScript and cannot be used. - Always return a string: Every function must return a string. Use
JSON.stringify()when returning objects or arrays. - Use TaskCreate/TaskUpdate: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.
Prerequisites:
- An existing Power Pages code site created
- The site must be deployed at least once (.powerpages-sitefolder must exist) — server logic files live inside.powerpages-site/server-logic/, so deployment is required before any server logic can be created
Initial request: $ARGUMENTS
---
Workflow
1. Verify Site Exists — Locate the Power Pages project, explore existing patterns, and verify prerequisites 2. Understand Requirements — Determine the user intent and whether the solution needs one or more server logic files 3. Fetch Latest Documentation — Query Microsoft Learn for the most current Server Logic SDK reference 4. Review Implementation Plan — Present the plan to the user and confirm before writing code 5. Implement Server Logic — Create the approved .js and .serverlogic.yml files in .powerpages-site/server-logic/<name>/ 6. Configure Table Permissions — (Conditional: only if Server.Connector.Dataverse is used) Set up table permissions for Dataverse tables accessed by the server logic 7. Manage Secrets & Environment Variables — (Conditional: only if the server logic requires secrets) Store sensitive values securely using Azure Key Vault (recommended) or direct environment variables in Dataverse 8. Configure Site Settings — Set up ServerLogic site settings if needed 9. Client-Side Integration — Help wire the server logic into the site's frontend code 10. Verify & Test Guidance — Validate the code and provide testing instructions 11. Review & Deploy — Present summary and offer deployment
---
Phase 1: Verify Site Exists
Goal: Locate the Power Pages project root and confirm prerequisites
Actions:
1. Create todo list with all 11 phases (see Progress Tracking table)
1.1 Locate Project
Look for powerpages.config.json in the current directory or immediate subdirectories
If not found: Tell the user to create a site first with /create-site.
1.2 Read Existing Config
Read powerpages.config.json to get the site name and configuration:
1.3 Detect Framework
Read package.json to determine the frontend framework (React, Vue, Angular, or Astro). This is needed for Phase 8 (client-side integration guidance). See ${PLUGIN_ROOT}/references/framework-conventions.md for the full framework detection mapping.
1.4 Explore Existing Server Logic and Frontend Code
Use the Explore agent (via Task tool with agent_type: "explore") to analyze the site for existing server logic patterns and frontend code that may call or need to call server logic endpoints.
Prompt for the Explore agent:
"Analyze this Power Pages code site for server logic context. Check:
1. Does .powerpages-site/server-logic/ exist? If yes, list all subdirectories and their .js files. Summarize what each server logic does (which functions it implements, what SDK features it uses). Also read the corresponding .serverlogic.yml files to check web role assignments.2. Search the frontend source code (src/**/*.{ts,tsx,js,jsx,vue,astro}) for any existing calls to/_api/serverlogics/— these indicate server logic endpoints already being consumed.
3. Look for CSRF token handling patterns (__RequestVerificationToken,_layout/tokenhtml) — these show how the site currently makes authenticated API calls.
4. Check for any TODO/FIXME comments mentioning server logic, backend, or server-side processing.
5. Look for hardcoded API URLs, mock data, or placeholder fetch calls that might need to be replaced with server logic calls.
6. Check for any existing service layer or API utility files insrc/shared/,src/services/, or similar directories that could be reused for server logic integration.
7. Read .powerpages-site/web-roles/*.webrole.yml files to list available web roles and their GUIDs — these are needed when creating the server logic metadata YAML.8. For each existing server logic, assess whether it can be reused or safely extended for the requested capability instead of creating a brand-new server logic file. Call out any strong reuse candidates and explain why.
Report all findings so we can avoid duplicating work and match existing patterns."
From the Explore agent's findings, note:
- Existing server logic files — what's already implemented, and which ones are candidates for reuse or extension
- Frontend calling patterns — how the site makes API calls (match this pattern in Phase 9)
- Existing service/utility files — reuse these when adding client-side integration
- Gaps — frontend code that references server logic endpoints that don't exist yet
1.5 Check Deployment Status (Mandatory)
Look for the .powerpages-site folder:
If not found: The site must be deployed before server logic can be created — server logic files live inside .powerpages-site/server-logic/. Tell the user:
"The .powerpages-site folder was not found. Server logic files are stored inside this folder, so the site must be deployed at least once before creating server logic. Would you like to deploy now?"<!-- gate: add-server-logic:1.5.deploy-first | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:1.5.deploy-first): .powerpages-site missing — server logic files live inside it. Deploy first or stop.>
Trigger: Phase 1.5 found no .powerpages-site directory.Why we ask: Server logic.js/.ymlfiles written to a non-existent path won't deploy.
Cancel leaves: Nothing — no server logic files written yet.
Use AskUserQuestion:
| Question | Options |
|---|---|
The .powerpages-site folder is required for server logic. Would you like to deploy the site now? | Yes, deploy now (Required), Cancel |
If "Yes, deploy now": Invoke /deploy-site first, then continue to Phase 2.
If "Cancel": Stop the workflow — server logic cannot be created without .powerpages-site.
Output: Confirmed project root, .powerpages-site exists, existing server logic (if any), available web roles
---
Phase 2: Understand Requirements
Goal: Determine the user intent, identify whether one or more server logic files are needed, and capture the required HTTP methods for each item
Actions:
2.1 Analyze User Request
From the user's request, determine:
- Intent shape: Does the request map to a single server logic or multiple server logic?
- Reuse opportunities: Can an existing server logic satisfy or be safely extended for part of the request?
- Server logic inventory: For each required server logic, capture the purpose, suggested endpoint name, and whether it should be reused, extended, or created new
- HTTP methods needed: Which of the 5 functions should be implemented for each server logic (
get,post,put,patch,del)
Prefer reuse or safe extension of an existing server logic when it already matches the domain, security model, and lifecycle of the requested capability. Only create a new server logic when reuse would make the existing file confusing, over-broad, or unsafe.
Prefer multiple server logic files when the use case naturally separates into different responsibilities, security boundaries, or lifecycle concerns. Examples:
- Separate read vs. write workflows with different web role requirements
- Distinct integrations with different external systems or site settings
- Independent business capabilities that would be harder to test or reason about if merged into one endpoint
2.1.1 Identify Validate-and-Execute Patterns
For each planned server logic item, determine whether it should validate-and-execute — meaning the server logic both validates a business rule AND performs the resulting Dataverse write, rather than just returning a validation result for the client to act on.
A server logic item should validate-and-execute when any of these are true:
| Condition | Example |
|---|---|
| It enforces a state machine or lifecycle | Order status: Draft → Submitted → Approved |
| The write is conditional on a business rule that must be tamper-proof | "Only allow bid submission before the deadline" |
| The operation spans multiple tables atomically | Award a bid + reject all others + update event status |
| The write involves a computed or derived value | Server calculates a score and writes it |
| The client should not have direct write access to the field | Status fields with strict transition rules |
For each validate-and-execute item, note:
- Which Dataverse writes the server logic will perform (UpdateRecord, CreateRecord, etc.)
- Which fields are being written — these fields should NOT be writable via Web API from the client
- What the server logic returns to the client — typically a success/failure result with the before/after state, NOT a validation flag that the client acts on
Anti-pattern to avoid: A server logic item that only validates and returns { valid: true/false }, expecting the client to make a separate Web API call to perform the write. This allows the client to skip validation and write directly.
2.1.2 Discover Dataverse Custom Actions
If any planned server logic item involves Dataverse operations, check whether the user's Dataverse environment has existing custom actions (Custom APIs or Custom Process Actions) that could be leveraged instead of building logic from scratch.
Step 1 — Fetch custom actions:
node "${PLUGIN_ROOT}/scripts/list-custom-actions.js" "<ENV_URL>"The script outputs a JSON object with:
customApis— Modern Custom APIs with full request parameters and response propertiescustomProcessActions— Legacy Custom Process Actions (activated only)total— Total count of both types combined
Each entry includes: name, displayName, description, type (action or function), binding (unbound, entity, or entityCollection), boundEntity, and source (customApi or customProcessAction). Custom APIs also include requestParameters and responseProperties arrays.
Step 2 — Present and ask the user:
If custom actions are found (total > 0), present a summary to the user grouped by binding type (unbound vs. entity-bound) and ask whether any should be used:
<!-- gate: add-server-logic:2.1.2.use-custom-actions | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:2.1.2.use-custom-actions): Custom actions discovered — decide whether to wrap existing Dataverse Custom APIs/Process Actions or build server logic from scratch. Choice changes the Phase 5 implementation shape.
>
Trigger: list-custom-actions.js returned at least one entry.Why we ask: Auto-wrapping could attach the wrong action; auto-skipping duplicates logic that already exists in Dataverse.
Cancel leaves: Nothing — no server logic files written yet.
Use AskUserQuestion:
| Question | Options |
|---|---|
Your Dataverse environment has <total> custom action(s). Would you like to use any of these in your server logic instead of writing the logic from scratch? | Yes, let me choose which ones to use; No, build everything from scratch |
Present the list clearly — for each action show: name, description, type (action/function), binding, and bound entity (if applicable). Group them as Unbound and Entity-bound for readability.
If the user says No, skip to Phase 2.2.
Step 3 — Map custom actions to server logic items:
If the user says Yes, for each server logic item being created, ask which custom action (if any) it should wrap:
<!-- not-a-gate: per-item custom-action mapping — data-gathering sub-prompt under the Phase 2.1.2 Yes path; final intent is locked in by the Phase 4.4 plan gate -->
Use AskUserQuestion for each server logic item:
| Question | Context |
|---|---|
For the <server-logic-name> endpoint, which custom action should it use? | Present the list of custom actions with their names, descriptions, and binding types. Include "None — build from scratch" as an option. |
Record the mapping for each server logic item. For items that wrap a custom action, note:
- The custom action name (used in the
InvokeCustomApicall) - Whether it's a function (
GET) or action (POST) - The binding type and bound entity (if applicable)
- The request parameters and response properties (if available from Custom APIs)
This mapping will be used in Phase 5.3 when generating the server logic code, and will appear in the HTML plan (Phase 4) to indicate which items wrap existing custom actions.
2.2 Identify SDK Features Needed
Based on each planned server logic item's purpose, identify which Server SDK features are required:
| Feature | When to use |
|---|---|
Server.Connector.HttpClient | Calling external REST APIs (NOT Dataverse) |
Server.Connector.Dataverse | Reading/writing Dataverse records (CRUD + InvokeCustomApi for Dataverse Custom APIs) |
Server.Context | Accessing request parameters, headers, body |
Server.User | User-scoped operations, role checks |
Server.Logger | Always — every function should log entry/exit and errors |
Server.Sitesetting | Reading site setting configuration values |
Server.EnvironmentVariable | Reading Dataverse environment variable values directly via Server.EnvironmentVariable.get(name) — an alternative to Server.Sitesetting for non-secret config |
Server.Website | Accessing site metadata |
2.3 Identify Secret Values
Determine whether any server logic item requires secret or sensitive configuration values that should not be hardcoded. Common examples:
| Scenario | Secret needed |
|---|---|
| Calling an authenticated external API | API key, client secret, bearer token |
| Connecting to a third-party service | Connection string, access token |
| OAuth2 client credentials flow | Client ID + client secret |
| Webhook verification | Signing secret, shared key |
For each identified secret, capture:
- Secret name: A descriptive name (e.g.,
ExchangeRateApiKey,PaymentGatewaySecret) - Purpose: Why the secret is needed
- Site setting name: The name the server logic will use with
Server.Sitesetting.Get()(e.g.,ExternalApi/ExchangeRateApiKey) - Environment variable schema name: The Dataverse environment variable schema name (e.g.,
cr5b4_ExchangeRateApiKey)
These values will be used in Phase 7 to create the environment variables and site settings.
2.3.1 Key Vault Decision
If secrets were identified in Phase 2.3, ask the user now whether they want to use Azure Key Vault. This decision must happen before Phase 4 so the implementation plan can show the chosen secret management approach.
<!-- gate: add-server-logic:2.3.1.keyvault | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:2.3.1.keyvault): Pick secret-storage mechanism (Key Vault vs plain env var). Choice changes the Phase 4 rendered plan and the Phase 7 implementation pipeline.
>
Trigger: Phase 2.3 identified at least one secret value.
Why we ask: Plain env var creation can expose secrets in solution exports; auto-picking Key Vault forces additional Azure setup.
Cancel leaves: Nothing — no env var definitions written yet.
Use AskUserQuestion:
| Question | Options |
|---|---|
| This server logic requires secret values (e.g., API keys, client secrets). Azure Key Vault is the recommended way to store secrets securely. Would you like to use Azure Key Vault? | Yes, use Azure Key Vault (Recommended), No, store directly as environment variable |
Record the user's choice — it will be shown in the HTML plan (Phase 4) and executed in Phase 7.
2.4 Confirm with User
<!-- not-a-gate: requirement clarification — multi-question data-gathering that shapes the upcoming Phase 4.4 plan gate -->
If the requirements are ambiguous, use AskUserQuestion to clarify:
| Question | Context |
|---|---|
| What should this server logic solution do overall? | If the purpose is unclear |
| Should this be one server logic or multiple server logic? | If the request could reasonably be modeled either way |
| Which HTTP methods does each server logic need? | If not specified — suggest based on the use case (e.g., read-only = GET, form processing = POST) |
| Does each server logic need to call external APIs, Dataverse, or both? | Determines which connectors to use |
| What should each server logic be named? | Suggest URL-friendly names based on the responsibilities |
| Does the server logic need any secret or sensitive values (API keys, client secrets, tokens)? | If the server logic calls authenticated external APIs or services |
Output: Clear understanding of the overall intent, the list of server logic items to reuse/extend/create, their HTTP methods, SDK features needed, and any secrets required
---
Phase 3: Fetch Latest Documentation
Goal: Discover and read all current Server Logic documentation from Microsoft Learn before writing any code
This step is critical because Server Logic is a preview feature and the SDK surface may change. The documentation on Microsoft Learn is the authoritative source.
Actions:
3.1 Follow the Documentation Reference
Use the reference document below as the source of truth for how to discover, classify, fetch, and reconcile Server Logic documentation:
Reference: ${PLUGIN_ROOT}/skills/add-server-logic/references/server-logic-docs.mdFollow that reference to:
- Search Microsoft Learn dynamically for all current Server Logic docs
- Fetch the core reference pages and any relevant scenario-specific pages
- Search for current code samples
- Reconcile the discovered documentation with the known SDK baseline in the reference
3.2 Extract Task-Specific Notes
From the fetched docs, extract and note the items that matter for the current task:
- All SDK method signatures, parameter types, and return types
- Current supported HTTP methods and function signatures
- Site settings and their defaults
- Security model (web roles, table permissions, CSRF)
- Client-side calling patterns and response format
- Any new methods or breaking changes discovered in Microsoft Learn
Output: Up-to-date SDK reference verified against all relevant Microsoft Learn documentation pages
---
Phase 4: Review Implementation Plan
Goal: Present the implementation plan to the user and confirm before writing any code
Actions:
4.1 Prepare the Plan Data
Build the server logic plan data and render the HTML plan before asking for approval.
Reference: ${PLUGIN_ROOT}/skills/add-server-logic/references/server-logic-plan-data-format.mdThe rendered plan should summarize:
- The number of server logic items being created or reused
- Each endpoint name, API URL, and files to be created
- The functions that will be implemented and what each one does
- The SDK features, external services, and Dataverse tables involved for each item
- The web roles, security constraints, and site settings that apply to each item
- Any secrets or sensitive values that will be stored as environment variables (with or without Azure Key Vault). If the user chose Azure Key Vault in Phase 2.3.1, populate
SECRETS_DATAwithuseKeyVault: trueand the list of secrets — the HTML plan will render a Key Vault banner explaining the security benefits and show which secrets each server logic depends on. If no secrets are needed, setSECRETS_DATAtonull. - The expected next steps after approval
4.2 Render the HTML Plan
Generate the HTML plan file from the template and open it in the user's default browser before asking for approval.
When working inside a Power Pages project, write the plan to:
<PROJECT_ROOT>/docs/serverlogic-plan.htmlCreate the docs/ folder if it does not already exist. Keep this HTML file inside the repository so it can be reviewed and committed with the rest of the server logic work.
Do not hand-author the HTML. Use the render script:
node "${PLUGIN_ROOT}/scripts/render-serverlogic-plan.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"The render script refuses to overwrite existing files. Before calling it, check if the default output path (<PROJECT_ROOT>/docs/serverlogic-plan.html) already exists. If it does, choose a new descriptive filename based on context — e.g., serverlogic-plan-exchange-rate.html, serverlogic-plan-apr-2026.html. Pass the chosen name via --output.
4.3 Present Plan Summary
Do not present a second detailed plan in the CLI. The HTML file is the single detailed plan artifact.
In the CLI, give only a brief summary that points the user to the HTML plan open in the browser. Keep it to:
- Total server logic count
- Whether the plan is creating, updating, or reusing items
- Whether web roles, table permissions, or site settings are involved
- The actual output path returned by the render script
- A note that the browser-opened HTML contains the full details
Do not restate the per-server-logic breakdown, rationale, role assignments, or function details inline in the CLI unless the user explicitly asks for a text version. Tell the user where the detailed HTML plan file was saved, that it has been opened in the browser for review, and that the repo copy of the plan will be committed with the implementation artifacts unless the user asks to discard it.
4.4 Confirm with User
<!-- gate: add-server-logic:4.4.plan-approval | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:4.4.plan-approval): Final sign-off on the rendered HTML plan before Phase 5 writes any.serverlogic.yml/.jsfiles or Phase 7 creates env vars.
>
Trigger: Phase 4.2 rendered the HTML plan; Phase 4.3 surfaced the CLI summary.
Why we ask: Server logic files committed under wrong names / wrong roles; env var definitions created against the wrong secret-storage mode.
Cancel leaves: Nothing — no server logic files written yet.
Use AskUserQuestion:
| Question | Options |
|---|---|
| Here's the implementation plan for this server logic work. Does it look correct? | Approve and implement (Recommended), Request changes, Cancel |
If "Request changes": Ask what needs to change, update the plan, and present again.
If "Cancel": Stop the workflow.
Output: User-approved implementation plan
---
Phase 5: Implement Server Logic
Goal: Create each approved server logic .js file and metadata YAML following the constraints verified in Phase 3
Actions:
5.1 Create Server Logic Folder
For each approved server logic item:
- If the approved plan says `reuse`: Do not create a new folder. Reuse the existing server logic as-is and only update the surrounding integration work if needed.
- If the approved plan says `update` / extend: Reuse the existing folder and update the existing
.js/.serverlogic.ymlfiles rather than creating duplicates. - If the approved plan says `create`: Create the folder inside
.powerpages-site/server-logic/(note: singularserver-logic, no trailing 's'). Ensure the folder name matches that endpoint name exactly.
5.2 Read or Create Web Roles
Use the Create Web Role skill to determine which web roles are required for the approved server logic plan and to create any missing roles before writing metadata.
Do not assume every server logic should get every available role. Instead, determine the minimum set of roles required for each server logic based on its purpose, security model, and the approved plan.
Example web role file content:
adx_anonymoususersrole: false
adx_authenticatedusersrole: true
description: Role for authenticated users
id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
name: Authenticated UsersIn the skill workflow, explicitly invoke the Create Web Role skill when:
- The site has no suitable existing web roles
- The approved plan includes proposed roles that do not exist yet
- The role assignments need to be refined before metadata can be created
After the Create Web Role skill completes, read the resulting web role YAML files and collect the id and name values needed for each server logic's metadata YAML.
5.3 Create the Server Logic File
Repeat this step for each approved server logic item. Create or update <PROJECT_ROOT>/.powerpages-site/server-logic/<name>/<name>.js according to the approved plan status (create, update, or reuse) and follow these mandatory patterns:
Structure Rules
1. Only top-level functions: The file can only contain these 5 functions at the top level: get, post, put, patch, del. Only include the functions the user needs. 2. Each function returns a string: Use JSON.stringify() for objects/arrays. 3. Each function has try/catch: Every function must wrap its logic in a try/catch block. 4. Each function logs: Use Server.Logger.Log() at entry and Server.Logger.Error() in catch blocks. 5. No imports or requires: No import, require, or external dependencies. 6. No browser APIs: No fetch, XMLHttpRequest, setTimeout, setInterval, console.log, or DOM APIs. 7. Async when needed: Mark functions as async only when they use await (HttpClient calls). Dataverse connector methods (Server.Connector.Dataverse.*) are synchronous — do NOT use async/await with them.
Prohibited Script Patterns
The Power Pages server-side script validator rejects scripts containing certain patterns at runtime. Violations surface as RTSL01: Script validation failed: prohibited pattern found - Pattern: <regex> in diagnostics, and the function silently falls through without executing user code.
| Pattern | Regex | Caveat |
|---|---|---|
JavaScript with statement | with\s*\( | The regex matches the substring with( anywhere in the file — including inside string literals and inside other identifiers. OData filter functions like startswith(, endswith(, and groupwith( will trip it because they end with with(. |
Workaround for OData functions — split the literal so with( is not contiguous in source:
// ❌ Triggers validator: "startswith(" contains the substring "with("
var query = "$filter=startswith(name,'INV-')";
// ✅ Split the literal — server still receives "startswith(name,...)"
var query = "$filter=startswith" + "(name,'INV-')";The same trick applies to endswith(, groupwith(, and any other identifier that ends with with(.
Code Template
// Server Logic: <name>
// Purpose: <description>
// API URL: https://<site-url>/_api/serverlogics/<name>
function get() {
try {
Server.Logger.Log("<name> GET called");
// Access query parameters
// const id = Server.Context.QueryParameters["id"];
// Your logic here...
return JSON.stringify({
status: "success",
method: "GET",
data: null // replace with actual data
});
} catch (err) {
Server.Logger.Error("<name> GET failed: " + err.message);
return JSON.stringify({
status: "error",
method: "GET",
message: err.message
});
}
}Validate-and-Execute Template
When a server logic item is identified as validate-and-execute (see Phase 2.1.1), use this pattern. The key difference: the server logic reads the current state, validates the business rule, AND writes the result to Dataverse — all in one call. The client never writes the protected field directly.
// Server Logic: <name>
// Purpose: Validate and execute <describe the operation>
// Pattern: Validate-and-execute — this endpoint both validates the business rule
// and performs the Dataverse write. The client should NOT write <protected fields>
// via Web API — all writes to those fields go through this endpoint.
// API URL: https://<site-url>/_api/serverlogics/<name>
function post() {
try {
Server.Logger.Log("<name> POST called");
const body = JSON.parse(Server.Context.Body);
const entityId = body.entityId;
const targetStatus = body.targetStatus;
// 1. Read the current record from Dataverse
const current = Server.Connector.Dataverse.RetrieveRecord("<table-name>", entityId, "?$select=<status-field>");
const currentStatus = current["<status-field>"];
// 2. Validate the transition
const allowedTransitions = {
"Draft": ["Submitted"],
"Submitted": ["Approved", "Rejected"],
"Approved": ["Fulfilled"]
};
const allowed = allowedTransitions[currentStatus] || [];
if (!allowed.includes(targetStatus)) {
return JSON.stringify({
status: "error",
message: "Invalid transition: " + currentStatus + " → " + targetStatus + " is not allowed",
currentStatus: currentStatus,
targetStatus: targetStatus,
allowedTargets: allowed
});
}
// 3. Execute the write — server performs the Dataverse update
const updateData = {};
updateData["<status-field>"] = targetStatus;
Server.Connector.Dataverse.UpdateRecord("<table-name>", entityId, JSON.stringify(updateData));
Server.Logger.Log("<name> transition executed: " + currentStatus + " → " + targetStatus);
// 4. Return the result — client receives confirmation, not a validation flag
return JSON.stringify({
status: "success",
previousStatus: currentStatus,
newStatus: targetStatus,
entityId: entityId
});
} catch (err) {
Server.Logger.Error("<name> POST failed: " + err.message);
return JSON.stringify({
status: "error",
message: err.message
});
}
}Key differences from the basic template: 1. The server logic reads the current state from Dataverse (not trusting the client's view) 2. It validates the business rule server-side 3. It writes the result to Dataverse via Server.Connector.Dataverse.UpdateRecord 4. It returns a success/failure result — NOT a { valid: true/false } flag for the client to act on 5. The client calls this one endpoint — it does NOT make a separate Web API PATCH call
Custom Action Wrapping Template
When a server logic item wraps a Dataverse custom action (mapped in Phase 2.1.2), use this pattern with Server.Connector.Dataverse.InvokeCustomApi. The server logic acts as a portal-friendly wrapper, exposing the custom action through a /_api/serverlogics/<name> endpoint with proper web role authorization.
Unbound action:
// Server Logic: <name>
// Purpose: Wraps Dataverse custom action "<custom-action-name>" for portal consumption
// Custom Action: <custom-action-name> (unbound, action)
// API URL: https://<site-url>/_api/serverlogics/<name>
function post() {
try {
Server.Logger.Log("<name> POST called — invoking custom action <custom-action-name>");
const body = JSON.parse(Server.Context.Body);
// Build the request payload matching the custom action's input parameters
const payload = JSON.stringify({
// "<ParameterName>": body.<clientFieldName>
});
const result = Server.Connector.Dataverse.InvokeCustomApi(
"POST",
"<custom-action-name>",
payload
);
Server.Logger.Log("<name> custom action completed successfully");
return JSON.stringify({
status: "success",
data: result
});
} catch (err) {
Server.Logger.Error("<name> POST failed: " + err.message);
return JSON.stringify({
status: "error",
message: err.message
});
}
}Entity-bound action:
function post() {
try {
Server.Logger.Log("<name> POST called — invoking bound action <custom-action-name>");
const body = JSON.parse(Server.Context.Body);
const entityId = body.entityId;
const payload = JSON.stringify({
// "<ParameterName>": body.<clientFieldName>
});
// Include the entity set and record ID, followed by the fully qualified action name
const result = Server.Connector.Dataverse.InvokeCustomApi(
"POST",
"<entity-set-name>(" + entityId + ")/Microsoft.Dynamics.CRM.<custom-action-name>",
payload
);
Server.Logger.Log("<name> bound action completed for entity " + entityId);
return JSON.stringify({
status: "success",
data: result,
entityId: entityId
});
} catch (err) {
Server.Logger.Error("<name> POST failed: " + err.message);
return JSON.stringify({
status: "error",
message: err.message
});
}
}Unbound function (read-only, GET):
function get() {
try {
Server.Logger.Log("<name> GET called — invoking custom function <custom-function-name>");
// Pass parameters as query string for functions
const param1 = Server.Context.QueryParameters["param1"];
const queryString = "<custom-function-name>(Param1='" + param1 + "')";
const result = Server.Connector.Dataverse.InvokeCustomApi(
"GET",
queryString,
null
);
Server.Logger.Log("<name> custom function completed successfully");
return JSON.stringify({
status: "success",
data: result
});
} catch (err) {
Server.Logger.Error("<name> GET failed: " + err.message);
return JSON.stringify({
status: "error",
message: err.message
});
}
}Key points:
- Unbound actions: Use the action name as the URL, pass parameters as JSON body
- Entity-bound actions: Include the entity set and record ID in the URL path, followed by
Microsoft.Dynamics.CRM.<action-name> - Functions (GET): Use
"GET"as the HTTP method and pass parameters inline in the URL using OData function call syntax - Actions (POST): Use
"POST"as the HTTP method and pass parameters as JSON body payload InvokeCustomApiis synchronous — do NOT useasync/await- The server logic can add additional validation, transformation, or logging around the custom action call — it doesn't have to be a pass-through
- When Custom API response properties are known (from Phase 2.1.2), map them to the response object for clarity
Dataverse Response Shape (Critical for Frontend Integration)
When a function returns the result of a Server.Connector.Dataverse.* method, the client sees a double-wrapped payload — the most common cause of broken frontend integrations. Before writing the function, pick one of three response shapes and record the choice for Phase 9: Approach A — raw passthrough (return the connector result as-is), Approach B — envelope that wraps the connector result (return { status, data: result } without unwrapping Body), or Approach C — fully normalized (parse Body server-side and return a feature-specific shape — recommended for non-generic endpoints).
See ${PLUGIN_ROOT}/skills/add-server-logic/references/frontend-integration-reference.md → "Dataverse Connector Response Format" for the double-wrapping explanation, the CreateRecord / entityid header behavior, and server- and client-side examples for each shape.
Referencing Secrets in Code
When the server logic needs a secret value identified in Phase 2.3, never hardcode the value. Instead, read it at runtime from a site setting backed by an environment variable:
const apiKey = Server.Sitesetting.Get("ExternalApi/ExchangeRateApiKey");Use the site setting name planned in Phase 2.3. The actual environment variable and site setting YAML will be created in Phase 7.
SDK Usage Guidance
Do not duplicate Microsoft Learn SDK usage patterns inline in this skill. Use the documentation fetched in Phase 3 as the source of truth for connector methods, signatures, and supported patterns, then apply only the task-specific notes that were captured in the approved plan.
5.4 Create the Metadata YAML
For each approved server logic item where the plan status is create, generate the metadata file with the deterministic writer script instead of hand-authoring the YAML. The script generates the UUID, writes the fields in the correct order, and returns the created file path as JSON. Skip this step for `update` / `reuse` items — the YAML already exists and should be updated manually if needed.
node "${PLUGIN_ROOT}/skills/add-server-logic/scripts/create-serverlogic-metadata.js" --projectRoot "<PROJECT_ROOT>" --name "<name>" --displayName "<human-readable display name>" --description "<description of what this server logic does>" --webRoleIds "<uuid1,uuid2,uuid3>"The generated <PROJECT_ROOT>/.powerpages-site/server-logic/<name>/<name>.serverlogic.yml file has this structure:
adx_serverlogic_adx_webrole:
- <web-role-guid-1>
- <web-role-guid-2>
- <web-role-guid-3>
description: <description of what this server logic does>
display_name: <human-readable display name>
id: <generated-uuid>
name: <name>Critical requirements:
- `id` field is mandatory — The script generates a new UUID (v4). PAC CLI crashes with
Expected Guid for primary key 'id'if this is missing. - `adx_serverlogic_adx_webrole` — Array of web role GUIDs from step 5.2. Include only the roles required for that server logic item.
- `name` — Must match the folder name and
.jsfile name (the URL-friendly name used in/_api/serverlogics/<name>). - `display_name` — Human-readable name (e.g., "Exchange Rate API", "Order Processor").
- Alphabetical field ordering — Fields must be sorted alphabetically:
adx_serverlogic_adx_webrole,description,display_name,id,name.
5.5 Validate the Code
Before saving, verify the code against these constraints:
| Constraint | Check |
|---|---|
| Only allowed top-level functions | No functions other than get, post, put, patch, del |
| Every function returns a string | All code paths return a string (including catch blocks) |
| try/catch in every function | Every function body is wrapped in try/catch |
| Server.Logger in every function | Log at entry, Error in catch |
| No external dependencies | No import, require, module.exports |
| No browser APIs | No fetch, XMLHttpRequest, setTimeout, console.log, document, window |
| Async only when needed | Only functions using await are marked async |
| ECMAScript 2023 compliant | Standard JS features only (optional chaining, nullish coalescing, etc. are fine) |
5.6 Git Commit
After creating the approved server logic files, do a git commit for the server logic changes.
If the HTML plan was generated inside the project, include it in the same commit (use the actual output path from the render script's JSON response).
Output: Server logic .js and .serverlogic.yml files created, validated, and committed
---
Phase 6: Configure Table Permissions (Conditional)
Goal: Set up table permissions for Dataverse tables accessed by Server.Connector.Dataverse in the server logic code
This phase only runs when the server logic uses `Server.Connector.Dataverse`. If the server logic only uses Server.Connector.HttpClient (external APIs) or doesn't access Dataverse at all, skip this phase entirely and proceed to Phase 7.
Server.Connector.Dataverse does NOT bypass table permissions — it respects them. Without table permissions configured, the Dataverse connector silently returns 0 records instead of the actual data. This is a common source of confusion.
Actions:
6.1 Detect Dataverse Tables and Required Privileges
Parse the server logic .js file created in Phase 5 to identify which Dataverse tables are accessed and what CRUD operations are performed:
| Dataverse SDK Method | Required Table Permission |
|---|---|
RetrieveMultipleRecords("tablename", ...) | Read |
RetrieveRecord("tablename", ...) | Read |
CreateRecord("tablename", ...) | Create |
UpdateRecord("tablename", ...) | Write |
DeleteRecord("tablename", ...) | Delete |
Extract the entity set name (first argument) from each method call. Build a mapping:
| Table (entity set name) | Read | Create | Write | Delete |
|---|---|---|---|---|
accounts | Yes | — | — | — |
contacts | Yes | Yes | — | — |
6.2 Use the Table Permissions Architect
When any approved server logic item uses Server.Connector.Dataverse, invoke the table-permissions-architect agent at ${PLUGIN_ROOT}/agents/table-permissions-architect.md to determine and create the required table permissions.
Prompt:
"Analyze this Power Pages code site and propose table permissions for Dataverse tables accessed by the approved server logic plan. The following tables need permissions:
>
[list each table with required CRUD privileges from step 6.1, grouped by server logic item]
>
Context:
- These permissions are needed because the server logic uses Server.Connector.Dataverse, which respects table permissions — without them, the connector silently returns 0 records.- The scope should typically be Global for server logic that fetches all records, unless the server logic filters by the current user (in which case use Contact scope).
- The web roles assigned to these server logic items are: [list web role names and GUIDs from Phase 5.2]
- Project root: [path]
>
Check for existing table permissions and web roles. If new web roles are needed, create them using the create-web-role.js script. Propose a plan, then after approval create the table permission YAML files using the deterministic scripts."
The agent will: 1. Discover existing table permissions and web roles 2. Create any missing web roles via create-web-role.js if needed 3. Propose a table permissions plan (with HTML visualization) 4. Present the plan via plan mode for user approval 5. After approval, create table permission YAML files in .powerpages-site/table-permissions/ using create-table-permission.js
6.3 Git Commit
After table permissions (and any new web roles) are created, do a git commit for the table permissions changes.
Output: Table permissions (and web roles if created) configured for all Dataverse tables accessed by the server logic
---
Phase 7: Manage Secrets & Environment Variables
Goal: Securely store any secret values (API keys, client secrets, connection strings) required by the server logic as environment variables in Dataverse, optionally backed by Azure Key Vault
This phase only runs when the server logic requires secret or sensitive configuration values (identified in Phase 2.3). If no secrets are needed, skip this phase and proceed to Phase 8.
Actions:
7.1 Recall Key Vault Decision
The user already chose whether to use Azure Key Vault in Phase 2.3.1 (before the plan was presented). Use that decision here — do not re-ask.
7.2a Azure Key Vault Path
If the user chose Azure Key Vault in Phase 2.3.1:
Step 1 — List available Key Vaults:
node "${PLUGIN_ROOT}/scripts/list-azure-keyvaults.js"The script outputs a JSON array of Key Vaults (name, resourceGroup, location) from the user's Azure subscription.
Step 2 — Select or create a Key Vault:
If Key Vaults were found, present the list and ask which one to use:
<!-- not-a-gate: Key Vault selection — data-gathering for the secret-store call under the Phase 2.3.1 Key Vault branch -->
Use AskUserQuestion:
| Question | Context |
|---|---|
| Which Azure Key Vault would you like to use for storing secrets? | Present the names from the script output |
If no Key Vaults are found, ask the user how to proceed:
<!-- gate: add-server-logic:7.2a.no-vaults | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:7.2a.no-vaults): No Key Vaults found in the user's subscription — create one or fall back to plain env vars. Branches the secret-storage flow.
>
Trigger: Phase 2.3.1 chose Key Vault but list-azure-keyvaults.js returned an empty list.Why we ask: Auto-creating a Key Vault provisions Azure resources without explicit consent; auto-falling-back stores secrets as plain env vars after the user explicitly opted in to Key Vault.
Cancel leaves: Nothing — no Azure or Dataverse writes yet.
Use AskUserQuestion:
| Question | Options |
|---|---|
| No Azure Key Vaults were found in your subscription. Would you like to create one, or fall back to storing secrets directly as environment variables? | Create a new Key Vault (Recommended), Store directly as environment variable |
If "Create a new Key Vault": Ask for a vault name, resource group, and location, then create it:
<!-- not-a-gate: Key Vault provisioning parameters — data-gathering for the create-azure-keyvault.js call under the Phase 7.2a "Create new" path -->
Use AskUserQuestion:
| Question | Context |
|---|---|
| What name, resource group, and Azure region would you like for the new Key Vault? | Vault names must be 3-24 characters, globally unique, start with a letter, and contain only alphanumerics and hyphens. Suggest a name based on the project/site name. |
node "${PLUGIN_ROOT}/scripts/create-azure-keyvault.js" \
--name "<vault-name>" \
--resourceGroup "<resource-group>" \
--location "<location>"The script outputs a JSON object with name, resourceGroup, and location. Use the created vault for the remaining steps.
If "Store directly as environment variable": Skip the rest of Phase 7.2a and proceed to Phase 7.2b (direct environment variable path).
Step 3 — Provide instructions for storing each secret in Key Vault:
For each secret identified in Phase 2.3, give the user instructions to store the value themselves. Do not ask for the secret value — secret values must never pass through the conversation.
Present both methods (CLI and Azure Portal) so the user can choose whichever they prefer:
Option A — Azure CLI (recommended for automation):
Present the commands as a numbered list the user can copy and run. Use the stdin form so the secret value does not appear in process listings:
For each secret, run the following command (replacing <YOUR_SECRET_VALUE> with the actual value):
1. <secret-name>:
printf '%s' '<YOUR_SECRET_VALUE>' | node "${PLUGIN_ROOT}/scripts/store-keyvault-secret.js" \
--vaultName "<selected-vault>" \
--secretName "<secret-name>"Tell the user each command outputs a JSON object with a secretUri and to share the output (which contains only the URI, not the secret) so the workflow can continue.
Option B — Azure Portal:
Provide these steps for each secret:
1. Go to the Azure Portal (https://portal.azure.com)
2. Search for "Key vaults" in the top search bar and select it
3. Select the Key Vault: <selected-vault>
4. In the left menu under "Objects", click "Secrets"
5. Click "+ Generate/Import" at the top
6. Fill in the fields:
- Upload options: Manual
- Name: <secret-name>
- Secret value: paste your secret value here
- Leave other fields as defaults
7. Click "Create"
8. After creation, click on the secret name, then click the current version
9. Copy the "Secret Identifier" URI and share it here so the workflow can continueTell the user the Secret Identifier URI looks like https://<vault-name>.vault.azure.net/secrets/<secret-name>/<version> and that this URI (not the secret value) is what should be shared back.
Step 4 — Create environment variable in Dataverse:
After the user shares the secretUri output from each command, create an environment variable definition in Dataverse that references the Key Vault secret. Use the secret type:
node "${PLUGIN_ROOT}/scripts/create-environment-variable.js" "<ENV_URL>" \
--schemaName "<prefix_SecretName>" \
--displayName "<Secret Display Name>" \
--type "secret" \
--value "<secretUri-from-step-3>"Step 5 — Create site setting for the environment variable:
For each environment variable, create a site setting YAML that maps to it:
node "${PLUGIN_ROOT}/scripts/create-site-setting.js" \
--projectRoot "<PROJECT_ROOT>" \
--name "<SiteSetting/Name>" \
--envVarSchema "<schemaName-from-step-4>"This creates a site setting with envvar_schema and source: 1, which tells Power Pages to resolve the value from the Dataverse environment variable (backed by Key Vault).
7.2b Direct Environment Variable Path
If the user chose not to use Azure Key Vault:
Step 1 — Create environment variables with placeholder values:
For each secret identified in Phase 2.3, create the environment variable in Dataverse with a placeholder value:
node "${PLUGIN_ROOT}/scripts/create-environment-variable.js" "<ENV_URL>" \
--schemaName "<prefix_SecretName>" \
--displayName "<Secret Display Name>" \
--value "PLACEHOLDER_SET_ACTUAL_VALUE"Step 2 — Create site setting for the environment variable:
node "${PLUGIN_ROOT}/scripts/create-site-setting.js" \
--projectRoot "<PROJECT_ROOT>" \
--name "<SiteSetting/Name>" \
--envVarSchema "<schemaName-from-step-1>"Step 3 — Give the user steps to set the actual secret values:
Do not ask for secret values — they must never pass through the conversation. Instead, tell the user to update each placeholder with the real value using one of these approaches:
1. Power Apps maker portal (make.powerapps.com) — Go to Solutions → Default Solution → Environment variables → find the variable by display name → update the value
Present the list of environment variables that need updating (display name and schema name for each) so the user knows exactly which ones to set.
7.3 Verify Environment Variable Configuration
After creating all environment variables and site settings:
- Confirm each site setting YAML was created in
.powerpages-site/site-settings/ - Verify each YAML contains
envvar_schemaandsource: 1 - Confirm the server logic code references the correct site setting names via
Server.Sitesetting.Get("<SiteSetting/Name>")
7.4 Git Commit
Do a git commit for the environment variable site setting changes.
Output: Environment variables created in Dataverse (with or without Azure Key Vault backing), site settings configured, server logic referencing correct setting names
---
Phase 8: Configure Site Settings
Goal: Set up site settings for the server logic feature
Actions:
8.1 Configure Server Logic Site Settings
The .powerpages-site folder is guaranteed to exist at this point (verified in Phase 1.5).
The following site settings control server logic behavior. Only create settings that differ from defaults or are specifically needed:
| Setting | Description | Default | When to configure |
|---|---|---|---|
ServerLogic/Enabled | Enable/disable server logic feature | true | Only if explicitly disabled and needs re-enabling |
ServerLogic/AllowedDomains | Restrict which external domains HttpClient can call | All domains | When the server logic calls external APIs and you want to restrict to specific domains for security |
ServerLogic/TimeoutInSeconds | Maximum execution time | 120 | The platform caps this at 120 seconds — values above 120 are silently clamped. Only configure when you need to lower the timeout, not raise it. |
ServerLogic/AllowNetworkingToAllDomains | Allow networking across domains | true | Set to false when restricting via AllowedDomains |
Use the existing site setting creation script:
node "${PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "ServerLogic/AllowedDomains" --value "api.example.com,api.other.com" --description "Restrict server logic external API calls to these domains"8.2 Git Commit
If any settings were created:
Do a git commit for the site settings changes.
Output: Site settings configured and committed (or skipped if not needed/deployed)
---
Phase 9: Client-Side Integration
Goal: Help the user call the server logic endpoints from their site's frontend code, matching existing patterns discovered in Phase 1
Server logic creates the backend — but without frontend code to call it, the endpoints are unused. This phase creates or updates frontend code to consume the server logic APIs, using the patterns and conventions already established in the codebase.
Actions:
9.1 Ask User About Integration Scope
<!-- gate: add-server-logic:9.1.frontend-scope | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:9.1.frontend-scope): Decide whether the skill also wires the server logic into the frontend UI or stops at the backend.
>
Trigger: Phase 8 completed (server logic deployed-ready).
Why we ask: Auto-integrating mutates UI files the user wanted to handle themselves; auto-skipping leaves the endpoints unreachable from the app.
Cancel leaves: Nothing — server logic backend is already on disk; this prompt only decides frontend follow-through.
Use AskUserQuestion:
| Question | Options |
|---|---|
| I've created the server logic backend. Would you like me to also fully integrate it into the frontend UI? | Yes, fully integrate it into the UI (Recommended), No, I'll handle the frontend myself |
If "No": Skip to Phase 10, but provide the API URL and a code snippet the user can copy.
9.2 Follow the Frontend Integration Reference
Use the reference below for the frontend integration approach, examples, and framework-specific patterns:
Reference: ${PLUGIN_ROOT}/skills/add-server-logic/references/frontend-integration-reference.mdBased on the Explore agent's findings from Phase 1.4 and the approved plan, choose the integration approach from that reference and apply it consistently across all server logic endpoints being wired into the frontend.
9.3 Create or Update Frontend Integration
Following the reference:
- Reuse the existing service layer or API utility when the site already has one
- Create a lightweight CSRF-aware helper only when the site has no established API client pattern
- Group multiple server logic endpoints into a coherent service module when that improves maintainability
- Add framework-specific hooks/composables/services only when the codebase already follows that pattern
- Fully integrate the server logic into the actual UI flow — do not stop at creating service/helper code
- Update the relevant pages, components, forms, buttons, or user journeys so the new backend behavior is reachable from the interface
- Replace placeholder data, mock handlers, or temporary actions when they are meant to be backed by the new server logic endpoints
- Add or preserve loading, success, empty, and error states so the UI behaves like a finished feature
- For validate-and-execute endpoints: The frontend must call the server logic endpoint for the protected operation (e.g., status transition) — it must NOT make a separate Web API PATCH for the same field. Ensure the UI for that operation (e.g., a "Submit" or "Approve" button) calls the server logic service function, not the Web API service
- For Dataverse-backed endpoints: Match the frontend parsing to the response shape chosen in Phase 5.3. See "Dataverse Connector Response Format" in the frontend integration reference for the exact parsing per shape.
- If the response shape is unclear: Do not guess. After the site is deployed, invoke
/test-siteagainst the live site so the actual server logic response can be captured from the network tab and used to drive the integration
9.4 Git Commit
If frontend integration code was created:
Do a git commit for the frontend integration changes.
Output: Frontend service/hook created as needed, UI components/pages fully integrated, and changes committed
---
Phase 10: Verify & Test Guidance
Goal: Validate the code and provide the user with everything needed to test the server logic
Actions:
10.1 Final Code Validation
Re-read each created .js file and verify:
- [ ] Only allowed top-level functions (get, post, put, patch, del)
- [ ] Every function returns a string
- [ ] try/catch in every function
- [ ] Server.Logger calls in every function
- [ ] No
import,require, or external dependencies - [ ] No browser APIs (
fetch,XMLHttpRequest,setTimeout,console.log,document,window) - [ ] Async only on functions that use await
- [ ] Correct SDK method usage (verified against Phase 3 documentation)
- [ ] HttpClient used only for external APIs (not Dataverse)
- [ ] Dataverse connector used for Dataverse operations
Re-read each .serverlogic.yml file and verify:
- [ ]
idfield exists and is a valid UUID - [ ]
adx_serverlogic_adx_webrolearray is non-empty (at least one web role) - [ ]
namematches the folder name and.jsfile name - [ ]
display_nameanddescriptionare populated - [ ] Fields are alphabetically sorted
- [ ] File names match: folder name,
.jsname,.serverlogic.ymlname, andnamefield all use the same value
10.2 Provide API URL
Tell the user each endpoint URL:
https://<site-url>/_api/serverlogics/<server-logic-name>10.3 Test Guidance
Provide testing instructions:
1. Deploy the site first — The server logic must be deployed via /deploy-site before it can be called 2. CSRF token required for non-GET requests — POST, PUT, PATCH, and DELETE calls to server logic endpoints require a CSRF token. Fetch the token from /_layout/tokenhtml and include it as __RequestVerificationToken header. GET requests are exempt from antiforgery validation — no token is needed for read-only calls. 3. Authentication — Server logic respects the site's authentication. Calls from authenticated sessions use cookie-based auth automatically. Anonymous access depends on governance settings. 4. Testing from browser console:
Use the frontend integration reference from Phase 9 for the exact calling pattern that matches the site's stack.
5. Check diagnostics — Server.Logger output can be viewed in Power Pages design studio diagnostics 6. If the endpoint returns an error or unexpected response — see Troubleshooting Server Logic Execution Errors for the Playwright + X-Ms-UserTrace debugging flow
Output: Code validated, API URL provided, test guidance given
---
Phase 11: Review & Deploy
Goal: Present a summary of all work performed and offer deployment
Actions:
11.1 Record Skill Usage
Reference: ${PLUGIN_ROOT}/references/skill-tracking-reference.mdFollow the skill tracking instructions in the reference to record this skill's usage. Use --skillName "AddServerLogic".
11.2 Present Summary
Present a summary of everything that was done:
| Step | Status | Details |
|---|---|---|
| Server Logic JS | Created | List each created .powerpages-site/server-logic/<name>/<name>.js file |
| Server Logic YAML | Created | List each created .powerpages-site/server-logic/<name>/<name>.serverlogic.yml file |
| HTML Plan | Created/Updated | Actual path from render script output |
| Functions | Implemented | Summarize methods implemented per server logic item |
| SDK Features Used | — | Summarize features used per server logic item |
| Table Permissions | Created/Skipped | accounts (Read), contacts (Read, Create), etc. |
| Secrets & Env Vars | Created/Skipped | Environment variables (Key Vault-backed or direct), site settings with envvar_schema |
| Site Settings | Created/Skipped | ServerLogic/AllowedDomains, etc. |
| Client-Side Service | Created/Skipped | List created or updated frontend service files |
| UI Integration | Created/Skipped | Pages, components, forms, or actions fully wired to the server logic endpoints |
| API URL | — | List each /_api/serverlogics/<name> URL |
11.3 Ask to Deploy
<!-- gate: add-server-logic:11.3.deploy | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:11.3.deploy): Post-implementation deploy prompt — server logic endpoints aren't reachable until deployed.
>
Trigger: All server logic artifacts written and committed.
Why we ask: Auto-deploy picks wrong env.
Cancel leaves: Nothing — artifacts stay on disk; no deploy fired.
Use AskUserQuestion:
| Question | Options |
|---|---|
| The server logic work is ready. To make it live, the site needs to be deployed. Would you like to deploy now? | Yes, deploy now (Recommended), No, I'll deploy later |
<!-- gate: add-server-logic:11.3.test | category=plan | cancel-leaves=nothing -->
🚦 Gate (plan · add-server-logic:11.3.test): Post-deploy validation prompt — invokes /test-site to exercise the new endpoints live.>
Trigger: Deploy from the previous gate succeeded.
Why we ask: Skipping is harmless (manual test still possible); auto-invoking /test-site adds runtime.Cancel leaves: Nothing — deploy has already completed.
If "Yes, deploy now": Invoke the /deploy-site skill to deploy the site.
After deployment succeeds, use AskUserQuestion:
| Question | Options |
|---|---|
The site has been deployed. Would you like me to run /test-site to validate it now? | Yes, run /test-site (Recommended), No, skip testing |
If "Yes, run `/test-site`": Invoke the /test-site skill.
If "No, I'll deploy later": Acknowledge and remind:
"No problem! Remember to deploy your site using /deploy-site when you're ready. The server logic endpoints won't be accessible until the site is deployed."11.4 Post-Deploy Notes
After deployment (or if skipped), remind the user:
- Test the endpoints: Call each
/_api/serverlogics/<name>URL with the appropriate HTTP method (include CSRF token for non-GET requests) - Recommended full-site validation: After deployment, ask whether to run
/test-siteso the live site can be validated end to end - Check logs: Use Server.Logger output in Power Pages design studio diagnostics to debug issues
- Table permissions: Table permissions were configured for Dataverse tables used by this server logic. If you add new Dataverse tables later, run the table permissions setup again — without permissions,
Server.Connector.Dataversesilently returns 0 records - Timeout: Default execution timeout is 120 seconds — this is also the platform maximum (values above 120 are silently clamped)
- Anonymous access: If the site's governance control disables anonymous access, anonymous users cannot invoke server logic that integrates with external systems
- Preview feature: Server Logic is currently in preview — monitor Microsoft Learn for updates
- Environment variables with placeholder values: If Phase 7 created environment variables with placeholder values, remind the user to update them with the actual secret values before testing. They can do this via:
1. Power Platform admin center — Environments → select environment → Environment variables → find by display name → update value 2. Power Apps maker portal — Solutions → open solution → Environment variables → edit value
Output: Summary presented, deployment completed or deferred, post-deploy guidance provided
---
Troubleshooting Server Logic Execution Errors
When a deployed server logic endpoint returns an error or unexpected response, the underlying cause is usually hidden inside the X-Ms-UserTrace response header — a base64-encoded blob containing the runtime diagnostic logs. The Power Pages Edge browser extension shows the same data, but inspecting the response header is the fastest path when iterating against a live site.
Use this flow whenever a server logic call fails or returns a different response than expected:
1. Open the Live Site in a Browser via Playwright
Use the Playwright MCP tools to drive the site:
1. Navigate to the deployed site URL (the websiteUrl returned by /activate-site or shown in the Power Pages admin center). 2. Ask the user to sign in if the endpoint requires authentication and wait for confirmation. 3. Trigger the action that calls the failing server logic endpoint (click the button, submit the form, etc.) — or call the endpoint directly with fetch().
2. Capture the Network Response
Use mcp__plugin_power-pages_playwright__browser_network_requests to list network activity, then locate the request to /_api/serverlogics/<name>. Note:
- The HTTP status code (e.g., 200, 400, 500)
- The response body (often a generic error or empty payload when validation fails)
- Most importantly: the `X-Ms-UserTrace` response header — this is where the actual diagnostic logs live
If browser_network_requests does not surface the response headers directly, fall back to mcp__plugin_power-pages_playwright__browser_evaluate and read the headers from a fetch() call:
const res = await fetch('/_api/serverlogics/<name>', { method: 'GET', credentials: 'include' });
const trace = res.headers.get('X-Ms-UserTrace');
return { status: res.status, body: await res.text(), trace };3. Decode the X-Ms-UserTrace Header
The header value is base64-encoded JSON. Decode it.
The decoded payload contains the diagnostic log entries — including the actual error message, the prohibited pattern (if script validation failed).
After fixing, redeploy via /deploy-site and restart the site so the change is picked up immediately.
---
Important Notes
Throughout All Phases
- Use TaskCreate/TaskUpdate to track progress at every phase
- Always fetch Microsoft Learn docs in Phase 3 before writing code — the docs are the source of truth
- Ask for user confirmation at key decision points
- Commit at milestones — after server logic code, table permissions (if any), secrets/environment variables (if any), site settings, and frontend integration (if any)
- Validate thoroughly — server logic has strict constraints and violations cause runtime errors
Key Decision Points (Wait for User)
1. At Phase 1.5: Deploy now or cancel (if .powerpages-site missing — mandatory) 2. At Phase 2.1.2: Use existing Dataverse custom actions or build from scratch (if custom actions found) 3. At Phase 2: Confirm requirements (purpose, name, HTTP methods, secrets) 4. At Phase 4: Approve implementation plan before writing code 5. At Phase 6.2: Review and approve the table-permissions-architect plan (if Dataverse connector is used) 6. At Phase 2.3.1: Choose Azure Key Vault or direct environment variable (if secrets needed) 7. At Phase 7.2a Step 2: Create a new Key Vault or fall back to direct environment variable (if no vaults found) 8. At Phase 9.1: Create frontend integration or skip 9. At Phase 11.3: Deploy now or deploy later
SDK Pattern Source of Truth
Do not treat this skill file as the canonical SDK reference. The Phase 3 Microsoft Learn fetch is the source of truth for SDK usage patterns, supported methods, signatures, and connector behavior. Keep only task-specific decisions in the plan and implementation notes.
Progress Tracking
Before starting Phase 1, create a task list with all phases using TaskCreate:
| Task subject | activeForm | Description |
|---|---|---|
| Verify site exists | Verifying site prerequisites | Locate project root, detect framework, explore existing server logics and frontend patterns, verify .powerpages-site exists (mandatory) |
| Understand requirements | Gathering requirements | Determine user intent, whether one or more server logic files are needed, the methods/features for each item, discover Dataverse custom actions, and any secrets required |
| Fetch latest documentation | Fetching Microsoft Learn docs | Query Microsoft Learn for current Server Logic SDK reference and samples |
| Review implementation plan | Reviewing plan with user | Present plan (server logic inventory, functions, SDK features, external APIs, secrets) and confirm before writing code |
| Implement server logic | Writing server logic code | Determine/create required web roles, create approved .js and .serverlogic.yml files, validate code |
| Configure table permissions | Setting up Dataverse table permissions | (Conditional) Parse .js files for Dataverse tables, launch table-permissions-architect, create permission YAML files |
| Manage secrets and environment variables | Configuring secrets and env vars | (Conditional) Recommend Azure Key Vault, list vaults, store secrets, create environment variables in Dataverse, create site settings with envvar_schema |
| Configure site settings | Configuring site settings | Set up ServerLogic/* site settings if needed |
| Client-side integration | Wiring frontend to server logic | Follow the frontend integration reference, create/update service files as needed, and fully wire the UI to the server logic endpoints |
| Verify and test guidance | Validating and providing test guidance | Final validation, API URLs, CSRF token instructions, testing guide |
| Review and deploy | Reviewing summary and deploying | Present summary, ask about deployment, provide post-deploy guidance |
Mark each task in_progress when starting it and completed when done via TaskUpdate. Use TaskList between phase transitions and before the final summary to confirm there are no incomplete work items left.
---
Begin with Phase 1: Verify Site Exists
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>__PLAN_TITLE__ - __SITE_NAME__</title>
<style>
:root{
--bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --border:#e1dfdd; --border-light:#c8c6c4;
--text:#323130; --text-dim:#605e5c; --text-bright:#201f1e; --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
--pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020; --high:#ca5010; --high-bg:#ca50100a; --high-border:#ca501020;
--purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;
--mono:'Cascadia Code','Consolas',monospace; --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
--radius:8px; --radius-sm:4px; --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
}
*{margin:0;padding:0;box-sizing:border-box;}
html{scroll-behavior:smooth;}
body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}
.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}
.topbar-left{display:flex;align-items:center;gap:14px;}
.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}
.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}
.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}
.layout{display:flex;min-height:calc(100vh - 65px);}
.sidebar{width:200px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}
.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}
.nav-btn:hover{color:var(--text);background:var(--surface2);}
.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}
.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}
.nav-btn.active .nav-icon{opacity:0.9;}
.content{flex:1;padding:32px 40px 72px;max-width:960px;}
.section{display:none;}
.section.active{display:block;animation:fadeIn 0.3s ease;}
@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}
.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}
.section-desc code{color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;font-family:var(--mono);font-size:12px;}
h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}
.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}
.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:24px;}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}
.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;}
.stat-card:nth-child(1)::after{background:var(--accent);}
.stat-card:nth-child(2)::after{background:var(--pass);}
.stat-card:nth-child(3)::after{background:var(--purple);}
.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;}
.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}
.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s,border-color 0.2s;}
.card:hover{box-shadow:var(--shadow-4);}
.principle{display:flex;gap:16px;padding:16px 0;border-bottom:1px solid var(--border);}
.principle:last-child{border-bottom:none;}
.principle-icon{font-size:22px;flex-shrink:0;margin-top:2px;}
.principle-title{font-size:13px;font-weight:700;color:var(--text-bright);margin-bottom:3px;}
.principle-desc{font-size:13px;color:var(--text-dim);line-height:1.65;}
.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}
.chip-row{display:flex;flex-wrap:wrap;gap:6px;}
.role-chip,.logic-chip,.fn-chip{font-size:11px;padding:2px 8px;border-radius:4px;font-weight:600;display:inline-block;}
.role-chip{border:1px solid var(--border);}
.logic-chip{background:var(--surface2);border:1px solid var(--border);color:var(--text);}
.fn-chip{background:var(--accent-bg);border:1px solid var(--accent-border);color:var(--accent);}
.new-badge,.existing-badge,.builtin-badge,.reused-badge,.updated-badge{font-size:9px;font-weight:700;padding:2px 6px;border-radius:3px;margin-left:8px;text-transform:uppercase;letter-spacing:0.5px;}
.new-badge{background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border);}
.existing-badge{background:var(--pass-bg);color:var(--pass);border:1px solid var(--pass-border);}
.builtin-badge{background:var(--surface2);color:var(--text-dim);border:1px solid var(--border);}
.reused-badge{background:var(--pass-bg);color:var(--pass);border:1px solid var(--pass-border);}
.updated-badge{background:var(--high-bg);color:var(--high);border:1px solid var(--high-border);}
.mono{font-family:var(--mono);}
.reason-box{font-size:12px;color:var(--text);background:var(--surface2);padding:10px 14px;border-radius:var(--radius-sm);border-left:2px solid var(--accent);line-height:1.8;}
.reasoning-list{margin:0;padding-left:18px;list-style:disc;}
.reasoning-list li{margin-bottom:2px;}
.reasoning-list li strong{color:var(--text-bright);}
.keyvault-banner{background:linear-gradient(135deg,#0078d408,#5c2d9108);border:1px solid #5c2d9130;border-radius:12px;padding:20px 22px;margin-bottom:22px;display:flex;gap:16px;align-items:flex-start;}
.keyvault-banner .kv-icon{width:40px;height:40px;border-radius:var(--radius);background:linear-gradient(135deg,#0078d4,#5c2d91);display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;color:#fff;}
.keyvault-banner .kv-title{font-size:14px;font-weight:700;color:var(--text-bright);margin-bottom:4px;}
.keyvault-banner .kv-desc{font-size:13px;color:var(--text-dim);line-height:1.65;}
.keyvault-banner .kv-benefits{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:12px;}
.keyvault-banner .kv-benefit{font-size:12px;color:var(--text);display:flex;align-items:center;gap:6px;}
.keyvault-banner .kv-benefit-icon{color:var(--pass);font-size:13px;flex-shrink:0;}
.secrets-section{margin-top:12px;}
.secret-chip{font-size:11px;padding:3px 10px;border-radius:4px;font-weight:600;display:inline-flex;align-items:center;gap:5px;background:#5c2d910a;border:1px solid #5c2d9120;color:#5c2d91;}
.secret-chip .secret-icon{font-size:10px;}
.kv-instructions{margin-top:16px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;}
.kv-instructions summary{font-size:13px;font-weight:700;color:var(--text-bright);cursor:pointer;user-select:none;}
.kv-instructions summary:hover{color:var(--accent);}
.kv-instructions-body{margin-top:14px;}
.kv-method{margin-bottom:16px;}
.kv-method:last-child{margin-bottom:0;}
.kv-method-title{font-size:12px;font-weight:700;color:var(--accent);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px;display:flex;align-items:center;gap:6px;}
.kv-method-title .kv-method-icon{font-size:14px;}
.kv-steps{font-size:12px;color:var(--text);line-height:1.8;padding-left:18px;}
.kv-steps li{margin-bottom:4px;}
.kv-steps code{font-family:var(--mono);font-size:11px;background:var(--surface2);padding:1px 5px;border-radius:3px;}
.kv-cmd-block{background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius-sm);padding:10px 14px;font-family:var(--mono);font-size:11px;line-height:1.7;white-space:pre-wrap;word-break:break-all;margin:8px 0;}
.kv-secret-instructions{margin-top:8px;border-top:1px solid var(--border);padding-top:12px;}
.custom-action-badge{font-size:10px;font-weight:700;padding:3px 8px;border-radius:4px;display:inline-flex;align-items:center;gap:4px;background:#8764b80a;border:1px solid #8764b825;color:#8764b8;text-transform:uppercase;letter-spacing:0.3px;}
.custom-action-detail{font-size:12px;color:var(--text);background:var(--purple-bg);border:1px solid var(--purple-border);padding:10px 14px;border-radius:var(--radius-sm);border-left:2px solid var(--purple);line-height:1.7;margin-top:8px;}
.custom-action-detail code{font-family:var(--mono);font-size:11px;background:var(--surface2);padding:1px 5px;border-radius:3px;}
.fn-list{display:grid;gap:10px;margin-top:12px;}
.fn-item{background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius-sm);padding:12px 14px;}
.meta-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px;}
@media(max-width:768px){
.sidebar{display:none;}
.content{padding:20px 16px 72px;}
.stats-grid,.meta-grid{grid-template-columns:1fr;}
}
</style>
</head>
<body>
<div id="mainApp">
<div class="topbar">
<div class="topbar-left">
<img class="logo" src="./power-pages-icon.png" alt="Power Pages" />
<div>
<div class="topbar-title">__PLAN_TITLE__</div>
<div class="topbar-sub">__SITE_NAME__</div>
</div>
</div>
<div class="topbar-sub" id="topbarCount"></div>
</div>
<div class="layout">
<div class="sidebar">
<button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span> Overview</button>
<button class="nav-btn" data-tab="roles"><span class="nav-icon">◈</span> Web Roles</button>
<button class="nav-btn" data-tab="serverlogic"><span class="nav-icon">▦</span> Server Logic</button>
</div>
<div class="content">
<div class="section active" id="tab-overview">
<h2>Plan Overview</h2>
<p class="section-desc">Server logic implementation plan for <code>__SITE_NAME__</code></p>
<div class="summary-box" id="summaryBox">__SUMMARY__</div>
<div class="stats-grid">
<div class="stat-card"><div class="stat-num" style="color:var(--accent)" id="statTotal">0</div><div class="stat-label">Server Logic Items</div></div>
<div class="stat-card"><div class="stat-num" style="color:var(--pass)" id="statCreate">0</div><div class="stat-label">New / Create</div></div>
<div class="stat-card"><div class="stat-num" style="color:var(--purple)" id="statReuse">0</div><div class="stat-label">Reused</div></div>
</div>
<div id="keyvaultBanner"></div>
<div class="card">
<div class="field-label">Status Summary</div>
<div class="chip-row" id="statusSummary"></div>
</div>
<h3>Design Rationale</h3>
<div id="rationaleContainer"></div>
</div>
<div class="section" id="tab-roles">
<h2>Web Roles</h2>
<p class="section-desc" id="rolesDesc"></p>
<div id="rolesContainer"></div>
</div>
<div class="section" id="tab-serverlogic">
<h2>Server Logic</h2>
<p class="section-desc" id="serverLogicDesc"></p>
<div id="serverLogicContainer"></div>
</div>
</div>
</div>
</div>
<script>
const WEB_ROLES = __WEB_ROLES_DATA__;
const SERVER_LOGICS = __SERVER_LOGICS_DATA__;
const RATIONALE = __RATIONALE_DATA__;
const SECRETS = __SECRETS_DATA__;
function esc(str) { const d = document.createElement('div'); d.textContent = str; return d.innerHTML; }
// Key Vault banner rendering
const kvBanner = document.getElementById('keyvaultBanner');
if (SECRETS && SECRETS.useKeyVault && SECRETS.secrets && SECRETS.secrets.length > 0) {
kvBanner.innerHTML = `
<div class="keyvault-banner">
<div class="kv-icon">🔑</div>
<div style="flex:1;">
<div class="kv-title">Azure Key Vault</div>
<div class="kv-desc">Secrets for this implementation will be stored in Azure Key Vault${SECRETS.vaultName ? ' (<span class="mono">' + esc(SECRETS.vaultName) + '</span>)' : ''}, keeping sensitive values out of source code and Dataverse environment variables.</div>
<div class="keyvault-banner kv-benefits" style="border:none;padding:0;margin-top:12px;background:none;">
<div class="kv-benefit"><span class="kv-benefit-icon">✓</span> Secrets never stored in code or config files</div>
<div class="kv-benefit"><span class="kv-benefit-icon">✓</span> Centralized access control via Azure RBAC</div>
<div class="kv-benefit"><span class="kv-benefit-icon">✓</span> Automatic secret rotation support</div>
<div class="kv-benefit"><span class="kv-benefit-icon">✓</span> Audit logging for all secret access</div>
</div>
<div style="margin-top:12px;">
<div class="field-label">Secrets (${SECRETS.secrets.length})</div>
<div class="chip-row" style="margin-top:4px;">
${SECRETS.secrets.map(s => '<span class="secret-chip"><span class="secret-icon">🔒</span> ' + esc(s.name) + '</span>').join('')}
</div>
</div>
</div>
</div>` + renderKvInstructions();
}
function renderKvInstructions() {
const vaultName = SECRETS.vaultName ? esc(SECRETS.vaultName) : '<your-vault-name>';
const secretRows = SECRETS.secrets.map((s, i) => {
const sn = esc(s.name);
return `<li><strong>${sn}</strong>${s.purpose ? ' — ' + esc(s.purpose) : ''}` +
`<div class="kv-cmd-block">printf '%s' '<YOUR_SECRET_VALUE>' | az keyvault secret set \\
--vault-name "${vaultName}" \\
--name "${sn}" \\
--value @-</div></li>`;
}).join('');
return `
<details class="kv-instructions" open>
<summary>⚙ How to Set Secrets in Azure Key Vault</summary>
<div class="kv-instructions-body">
<div class="kv-method">
<div class="kv-method-title"><span class="kv-method-icon">〉</span> Option A — Azure CLI</div>
<ol class="kv-steps">
<li>Open a terminal and ensure you are logged in: <code>az login --allow-no-subscriptions</code> (works without an Azure subscription if you have vault data-plane RBAC, e.g. <em>Key Vault Secrets Officer</em>)</li>
${secretRows}
</ol>
<div style="font-size:11px;color:var(--text-dim);margin-top:6px;">Each command prints a JSON object containing a <code>id</code> field — that is the Secret Identifier URI you will need.</div>
</div>
<div class="kv-method">
<div class="kv-method-title"><span class="kv-method-icon">☍</span> Option B — Azure Portal</div>
<ol class="kv-steps">
<li>Go to <a href="https://portal.azure.com" target="_blank" rel="noopener">portal.azure.com</a></li>
<li>Search for <strong>Key vaults</strong> in the top search bar and select it</li>
<li>Select the Key Vault: <strong>${vaultName}</strong></li>
<li>In the left menu under <strong>Objects</strong>, click <strong>Secrets</strong></li>` +
SECRETS.secrets.map(s => {
const sn = esc(s.name);
return `
<li>Click <strong>+ Generate/Import</strong> and fill in:
<ul style="margin-top:4px;">
<li>Upload options: <strong>Manual</strong></li>
<li>Name: <code>${sn}</code></li>
<li>Secret value: paste your actual value</li>
</ul>
Then click <strong>Create</strong></li>`;
}).join('') + `
<li>After creating each secret, click its name → click the current version → copy the <strong>Secret Identifier</strong> URI</li>
</ol>
<div style="font-size:11px;color:var(--text-dim);margin-top:6px;">The Secret Identifier looks like <code>https://${vaultName}.vault.azure.net/secrets/<name>/<version></code></div>
</div>
</div>
</details>`;
}
function getCustomActionMarkup(item) {
if (!item.customAction) return '';
const ca = item.customAction;
const bindingLabel = ca.binding === 'entity' ? 'Bound to <code>' + esc(ca.boundEntity || '') + '</code>' :
ca.binding === 'entityCollection' ? 'Bound to <code>' + esc(ca.boundEntity || '') + '</code> collection' : 'Unbound';
const typeLabel = ca.type === 'function' ? 'Function (GET)' : 'Action (POST)';
return '<div style="margin-top:12px;"><div class="field-label">Wraps Dataverse Custom Action</div>' +
'<div class="custom-action-detail">' +
'<strong>' + esc(ca.displayName || ca.name) + '</strong>' +
' — <code>' + esc(ca.name) + '</code>' +
'<br/>' + typeLabel + ' • ' + bindingLabel +
'</div></div>';
}
function getCustomActionBadge(item) {
if (!item.customAction) return '';
return ' <span class="custom-action-badge">⚙ Custom Action</span>';
}
function getSecretsMarkup(serverLogicId) {
if (!SECRETS || !SECRETS.useKeyVault || !SECRETS.secrets) return '';
const matched = SECRETS.secrets.filter(s => s.serverLogicId === serverLogicId);
if (matched.length === 0) return '';
return '<div class="secrets-section"><div class="field-label">Secrets (Azure Key Vault)</div><div class="chip-row" style="margin-top:4px;">' +
matched.map(s => '<span class="secret-chip"><span class="secret-icon">🔒</span> ' + esc(s.name) + ' — ' + esc(s.purpose || '') + '</span>').join('') +
'</div></div>';
}
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
});
});
function getRole(id) {
return WEB_ROLES.find(role => role.id === id) || { id, name: id, desc: '', builtin: false, isNew: false, color: '#8890a4' };
}
function getAssignedRoleDetails(item) {
return (item.webRoles || []).map(entry => {
if (typeof entry === 'string') {
return { id: entry, reasoning: '' };
}
return { id: entry.id, reasoning: entry.reasoning || '' };
});
}
function getStatusBadge(status) {
if (status === 'create') return '<span class="new-badge">PROPOSED</span>';
if (status === 'reuse') return '<span class="reused-badge">REUSED</span>';
if (status === 'update') return '<span class="updated-badge">UPDATE</span>';
return '<span class="existing-badge">EXISTING</span>';
}
function getStatusLabel(status) {
if (status === 'create') return 'Proposed';
if (status === 'reuse') return 'Reused';
if (status === 'update') return 'Updated';
return 'Existing';
}
document.getElementById('topbarCount').textContent =
SERVER_LOGICS.length + ' server logic item' + (SERVER_LOGICS.length !== 1 ? 's' : '');
const createCount = SERVER_LOGICS.filter(item => item.status === 'create').length;
const reuseCount = SERVER_LOGICS.filter(item => item.status === 'reuse').length;
document.getElementById('statTotal').textContent = SERVER_LOGICS.length;
document.getElementById('statCreate').textContent = createCount;
document.getElementById('statReuse').textContent = reuseCount;
const statusSummary = document.getElementById('statusSummary');
statusSummary.innerHTML = SERVER_LOGICS.length
? SERVER_LOGICS.map(item => `<span class="logic-chip">${item.displayName || item.name} ${getStatusBadge(item.status)}</span>`).join('')
: '<span class="logic-chip">No server logic items defined</span>';
const rationaleContainer = document.getElementById('rationaleContainer');
rationaleContainer.innerHTML = RATIONALE.map(r => `
<div class="principle">
<div class="principle-icon">${r.icon}</div>
<div>
<div class="principle-title">${r.title}</div>
<div class="principle-desc">${r.desc}</div>
</div>
</div>
`).join('');
const proposedRoles = WEB_ROLES.filter(r => r.isNew).length;
const builtinRoles = WEB_ROLES.filter(r => r.builtin).length;
const existingRoles = WEB_ROLES.filter(r => !r.builtin && !r.isNew).length;
const roleParts = [];
if (builtinRoles > 0) roleParts.push(builtinRoles + ' built-in');
if (existingRoles > 0) roleParts.push(existingRoles + ' existing');
if (proposedRoles > 0) roleParts.push(proposedRoles + ' proposed');
document.getElementById('rolesDesc').textContent =
WEB_ROLES.length + ' role' + (WEB_ROLES.length !== 1 ? 's' : '') +
(roleParts.length ? ' — ' + roleParts.join(', ') : '') + '.';
const rolesContainer = document.getElementById('rolesContainer');
rolesContainer.innerHTML = WEB_ROLES.map(role => {
const assigned = SERVER_LOGICS.filter(item => getAssignedRoleDetails(item).some(entry => entry.id === role.id));
const assignedMarkup = assigned.length
? assigned.map(item => `<span class="logic-chip">${item.displayName || item.name}</span>`).join('')
: '<span style="font-size:11px;color:var(--text-dim);font-style:italic;">Not assigned</span>';
return `<div class="card"${role.isNew ? ' style="background:var(--accent-bg);border-color:var(--accent-border);"' : ''}>
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;">
<div style="display:flex;align-items:flex-start;gap:10px;">
<div style="width:10px;height:10px;border-radius:50%;background:${role.color || '#8890a4'};flex-shrink:0;margin-top:6px;"></div>
<div>
<span style="font-size:14px;font-weight:700;color:var(--text-bright)">${role.name}</span>
${role.builtin ? '<span class="builtin-badge">BUILT-IN</span>' : role.isNew ? '<span class="new-badge">PROPOSED</span>' : '<span class="existing-badge">EXISTING</span>'}
<div style="font-size:12px;color:var(--text-dim);margin-top:2px;">${role.desc || ''}</div>
</div>
</div>
</div>
<div style="margin-top:12px;">
<div class="field-label">Assigned Server Logic</div>
<div class="chip-row">${assignedMarkup}</div>
</div>
</div>`;
}).join('');
const createLogicCount = SERVER_LOGICS.filter(item => item.status === 'create').length;
const reuseLogicCount = SERVER_LOGICS.filter(item => item.status === 'reuse').length;
const updateLogicCount = SERVER_LOGICS.filter(item => item.status === 'update').length;
const logicParts = [];
if (createLogicCount > 0) logicParts.push(createLogicCount + ' proposed');
if (reuseLogicCount > 0) logicParts.push(reuseLogicCount + ' reused');
if (updateLogicCount > 0) logicParts.push(updateLogicCount + ' updated');
document.getElementById('serverLogicDesc').textContent =
SERVER_LOGICS.length + ' server logic item' + (SERVER_LOGICS.length !== 1 ? 's' : '') +
(logicParts.length ? ' — ' + logicParts.join(', ') : '') + '.';
const serverLogicContainer = document.getElementById('serverLogicContainer');
serverLogicContainer.innerHTML = SERVER_LOGICS.map(item => {
const roles = getAssignedRoleDetails(item).map(entry => ({ ...getRole(entry.id), reasoning: entry.reasoning }));
const roleMarkup = roles.length
? roles.map(role => `
<div class="fn-item">
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
<div style="font-size:13px;font-weight:700;color:var(--text-bright);">${role.name}</div>
<div class="role-chip" style="background:${role.color || '#8890a4'}18;color:${role.color || '#8890a4'};">Assigned Role</div>
</div>
<div style="font-size:12px;color:var(--text-dim);margin-top:8px;">${role.reasoning || 'No role reasoning provided.'}</div>
</div>
`).join('')
: '<div class="fn-item">No web roles assigned.</div>';
const fnMarkup = (item.functions || []).map(fn => `
<div class="fn-item">
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
<div style="font-size:13px;font-weight:700;color:var(--text-bright);"><span class="mono">${fn.name}()</span></div>
<div class="fn-chip">${fn.purpose}</div>
</div>
<div style="font-size:12px;color:var(--text-dim);margin-top:8px;">${fn.reasoning || ''}</div>
</div>
`).join('');
return `<div class="card"${item.status === 'create' ? ' style="background:var(--accent-bg);border-color:var(--accent-border);"' : ''}>
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;">
<div>
<span style="font-size:14px;font-weight:700;color:var(--text-bright)">${item.displayName || item.name}</span>
${getStatusBadge(item.status)}${getCustomActionBadge(item)}
<div style="font-size:12px;color:var(--text-dim);margin-top:4px;"><span class="mono">${item.name}</span>${item.apiUrl ? ' • <span class="mono">' + item.apiUrl + '</span>' : ''}</div>
</div>
</div>
<div class="meta-grid">
<div>
<div class="field-label">Status</div>
<div>${getStatusLabel(item.status)}</div>
</div>
<div>
<div class="field-label">API URL</div>
<div class="mono" style="font-size:11px;word-break:break-word;">${item.apiUrl || 'Not provided'}</div>
</div>
</div>
${getCustomActionMarkup(item)}
<div style="margin-top:12px;">
<div class="field-label">Reasoning</div>
<div class="reason-box">${item.rationale || 'No rationale provided.'}</div>
</div>
<div style="margin-top:12px;">
<div class="field-label">Assigned Web Roles and Why</div>
<div class="fn-list">${roleMarkup}</div>
</div>
<div style="margin-top:12px;">
<div class="field-label">Functions</div>
<div class="fn-list">${fnMarkup || '<div class="fn-item">No functions proposed.</div>'}</div>
</div>
${getSecretsMarkup(item.id || item.name)}
</div>`;
}).join('');
</script>
<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>
</body>
</html>
Frontend Integration Reference
Use this reference in Phase 9 of add-server-logic to decide how the site's frontend should call one or more server logic endpoints.
Goal
Choose the lightest integration approach that matches the existing codebase patterns. Reuse established utilities when possible. Only introduce new helpers when the site does not already have a consistent API calling pattern.
Frontend integration is not complete when only a helper or service file exists. The endpoint must be wired into the actual user experience unless the user explicitly asks for backend-only work.
Decision Order
1. Reuse an existing service layer or API wrapper if one already exists. 2. Reuse existing CSRF token handling patterns if the site already has them. 3. Create a new helper only when no suitable pattern exists. 4. Group related server logic endpoints into a coherent service module when multiple endpoints are being introduced together. 5. Add framework-specific hooks/composables/services only when the codebase already uses those abstractions.
Existing Pattern Detection
Look for:
shell.safeAjaxusage in legacy or jQuery-based sites- Shared fetch wrappers such as
powerPagesApi.ts,apiClient.ts, or framework-specific service modules - Existing CSRF token helpers built around
/_layout/tokenhtml - Existing hooks/composables/services that wrap backend calls with loading and error state
Server Logic Response Envelope
Server logic endpoints return responses in a standard JSON envelope:
{
"requestId": "<activity-guid>",
"success": true,
"serverLogicName": "<endpoint-name>",
"data": "<string returned by your function>",
"error": null
}datacontains the string returned by the invoked function (e.g., theJSON.stringify(...)result). Parse it withJSON.parse(response.data)when the function returns serialized JSON.- On failure,
successisfalse,dataisnull, anderrorcontains the error message. requestIdis the server-side activity GUID — useful for correlating withServer.Loggeroutput in diagnostics.
All frontend helpers and service wrappers should unwrap .data from this envelope rather than treating the entire response body as the function's return value.
Dataverse Connector Response Format
When a server logic function returns the raw result of a Server.Connector.Dataverse.* method, the shape that reaches the client is double-wrapped. This is the most common source of bugs in client integration code.
Reference: Microsoft Learn — How to interact with Dataverse tables using server logic.
Shape of Server.Connector.Dataverse.* return values
The Dataverse connector methods (RetrieveRecord, RetrieveMultipleRecords, CreateRecord, UpdateRecord, DeleteRecord, InvokeCustomApi) return an object that contains the raw Dataverse HTTP response. When that object is returned from the server logic function, it is serialized into the envelope's data string. Concretely the client sees:
{
"requestId": "…",
"success": true,
"serverLogicName": "dataverse-crud-operations",
"data": "{\"Body\":\"{\\\"@odata.context\\\":\\\"…\\\",\\\"value\\\":[{…}, {…}]}\",\"StatusCode\":200,\"Headers\":{…}}",
"error": null
}To reach the Dataverse records the client must parse twice:
const envelope = responseBody; // server logic envelope
const outer = JSON.parse(envelope.data); // { Body: "<json string>", StatusCode, Headers }
const body = JSON.parse(outer.Body); // { "@odata.context": "...", value: [...] } (for RetrieveMultipleRecords)
const records = body.value; // the actual arrayFor RetrieveRecord, body is the single record object (no value array). For CreateRecord, the new record's GUID is returned in the HTTP response header entityid — read it with xhr.getResponseHeader('entityid') (jQuery/safeAjax) or response.headers.get('entityid') (fetch).
Three approaches — pick one and apply it consistently
For Dataverse-backed server logic there are three valid response shapes: raw passthrough (return the connector result as-is and parse it twice on the client), server envelope that still wraps the connector result (preserve the connector metadata but add an outer status wrapper), and fully normalized (unwrap everything server-side and return only what the UI needs). Pick one shape for each endpoint and apply it consistently across the server logic and the frontend integration.
Approach A — Return the raw Dataverse response, double-parse on the client
This is the pattern shown in the Microsoft Learn sample. Useful when the server logic is a thin CRUD passthrough driven by entitySetName query parameters.
Server logic:
function get() {
try {
Server.Logger.Log("GET called");
const entitySetName = Server.Context.QueryParameters["entitySetName"];
const additionalParameters = Server.Context.QueryParameters["additionalParameters"];
if (!Server.Context.QueryParameters["id"]) {
return Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName, additionalParameters);
}
const id = Server.Context.QueryParameters["id"];
return Server.Connector.Dataverse.RetrieveRecord(entitySetName, id, additionalParameters);
} catch (err) {
Server.Logger.Error("GET failed: " + err.message);
return JSON.stringify({ status: "error", method: "GET", message: err.message });
}
}Client (matches the Microsoft Learn sample exactly):
ajaxCall('Loading...', {
type: 'GET',
url: '/_api/serverlogics/dataverse-crud-operations?entitySetName=contacts&additionalParameters=$select=fullname,firstname,lastname,emailaddress1,telephone1',
contentType: 'application/json'
}).done(res => {
const outer = JSON.parse(res.data);
const body = JSON.parse(outer.Body);
const rows = (body.value || []).map(r => ({ ...r, id: r.contactid }));
render(rows);
});For CreateRecord the new id comes from a response header:
success: (res, status, xhr) => {
record.id = xhr.getResponseHeader('entityid');
addRecord(record);
}Approach B — Server envelope that still wraps the connector result
Use this when you want to add a stable top-level wrapper (e.g. { status, data }) to every response but keep the raw connector result inside so generic handling code can read Body/StatusCode/Headers if needed.
Server logic:
function get() {
try {
Server.Logger.Log("GET called");
const entitySetName = Server.Context.QueryParameters["entitySetName"];
const result = Server.Connector.Dataverse.RetrieveMultipleRecords(entitySetName);
return JSON.stringify({ status: "success", data: result });
} catch (err) {
Server.Logger.Error("GET failed: " + err.message);
return JSON.stringify({ status: "error", message: err.message });
}
}Client — note the extra data layer before reaching Body:
const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(
'/_api/serverlogics/contacts-crud',
{ method: 'GET' }
);
if (!envelope) throw new Error('Empty response from contacts-crud');
if (!envelope.success) throw new Error(envelope.error ?? 'Failed');
if (envelope.data == null) throw new Error('Missing response data from contacts-crud');
const payload = JSON.parse(envelope.data) as { status: string; data: { Body: string; StatusCode: number; Headers: Record<string, string> } };
const outer = payload.data; // connector result still wrapped here
const body = JSON.parse(outer.Body); // { "@odata.context": "...", value: [...] }
const records = body.value;Do not use the Approach A parsing path (JSON.parse(envelope.data) → JSON.parse(outer.Body)) against this shape — that skips the payload.data unwrap and reads Body off the wrong object.
Approach C — Unwrap server-side and return a clean shape (recommended for most new code)
Return a stable, documented shape from the function. Client code then only unwraps the outer envelope and parses data once. Prefer this when the server logic serves a specific feature (not a generic CRUD passthrough).
Server logic:
function get() {
try {
Server.Logger.Log("getContacts GET called");
const dvResponse = Server.Connector.Dataverse.RetrieveMultipleRecords(
"contacts",
"?$select=contactid,firstname,lastname,emailaddress1,telephone1"
);
const body = JSON.parse(dvResponse.Body);
const contacts = (body.value || []).map(r => ({
id: r.contactid,
firstName: r.firstname,
lastName: r.lastname,
email: r.emailaddress1,
phone: r.telephone1
}));
return JSON.stringify({ status: "success", contacts });
} catch (err) {
Server.Logger.Error("getContacts GET failed: " + err.message);
return JSON.stringify({ status: "error", message: err.message });
}
}Client:
const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(
'/_api/serverlogics/getContacts',
{ method: 'GET' }
);
if (!envelope) throw new Error('Empty response from getContacts');
if (!envelope.success) throw new Error(envelope.error ?? 'Failed');
if (envelope.data == null) throw new Error('Missing response data from getContacts');
const payload = JSON.parse(envelope.data) as { status: string; contacts: Contact[] };
return payload.contacts;For writes, return the new id from the server logic explicitly rather than relying on the entityid header:
const dvResponse = Server.Connector.Dataverse.CreateRecord("contacts", JSON.stringify(body));
const newId = dvResponse.Headers && dvResponse.Headers.entityid;
return JSON.stringify({ status: "success", id: newId });When the response shape is unknown
If the frontend integration is failing because the exact Dataverse response shape is unclear for a specific operation (custom actions, bound actions, non-standard query options), invoke /test-site against the deployed site. The test-site skill captures live /_api/serverlogics/ responses and reports the exact envelope.data and (when present) outer.Body shapes so the frontend integration can be written against the real response, not a guessed one.
Key points for Dataverse-backed server logic
Server.Connector.Dataverse.*methods return an object withBody(a JSON string),StatusCode, andHeaders. They are synchronous — do notawaitthem.- When the server logic returns that object directly, the client must
JSON.parse(res.data)to get the outer object andJSON.parse(outer.Body)to get the Dataverse payload. RetrieveMultipleRecordspayloads have avaluearray;RetrieveRecordpayloads are a single record object.CreateRecordreturns the new record id via theentityidHTTP response header — not in the body.- For non-trivial features, prefer unwrapping
Bodyinside the server logic and returning a feature-specific shape (Approach C) so the client integration is obvious and stable.
Recommended Approaches
1. Sites Using shell.safeAjax
If the site already uses shell.safeAjax, create thin wrappers around it instead of introducing a new fetch abstraction.
Use this shape:
function callServerLogic(method, endpointName, queryParams, body) {
return new Promise((resolve, reject) => {
let url = `/_api/serverlogics/${endpointName}`;
if (queryParams) {
url += '?' + new URLSearchParams(queryParams).toString();
}
shell.safeAjax({
type: method,
url,
contentType: 'application/json',
data: body ? JSON.stringify(body) : undefined,
success: function (res) { resolve(res); },
error: function (xhr) { reject(xhr); }
});
});
}2. SPA Sites with an Existing API Wrapper
If the site already has a helper such as powerPagesFetch, reuse it and add one or more thin server logic functions on top.
Use this shape:
import { powerPagesFetch } from '../shared/powerPagesApi';
export async function callServerLogic<T = unknown>(
endpointName: string,
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
params?: Record<string, string>,
body?: unknown
): Promise<T> {
const url = params
? `/_api/serverlogics/${endpointName}?${new URLSearchParams(params)}`
: `/_api/serverlogics/${endpointName}`;
const envelope = await powerPagesFetch<{ data: string | null; success: boolean; error: string | null }>(url, {
method,
body: body ? JSON.stringify(body) : undefined,
});
if (!envelope) {
throw new Error(`Empty response from ${endpointName}`);
}
if (!envelope.success) {
throw new Error(envelope.error ?? 'Server logic call failed');
}
if (envelope.data == null) {
throw new Error(`Missing response data from ${endpointName}`);
}
return JSON.parse(envelope.data) as T;
}3. SPA Sites Without an Existing API Wrapper
If the site has no established API client, create a lightweight CSRF-aware helper and keep it narrowly scoped.
Use this shape:
async function getCsrfToken(): Promise<string> {
const response = await fetch('/_layout/tokenhtml');
const html = await response.text();
const match = html.match(/value="([^"]+)"/);
if (!match) {
throw new Error('Failed to get CSRF token');
}
return match[1];
}
export async function callServerLogic<T = unknown>(
endpointName: string,
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
params?: Record<string, string>,
body?: unknown
): Promise<T> {
const url = params
? `/_api/serverlogics/${endpointName}?${new URLSearchParams(params)}`
: `/_api/serverlogics/${endpointName}`;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
// CSRF token is required for non-GET requests only
if (method !== 'GET') {
headers['__RequestVerificationToken'] = await getCsrfToken();
}
const response = await fetch(url, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
throw new Error(`Server logic call failed: ${response.status}`);
}
return response.json();
}Multiple Server Logic Endpoints
When a single user request results in multiple server logic endpoints:
- Prefer one shared helper plus endpoint-specific wrapper functions
- Group related endpoints into one service module when they belong to the same feature area
- Keep endpoint names explicit rather than hiding them behind vague generic method names
- Share token handling and low-level request plumbing; keep business semantics in endpoint-specific functions
Example:
export const orderServerLogic = {
getSummary: () => callServerLogic('order-summary', 'GET'),
submitOrder: (payload: unknown) => callServerLogic('order-submit', 'POST', undefined, payload),
};Framework-Specific Abstractions
Only add hooks/composables/services with loading/error state when the site already uses that pattern.
- React:
useServerLogicor feature-specific hooks such asuseOrderSummary - Vue: composables such as
useServerLogic - Angular: injectable services returning observables or promises following existing conventions
- Astro: plain service modules are usually sufficient
Component Updates
When integrating the new endpoints into existing UI:
- Make the feature reachable from the real UI flow — a button, form submission, page load, filter action, or other user-triggered path
- Replace mock data or placeholder URLs only when they clearly map to the approved server logic plan
- Preserve existing loading, empty, and error states when present
- Add loading/error handling if the component currently has none and the codebase pattern supports it
- Avoid broad refactors unrelated to the server logic integration
Output Expectations
Phase 9 should leave behind:
- The frontend helper or service files needed to call the server logic endpoints
- Any framework-specific wrappers that match the site's existing architecture
- Updated components/pages/forms/actions wired to the new endpoints when the scope includes that work
- A summary of which frontend files were created or changed and which endpoints they call
Server Logic Documentation Discovery
Power Pages Server Logic is a preview feature with documentation that may expand or change at any time. Never rely on a hardcoded list of URLs. Always search Microsoft Learn dynamically to discover all available pages.
Discovery Strategy
Step 1: Search to discover pages
mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search("Power Pages Server Logic")Step 2: Collect unique page URLs
From all search results, extract unique contentUrl values. Keep pages that match:
learn.microsoft.com/.../power-pages/configure/server-logic*learn.microsoft.com/.../power-pages/configure/server-objects*learn.microsoft.com/.../power-pages/configure/author-server-logic*
Discard: release-plan announcements, blog posts, unrelated configuration pages.
Step 3: Classify and fetch
Classify each discovered page into one of these categories:
| Category | Always fetch? | How to identify |
|---|---|---|
| Core reference | Yes | Overview page, authoring guide, SDK/server objects reference |
| How-to guide | If relevant | Tutorials for specific scenarios (Dataverse, external APIs, Azure Functions, Graph, etc.) |
| New/unknown | If relevant | Any page not matching known patterns — read it to learn about new capabilities |
Step 4: Fetch in parallel
Fetch all core reference pages plus relevant how-to guides in parallel using mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch.
Known Pages (as of March 2026)
These are pages that existed when this reference was last updated. They serve as a baseline — the search step above will discover these plus any new ones:
| Page | URL |
|---|---|
| Overview | https://learn.microsoft.com/en-us/power-pages/configure/server-logic-overview |
| Author server logic | https://learn.microsoft.com/en-us/power-pages/configure/author-server-logic |
| Server objects (SDK) | https://learn.microsoft.com/en-us/power-pages/configure/server-objects |
| Dataverse operations | https://learn.microsoft.com/en-us/power-pages/configure/server-logic-operations |
| External services | https://learn.microsoft.com/en-us/power-pages/configure/server-logic-external-services |
| Azure Function | https://learn.microsoft.com/en-us/power-pages/configure/server-logic-azure-function |
| Graph & SharePoint | https://learn.microsoft.com/en-us/power-pages/configure/server-logic-graph-sharepoint |
If the search discovers pages not in this table, those are new additions — fetch and use them.
What to Extract from the Docs
For the current task, capture:
- All SDK method signatures, parameter types, and return types
- Supported HTTP methods and function signatures
- Site settings and their defaults
- Security model details (web roles, table permissions, CSRF)
- Client-side calling patterns and response formats
- Any new methods, changed behaviors, or breaking changes
Use-Case Mapping
When the user's requirements are known, fetch any additional pages that match the scenario:
| User needs | Look for pages about |
|---|---|
| Dataverse CRUD | Dataverse operations, table interactions |
| External API calls | External services, HttpClient |
| Azure Functions | Azure Function HTTP trigger |
| Microsoft Graph / SharePoint | Graph API, SharePoint integration |
| Any other scenario | Any matching tutorial or how-to page |
If the search results contain unfamiliar but relevant pages, read them — they may document new capabilities.
Code Samples
Also search for current samples:
mcp__plugin_power-pages_microsoft-learn__microsoft_code_sample_search("Power Pages server logic")Known SDK Baseline
Use this as a baseline only. If Microsoft Learn differs, Microsoft Learn wins.
- Server.Logger:
Log(message),Warn(message),Error(message) - Server.Context:
QueryParameters["key"],Headers["key"],Body,HttpMethod,Url,ActivityId,FunctionName,ServerLogicName - Server.Connector.HttpClient:
GetAsync(url, headers?),PostAsync(url, jsonBody, headers?, contentType?),PatchAsync(url, jsonBody, headers?, contentType?),PutAsync(url, jsonBody, headers?, contentType?),DeleteAsync(url, headers?) - Server.Connector.Dataverse:
CreateRecord(entitySetName, payload),RetrieveRecord(entitySetName, id, options),RetrieveMultipleRecords(entitySetName, options),UpdateRecord(entitySetName, id, payload),DeleteRecord(entitySetName, id),InvokeCustomApi(httpMethod, url, payload) - Server.User:
fullname,firstname,lastname,emailaddress1,contactid,Roles,Token, and many other contact properties - Server.Website:
adx_websiteid,adx_name,adx_primarydomainname,adx_defaultlanguage, etc. - Server.Sitesetting:
Get(name) - Server.EnvironmentVariable:
get(name)— reads Dataverse environment variable values directly (alternative to reading via site settings withenvvar_schema)
When new SDK members or changed patterns are discovered, use them and record the differences in the implementation plan.
Server Logic Plan Data Format
Reference document for generating the HTML server logic plan using render-serverlogic-plan.js.
Determine Output Location
- If working in the context of a website (a project root with
powerpages.config.jsonexists): write the file to<PROJECT_ROOT>/docs/serverlogic-plan.html - Otherwise: write to the system temp directory (
[System.IO.Path]::GetTempPath())
Prepare Data
Write a temporary JSON data file with these keys:
{
"SITE_NAME": "The site name from powerpages.config.json or the project folder",
"PLAN_TITLE": "A short plan title such as 'Server Logic Plan'",
"SUMMARY": "A 1-2 sentence summary of what this endpoint will do and why",
"WEB_ROLES_DATA": [],
"SERVER_LOGICS_DATA": [],
"RATIONALE_DATA": [],
"SECRETS_DATA": null
}WEB_ROLES_DATA Format
[
{
"id": "role-authenticated",
"name": "Authenticated Users",
"desc": "Built-in role for signed-in users.",
"builtin": true,
"isNew": false,
"color": "#8890a4"
}
]SERVER_LOGICS_DATA Format
[
{
"id": "ticket-dashboard",
"name": "ticket-dashboard",
"displayName": "Ticket Dashboard",
"status": "create",
"apiUrl": "https://<site-url>/_api/serverlogics/ticket-dashboard",
"webRoles": [
{
"id": "role-authenticated",
"reasoning": "Authenticated users need access because the dashboard is part of the signed-in support workspace."
}
],
"rationale": "Keeps Dataverse queries and shaping logic off the client while enforcing role-scoped access.",
"functions": [
{
"name": "get",
"purpose": "Return dashboard metrics",
"reasoning": "The dashboard is read-heavy, so GET keeps the endpoint simple and cache-friendly."
}
]
}
]Use status values like create, update, or reuse.
Each webRoles entry should explain why that specific role is assigned to that specific server logic.
Each functions entry should explain why that specific function is being implemented for that specific server logic.
When a server logic item wraps a Dataverse custom action (mapped in Phase 2.1.2), include a customAction object:
{
"id": "calculate-discount",
"name": "calculate-discount",
"displayName": "Calculate Discount",
"status": "create",
"customAction": {
"name": "new_CalculateDiscount",
"displayName": "Calculate Discount",
"type": "action",
"binding": "entity",
"boundEntity": "salesorder"
},
"...": "other fields as above"
}| Field | Description |
|---|---|
customAction | (Optional) Present only when the server logic wraps a Dataverse custom action |
customAction.name | The unique name of the custom action (used in InvokeCustomApi) |
customAction.displayName | Human-readable display name |
customAction.type | action (POST) or function (GET) |
customAction.binding | unbound, entity, or entityCollection |
customAction.boundEntity | (Optional) Logical name of the bound entity, if applicable |
When customAction is present, the plan HTML renders a badge on the server logic card indicating that it wraps an existing Dataverse custom action. When customAction is absent or null, no badge is shown.
RATIONALE_DATA Format
[
{
"icon": "🛡️",
"title": "Why this structure",
"desc": "Separate server logic files keep responsibilities focused and make role assignment clearer."
}
]The overview tab renders these rationale items in the same style as the other Power Pages plan documents.
SECRETS_DATA Format
Set to null when the server logic does not require any secrets. When the user has chosen to use Azure Key Vault, provide an object:
{
"useKeyVault": true,
"vaultName": "contoso-keyvault",
"secrets": [
{
"name": "ExchangeRateApiKey",
"purpose": "API key for the exchange rate service",
"siteSetting": "ExternalApi/ExchangeRateApiKey",
"serverLogicId": "exchange-rate"
}
]
}| Field | Description |
|---|---|
useKeyVault | true if the user chose Azure Key Vault; omit or set false for direct env vars |
vaultName | (Optional) Name of the selected/created Key Vault — shown in the plan if known |
secrets[].name | Descriptive name for the secret (e.g., ExchangeRateApiKey) |
secrets[].purpose | Why the secret is needed |
secrets[].siteSetting | The site setting name the server logic reads via Server.Sitesetting.Get() |
secrets[].serverLogicId | The id (or name) of the server logic item that uses this secret — links the secret to the correct card in the plan |
When useKeyVault is true, the plan HTML renders a prominent banner in the Overview tab explaining that secrets are stored in Azure Key Vault and why it matters (centralized access control, audit logging, rotation support, secrets never in code). Each server logic card also shows the secrets it depends on.
When SECRETS_DATA is null or useKeyVault is false, the banner and per-card secrets sections are hidden.
Render the HTML File
Do not write the HTML manually. Use the render script:
node "${PLUGIN_ROOT}/scripts/render-serverlogic-plan.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"The render script refuses to overwrite existing files. Before calling it, check if the default output path (<PROJECT_ROOT>/docs/serverlogic-plan.html) already exists. If it does, choose a new descriptive filename based on context — e.g., serverlogic-plan-exchange-rate.html, serverlogic-plan-apr-2026.html. Pass the chosen name via --output.
Delete the temporary data JSON file after the script succeeds.
Open in Browser
Open the generated HTML file in the user's default browser.
Related skills
FAQ
Do I need to deploy the site before creating server logic?
Yes. Server logic files live inside .powerpages-site/server-logic/, which only exists after the first deployment. If the folder is missing, the skill will ask whether to deploy first before proceeding.
What languages and dependencies can server logic use?
Server Logic uses ECMAScript 2023 only. No npm packages, no imports/requires, no browser APIs (fetch, XMLHttpRequest, setTimeout, DOM), and no external dependencies. Only Server SDK methods are available (HttpClient for external APIs, Dataverse for data operations, Logger, Contex
How do I store API keys and other secrets securely?
The skill recommends Azure Key Vault (most secure, requires setup) or direct Dataverse environment variables (simpler, less secure in solution exports). Secrets are never hardcoded in .js files; instead, read them at runtime via Server.Sitesetting.Get(). The skill automates the c
Is Add Server Logic safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.