May 1, 2025

How to Call Dataverse API from Power Pages Using safeAjax JavaScript

Introduction:

Power Pages offers a flexible way to expose Dataverse data to users, but calling the Dataverse Web API directly from JavaScript inside a Power Pages app requires some careful configuration. In this blog, we’ll walk through the required setup steps in Power Pages and demonstrate how to make secure GET and POST calls using a custom safeAjax wrapper.

Whether you're working with authenticated or anonymous users, this guide will help you get started with Dataverse API calls using jQuery.


Step-by-Step Configuration to Enable Dataverse API in Power Pages

Step 1: Configure Site Settings for the Target Table

Navigate to Power Pages Management > Site Settings and add the following entries for your Dataverse table. These settings enable API access, field-level control, and CORS.

  1. Enable Web API for the Table

    • Name: Webapi/{Table Logical Name}/enabled

    • Value: true

  2. Define Fields to Be Accessed

    • Name: Webapi/{Table Logical Name}/fields

    • Value: * (all fields)

  3. Allow Cross-Origin Requests

    • Name: Webapi/{Table Logical Name}/AllowedOrigins

    • Value: * (or specify your domain)

  4. (Optional) Enable Anonymous Access

    • Name: Webapi/{Table Logical Name}/AllowAnonymousAccess

    • Value: true

    • Only required if your Power Pages site supports anonymous users

Make sure to select the correct Website and set Source as Table in all entries.


Step 2: Set Up Table Permissions

Next, go to the Security > Table Permissions section in Power Pages Management.

  • Create a new permission for your table.

  • Assign appropriate permissions (Read, Create, Update, etc.) based on your use case.

  • Link this permission to the appropriate Web Roles (Authenticated or Anonymous Users).

Without table permissions, the API call will fail even if site settings are correct.



safeAjax JavaScript Wrapper for Dataverse API Calls

Once your configuration is complete, use the following script to wrap your AJAX calls securely. This script ensures tokens are included for request validation and handles common error scenarios gracefully.

$(function () {
    // Web API ajax wrapper
    (function (webapi, $) {
        function safeAjax(ajaxOptions) {
            var deferredAjax = $.Deferred();
            shell.getTokenDeferred().done(function (token) {
                // Add headers for ajax
                if (!ajaxOptions.headers) {
                    $.extend(ajaxOptions, {
                        headers: {
                            "__RequestVerificationToken": token
                        }
                    });
                } else {
                    ajaxOptions.headers["__RequestVerificationToken"] = token;
                }
                $.ajax(ajaxOptions)
                    .done(function (data, textStatus, jqXHR) {
                        validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
                    }).fail(deferredAjax.reject); // ajax fail
            }).fail(function () {
                deferredAjax.rejectWith(this, arguments); // On token failure
            });
            return deferredAjax.promise();
        }
        webapi.safeAjax = safeAjax;
    })(window.webapi = window.webapi || {}, jQuery)
});

function appAjax(ajaxOptions) {
    return webapi.safeAjax(ajaxOptions).done(function (res) {
        if (res.value.length > 0) {
            const result = res.value[0];
            alert("Successfully logged in!");
        } else {
            alert("Incorrect ID or Password.");
        }
    })
    .fail(function (response) {
        if (response.responseJSON) {
            alert("Error: " + response.responseJSON.error.message)
        } else {
            alert("Error: Web API is not available... ")
        }
    });
}

Usage Examples

GET Request

Call this when you want to retrieve data from your Dataverse table.

appAjax({
    type: "GET",
    url: "/_api/crb50_tablename?$select=*&$filter=crb50_customerid eq '001' and crb50_password eq '001'",
    contentType: "application/json"
});


POST Request

Use this to insert a new record into Dataverse.

var recordObj = {
    "crb50_name": "Name1"
};

appAjax({
    type: "POST",
    url: "/_api/crb50_TableName",
    contentType: "application/json",
    data: JSON.stringify(recordObj),
    success: function (res, status, xhr) {
        recordObj.id = xhr.getResponseHeader("entityid");
        table.addRecord(recordObj);
    }
});


Conclusion

Integrating Power Pages with Dataverse Web API opens up a wide range of possibilities, from custom login experiences to fully dynamic data interactions. With a few key configurations in site settings and table permissions, and a secure AJAX wrapper like safeAjax, you can harness the full power of Dataverse from the front end of your Power Pages apps.

If you have any questions you can reach out our SharePoint Consulting team here.

Fixing SPFx Build Error: “UglifyJs Unexpected Token” When Running gulp bundle --ship

Introduction:

While packaging your SharePoint Framework (SPFx) solution using the production command: 

gulp bundle --ship

You may encounter a frustrating error message like: 

Unexpected token: name (corefeature) - SPFx while build solution

This usually indicates that UglifyJS, the default minifier in SPFx, stumbled upon ES6+ syntax (e.g., class, let, const) that it does not understand. 

In this post, I will guide you through a clean and effective workaround using terser-webpack-plugin, a modern minifier that fully supports ES6+. 

Why This Error Occurs:

  • Root Cause: UglifyJS does not support modern JavaScript (ES6+). 
  • Impact: Webpack fails during the minification process, stopping the bundle process for production. 
  • Trigger: Usage of ES6+ syntax like class, const, etc., in your SPFx web part code.  

Solution: Swap UglifyJS with Terser:

To resolve this, we will: 

  1. Add Terser and Webpack merge dependencies. 
  2. Update gulpfile.js to override the default SPFx Webpack configuration. 
  3. Clean and rebuild your project. 

Step-by-Step Fix:

Step 1: Install Compatible Dependencies:

Update your package.json to include: 

"terser-webpack-plugin-legacy": "1.2.3",
"webpack-merge": "4.2.1"

Then run the following commands in your terminal: 

npm install terser-webpack-plugin --save-dev
npm install terser-webpack-plugin-legacy --save-dev
npm install webpack-merge@4.2.1 --save-dev

Optional (if Babel is needed for ES6+ transpilation): 

npm install @babel/core @babel/preset-env babel-loader --save-dev

Step 2: Update gulpfile.js:

Modify your gulpfile.js as shown below: 

'use strict';
 
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const merge = require('webpack-merge');
const TerserPlugin = require('terser-webpack-plugin-legacy');
 
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase
  and will not be type-safe.`);

build.initialize(gulp);
 
build.configureWebpack.setConfig({
 additionalConfiguration: function (config) {
   config.plugins = config.plugins.filter(plugin => !(plugin.options && plugin.options.mangle));
 
   return merge(config, {
     optimization: {
       minimize: true,
       minimizer: [new TerserPlugin()]
     }
   });
 }
});

This code replaces UglifyJS with Terser during the bundle phase. 

Step 3: Clean & Rebuild the Project: 

Run the following commands in sequence: 

gulp clean
gulp build --ship
gulp bundle --ship

Your project should now build successfully, free of any “unexpected token” errors from UglifyJS. 

Optional: Babel Setup (Only If Needed): 

If your project uses newer JavaScript features not supported in your target environments, consider setting up Babel. However, for the UglifyJS error alone, swapping in Terser is typically enough. 

Conclusion: 

  • If you are getting the "UglifyJs Unexpected Token" error while bundling your SPFx project, it is because the default minifier does not support modern JavaScript. By switching to it terser-webpack-plugin, you can fix the issue and bundle your project without errors. Just follow the steps to update your packages and gulpfile, and you will be good to go!
  • If you run into any issues while implementing this solution, feel free to drop a comment. I will be happy to help. 

If you have any questions you can reach out our SharePoint Consulting team here.

How to Add a Custom Command Bar Button to Create a New Row in a Model-Driven App

How to Add a Custom Command bar Button to Create a New Row in a Model-Driven App

Introduction

Model-driven apps in Power Platform offer a powerful way to create data-centric business apps with minimal code. In this post, we’ll walk through the steps to create a custom command bar button on the Main Grid view that allows users to add a new row to a table (entity).

This guide assumes you have some basic familiarity with the Power Apps Maker Portal and Dataverse.


Step 1: Create Your Model-Driven App

  1. Go to Power Apps.
  2. Click Apps from the left navigation pane.
  3. Click + New app > Model-driven app.
  4. Give your app a name (e.g., Data Form) and click Create.
  5. Use the app designer to add a table (e.g., Data) to your app.
  6. Save and publish the app.

Step 2: Add a Custom Command bar Button

We will now add a custom button to the command bar of the Main Grid for the table.

2.1 Navigate to the App

  1. In the Maker Portal, go to View.
  2. Select your view (e.g., DataForms view).
  3. Click the three dots (⋮) beside the view.
  4. Click Edit under the Edit command bar options.














2.2 Edit the Main Grid Command Bar

  1. In the command designer, choose Main grid.


















  2. Click +New and select Command.



















2.3 Configure the Custom Button

  1. Label: Add New Row
  2. Icon: Choose an appropriate icon or upload a custom one.
  3. Action: Choose JavaScript or Modern Action (recommended).














Step 3: Add the Button Logic (Use JavaScript)

  1. Create a JavaScript web resource.
  2. Add the following function:
  3. Click Add Library button to open new side panel
  4. Click New web resource



























Below is the JavaScript Code.

    
function AddNewRowToMainGrid(primaryControl) {
	try {
		// Check if primaryControl is defined (for main grid button)
        if (!primaryControl || !primaryControl.data || !primaryControl.data.entity) {
            console.log("No record selected. This is a new record creation.");
        }

        // Define the table name (logical name of your table)
        var tableName = "new_dataform"; // Make sure this is correct!

        // Prepare default values for the new row
        var defaultData = {
        "new_dateoftillcheck": null,
        "new_tillid": null,
		"new_nameofcurrenttillholder": "",
        "new_discrepancydeficiency": "",
        "new_discrepancysurplus": "",
        "new_actiontakeen": "",
        "new_postplusadjustmentdate": null,
        "new_signatureoftillholdercheckingofficer": "",
        };

        //console.log("Creating record in table: " + tableName);
        //console.log("Data: ", JSON.stringify(defaultData));

        // Create a new record in Dataverse
        Xrm.WebApi.createRecord(tableName, defaultData).then(
		function success(result) {
		  //console.log("Record created successfully with ID: " + result.id);

		  // Refresh the main grid after adding the record
		  if (primaryControl && primaryControl.refresh) {
			primaryControl.refresh();
		  } 
		  else {
		console.warn("primaryControl not available. Trying page refresh.");
		Xrm.Page.ui.refresh(); // Fallback
		}
		  },
		  function(error) {
		  	console.error("Error creating record: ", error.message);
			Xrm.Navigation.openErrorDialog({
			message: "Error adding new record: " + error.message
		  });
		}
	);
} 
catch (e) {
	console.error("Unexpected error:", e);
	Xrm.Navigation.openErrorDialog({
	message: "Unexpected error occurred: " + e.message
	});
  }
}

Step 4: Test the Custom Button

  1. Open your model-driven app.
  2. Navigate to the DataForm Main Grid.
  3. Click on your custom Add New Row button.
  4. A new row added, allowing the user to add a new record.










Conclusion

Customizing command bars in model-driven apps can significantly enhance user experience and streamline operations. Whether using Power Fx for low-code scenarios or JavaScript for more complex logic, adding a "New Row" button makes it easier for your users to create data on the fly.