Morten Sæther

← Blog

JavaScript Frameworks Integration

#18 · 10 June 2026

React, Vue and Angular inside Power Pages, without losing the platform's benefits

There’s a point where server-rendered pages stop being enough and you want something that behaves like an app. That’s when React, Vue or Angular start looking attractive.

The trick is bringing them in without throwing away what Power Pages gives you for free - authentication, security, the data layer. Done well, you get modern frontend patterns on top of a backend you didn’t have to build. Done badly, you get a slow page with two competing ideas about who owns the DOM.

Step by step

Two things every framework example below shares. First, data comes from the portal’s own Web API at /_api/<entity set>, with the anti-forgery token from shell.getTokenDeferred() in the __RequestVerificationToken header on every call, reads included; the table also needs its Webapi/<table>/enabled and Webapi/<table>/fields site settings and a table permission for the web role. Second, Liquid renders the page before any framework runs. JSX uses single braces, so Liquid leaves React alone. Vue templates use {{ }}, which Liquid would swallow, so they go inside {% raw %}. Angular templates are compiled at build time and never reach Liquid at all.

1. React

<!-- React Component Container -->
<div id="react-task-dashboard" data-user-id="{{ user.id }}">
    <!-- Server-side fallback content -->
    <div class="loading-state">
        <div class="spinner"></div>
        <p>Loading tasks...</p>
    </div>
</div>

<!-- React Application Script -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<script type="text/babel">
    const { useState, useEffect, useCallback } = React;

    // Needs Webapi/task/enabled = true,
    // Webapi/task/fields = subject,description,scheduledend,statecode,statuscode
    // and a table permission on Task for the user's web role.
    function getToken() {
        return new Promise((resolve, reject) => {
            shell.getTokenDeferred().done(resolve).fail(reject);
        });
    }

    async function portalApi(path, options = {}) {
        const token = await getToken();
        const response = await fetch(`/_api${path}`, {
            ...options,
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                '__RequestVerificationToken': token,
                ...(options.headers || {})
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return response.status === 204 ? null : response.json();
    }

    function Dashboard() {
        const [tasks, setTasks] = useState([]);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(null);

        // Table permissions decide which tasks come back, not the filter.
        useEffect(() => {
            portalApi('/tasks?$select=activityid,subject,description,scheduledend&$filter=statecode eq 0&$orderby=scheduledend asc')
                .then(data => setTasks(data.value))
                .catch(err => setError(err.message))
                .finally(() => setLoading(false));
        }, []);

        const handleTaskComplete = useCallback(async (taskId) => {
            try {
                await portalApi(`/tasks(${taskId})`, {
                    method: 'PATCH',
                    body: JSON.stringify({ statecode: 1, statuscode: 5 })
                });
                setTasks(prev => prev.filter(task => task.activityid !== taskId));
                showNotification('Task completed', 'success');
            } catch (err) {
                showNotification('Failed to complete task', 'error');
                console.error('Task completion error:', err);
            }
        }, []);

        if (loading) {
            return (
                <div className="dashboard-loading">
                    <div className="spinner"></div>
                    <p>Loading your tasks...</p>
                </div>
            );
        }

        if (error) {
            return (
                <div className="dashboard-error">
                    <h3>Unable to load tasks</h3>
                    <p>{error}</p>
                    <button onClick={() => window.location.reload()}>Retry</button>
                </div>
            );
        }

        return (
            <div className="react-dashboard">
                <div className="dashboard-header">
                    <h2>Your Tasks</h2>
                    <span className="stat-value">{tasks.length}</span>
                    <span className="stat-label">Open</span>
                </div>
                <TasksList tasks={tasks} onTaskComplete={handleTaskComplete} />
            </div>
        );
    }

    function TasksList({ tasks, onTaskComplete }) {
        if (tasks.length === 0) {
            return (
                <div className="empty-state">
                    <h4>No open tasks</h4>
                    <p>You're all caught up.</p>
                </div>
            );
        }

        return (
            <div className="tasks-list">
                {tasks.map(task => (
                    <TaskItem key={task.activityid} task={task} onComplete={onTaskComplete} />
                ))}
            </div>
        );
    }

    function TaskItem({ task, onComplete }) {
        const [completing, setCompleting] = useState(false);

        const handleComplete = async () => {
            setCompleting(true);
            try {
                await onComplete(task.activityid);
            } finally {
                setCompleting(false);
            }
        };

        return (
            <div className="task-item">
                <div className="task-info">
                    <h4>{task.subject}</h4>
                    <p>{task.description}</p>
                    {task.scheduledend && (
                        <span className="task-due-date">
                            Due: {new Date(task.scheduledend).toLocaleDateString()}
                        </span>
                    )}
                </div>
                <div className="task-actions">
                    <button className="btn btn-success" onClick={handleComplete} disabled={completing}>
                        {completing ? 'Completing...' : 'Complete'}
                    </button>
                </div>
            </div>
        );
    }

    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.textContent = message;
        document.body.appendChild(notification);
        setTimeout(() => notification.remove(), 3000);
    }

    document.addEventListener('DOMContentLoaded', function () {
        const container = document.getElementById('react-task-dashboard');
        if (container) {
            ReactDOM.createRoot(container).render(<Dashboard />);
        }
    });
</script>

React escapes what it renders, so task.subject is safe to show as-is. What this leaves out next to a full dashboard is notifications and statistics; those are another table and another query through the same helper.

2. Vue

<!-- Vue.js Application Container -->
<div id="vue-product-configurator" data-product-id="{{ request.params.id | escape }}">
    <!-- Server-side fallback -->
    <div class="configurator-fallback">
        <h3>Product Configuration</h3>
        <p>Please enable JavaScript to use the interactive configurator.</p>
    </div>
</div>

<!-- Vue.js Integration -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
    const { createApp, ref, computed, onMounted } = Vue;

    // Needs Webapi/product/enabled = true and Webapi/product/fields = name,price
    function getToken() {
        return new Promise((resolve, reject) => {
            shell.getTokenDeferred().done(resolve).fail(reject);
        });
    }

    async function portalApi(path, options = {}) {
        const token = await getToken();
        const response = await fetch(`/_api${path}`, {
            ...options,
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                '__RequestVerificationToken': token,
                ...(options.headers || {})
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return response.status === 204 ? null : response.json();
    }

    const ProductConfiguratorApp = {
        setup() {
            const product = ref(null);
            const quantity = ref(1);
            const selectedFeatures = ref([]);
            const loading = ref(true);
            const errors = ref([]);

            const availableFeatures = [
                { value: 'warranty', label: 'Extended warranty', price: 49 },
                { value: 'install', label: 'Installation', price: 120 }
            ];

            const featuresTotal = computed(() =>
                availableFeatures
                    .filter(feature => selectedFeatures.value.includes(feature.value))
                    .reduce((sum, feature) => sum + feature.price, 0)
            );

            const totalPrice = computed(() =>
                product.value ? (product.value.price + featuresTotal.value) * quantity.value : 0
            );

            const money = (amount) => amount.toLocaleString(undefined, { style: 'currency', currency: 'USD' });

            const toggleFeature = (featureId) => {
                const index = selectedFeatures.value.indexOf(featureId);
                if (index > -1) {
                    selectedFeatures.value.splice(index, 1);
                } else {
                    selectedFeatures.value.push(featureId);
                }
            };

            onMounted(async () => {
                const container = document.getElementById('vue-product-configurator');
                try {
                    product.value = await portalApi(`/products(${container.dataset.productId})?$select=name,price`);
                } catch (error) {
                    errors.value.push('Failed to load product');
                    console.error('Product loading error:', error);
                } finally {
                    loading.value = false;
                }
            });

            return {
                product,
                quantity,
                selectedFeatures,
                availableFeatures,
                loading,
                errors,
                totalPrice,
                money,
                toggleFeature
            };
        },

        template: `{% raw %}
            <div class="vue-product-configurator">
                <div v-if="loading" class="loading-state">
                    <div class="spinner"></div>
                    <p>Loading configurator...</p>
                </div>

                <div v-else-if="errors.length > 0" class="alert alert-danger">
                    <ul>
                        <li v-for="error in errors" :key="error">{{ error }}</li>
                    </ul>
                </div>

                <div v-else class="configurator-content">
                    <h3>{{ product.name }}</h3>
                    <p class="unit-price">Unit price: {{ money(product.price) }}</p>

                    <div class="form-section">
                        <h4>Optional Features</h4>
                        <label v-for="feature in availableFeatures" :key="feature.value" class="feature-option">
                            <input type="checkbox"
                                   :checked="selectedFeatures.includes(feature.value)"
                                   @change="toggleFeature(feature.value)">
                            <span class="feature-name">{{ feature.label }}</span>
                            <span class="feature-price">+{{ money(feature.price) }}</span>
                        </label>
                    </div>

                    <div class="form-section">
                        <h4>Quantity</h4>
                        <button @click="quantity = Math.max(1, quantity - 1)" class="quantity-btn">-</button>
                        <input type="number" v-model.number="quantity" min="1" max="99" class="quantity-input">
                        <button @click="quantity = Math.min(99, quantity + 1)" class="quantity-btn">+</button>
                    </div>

                    <div class="pricing-summary">
                        <span class="label">Total:</span>
                        <span class="value">{{ money(totalPrice) }}</span>
                    </div>
                </div>
            </div>
        {% endraw %}`
    };

    document.addEventListener('DOMContentLoaded', function () {
        if (document.getElementById('vue-product-configurator')) {
            createApp(ProductConfiguratorApp).mount('#vue-product-configurator');
        }
    });
</script>

The {% raw %} block is the part people miss. Without it Liquid evaluates {{ product.name }} on the server, finds nothing, and Vue gets an empty template. Keeping the dollar signs out of the template string also matters: ${{ ... }} inside a JavaScript template literal is a syntax error, so prices are formatted by a function instead. What this leaves out is saving the configuration, which is a POST to a custom table through the same helper.

3. Angular

Angular decorators are TypeScript, not something a browser runs from an inline <script>, and a component’s template is compiled at build time. So Angular is a build: create the project with the Angular CLI, upload the output as web files, and mount it on a host element whose tag matches the component selector. The page is Liquid, the bundle is not.

<!-- Web page copy -->
{% assign can_delete = user | has_role: 'Document Managers' %}

<div id="angular-document-manager" data-can-delete="{{ can_delete }}">
    <app-document-manager>
        <!-- Progressive Enhancement Fallback -->
        <div class="document-manager-fallback">
            <h3>Document Management</h3>
            <a href="/documents/list" class="btn btn-outline-secondary">View All Documents</a>
        </div>
    </app-document-manager>
</div>

<script src="/angular/main.js" type="module"></script>
// document.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { from, Observable, switchMap } from 'rxjs';

// Provided by the Power Pages runtime on every page
declare const shell: {
    getTokenDeferred(): { done(cb: (token: string) => void): { fail(cb: () => void): void } };
};

export interface PortalDocument {
    annotationid: string;
    subject: string;
    filename: string;
    filesize: number;
    createdon: string;
}

// Needs Webapi/annotation/enabled = true and
// Webapi/annotation/fields = subject,filename,filesize,isdocument,createdon
@Injectable({ providedIn: 'root' })
export class DocumentService {
    constructor(private http: HttpClient) {}

    private token(): Promise<string> {
        return new Promise((resolve, reject) => {
            shell.getTokenDeferred().done(resolve).fail(reject);
        });
    }

    private withToken<T>(request: (headers: HttpHeaders) => Observable<T>): Observable<T> {
        return from(this.token()).pipe(
            switchMap(token => request(new HttpHeaders({
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                '__RequestVerificationToken': token
            })))
        );
    }

    getDocuments(): Observable<{ value: PortalDocument[] }> {
        return this.withToken(headers => this.http.get<{ value: PortalDocument[] }>(
            '/_api/annotations?$select=annotationid,subject,filename,filesize,createdon&$filter=isdocument eq true&$orderby=createdon desc',
            { headers, withCredentials: true }
        ));
    }

    deleteDocument(id: string): Observable<void> {
        return this.withToken(headers => this.http.delete<void>(
            `/_api/annotations(${id})`,
            { headers, withCredentials: true }
        ));
    }
}
// document-manager.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DocumentService, PortalDocument } from './document.service';

@Component({
    selector: 'app-document-manager',
    standalone: true,
    imports: [CommonModule, FormsModule],
    template: `
        <div class="document-list">
            <div class="list-header">
                <h4>Documents ({{ filtered.length }})</h4>
                <input type="text" [(ngModel)]="searchTerm" placeholder="Search documents..." class="search-input">
            </div>

            <div class="document-item" *ngFor="let doc of filtered">
                <div class="document-info">
                    <h5>{{ doc.filename }}</h5>
                    <p class="document-details">
                        {{ doc.filesize | number }} bytes | {{ doc.createdon | date:'short' }}
                    </p>
                </div>
                <div class="document-actions">
                    <button (click)="remove(doc)" *ngIf="canDelete" class="btn btn-sm btn-outline-danger">
                        Delete
                    </button>
                </div>
            </div>

            <div class="empty-state" *ngIf="!loading && filtered.length === 0">
                <h4>No documents found</h4>
            </div>
        </div>
    `
})
export class DocumentManagerComponent implements OnInit {
    documents: PortalDocument[] = [];
    searchTerm = '';
    loading = true;
    canDelete = false;

    constructor(private service: DocumentService) {}

    ngOnInit() {
        const host = document.getElementById('angular-document-manager');
        this.canDelete = host?.dataset['canDelete'] === 'true';

        this.service.getDocuments().subscribe({
            next: result => {
                this.documents = result.value;
                this.loading = false;
            },
            error: error => {
                console.error('Failed to load documents:', error);
                this.loading = false;
            }
        });
    }

    get filtered() {
        const term = this.searchTerm.toLowerCase();
        return this.documents.filter(doc => doc.filename.toLowerCase().includes(term));
    }

    remove(doc: PortalDocument) {
        if (!confirm(`Delete "${doc.filename}"?`)) {
            return;
        }

        this.service.deleteDocument(doc.annotationid).subscribe({
            next: () => {
                this.documents = this.documents.filter(d => d.annotationid !== doc.annotationid);
            },
            error: error => console.error('Failed to delete document:', error)
        });
    }
}
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { DocumentManagerComponent } from './document-manager.component';

bootstrapApplication(DocumentManagerComponent, {
    providers: [provideHttpClient()]
}).catch(err => console.error('Angular bootstrap error:', err));

The canDelete flag deserves a word. In Liquid, user.permissions is not a list of permission strings: user is an entity object, so user.permissions is the table permission result for the contact record itself, an object with can_read, can_write, can_delete and so on. For a UI decision, work it out in Liquid from a web role and pass one boolean. The real rule is enforced on the server: without a table permission that grants Delete, the DELETE call returns 403 whatever the button says. What this leaves out is upload, which is a POST to /_api/annotations with the file as a base64 documentbody.

Angular is the heaviest of the three to embed. Worth it if your team already lives there, hard to justify if not.

What this looks like in practice

A dashboard combining several frameworks on one portal:

<!-- multi-framework-dashboard.html -->
<div class="multi-framework-dashboard"
     data-user-id="{{ user.id }}"
     data-user-name="{{ user.fullname | escape }}"
     data-user-roles="{{ user.roles | join: ',' | escape }}">
    <!-- React Analytics Section -->
    <div class="dashboard-section">
        <div id="react-analytics-widget" data-date-range="30">
            <div class="widget-fallback">
                <h4>Analytics</h4>
                <p>Loading analytics data...</p>
            </div>
        </div>
    </div>

    <!-- Vue.js Task Management Section -->
    <div class="dashboard-section">
        <div id="vue-task-manager">
            <div class="widget-fallback">
                <h4>Task Management</h4>
                <p>Loading task manager...</p>
            </div>
        </div>
    </div>

    <!-- Angular Communication Hub -->
    <div class="dashboard-section">
        <div id="angular-communication-hub">
            <div class="widget-fallback">
                <h4>Communication</h4>
                <p>Loading communication hub...</p>
            </div>
        </div>
    </div>
</div>

<!-- Cross-Framework Communication -->
<script>
    // Global event bus for framework communication
    window.FrameworkEventBus = {
        events: {},

        on(event, callback) {
            if (!this.events[event]) {
                this.events[event] = [];
            }
            this.events[event].push(callback);
        },

        emit(event, data) {
            if (this.events[event]) {
                this.events[event].forEach(callback => callback(data));
            }
        },

        off(event, callback) {
            if (this.events[event]) {
                const index = this.events[event].indexOf(callback);
                if (index > -1) {
                    this.events[event].splice(index, 1);
                }
            }
        }
    };

    // Shared data store, seeded from the data attributes Liquid rendered
    const dashboard = document.querySelector('.multi-framework-dashboard').dataset;

    window.SharedDataStore = {
        data: {
            user: {
                id: dashboard.userId,
                name: dashboard.userName,
                roles: dashboard.userRoles.split(',').filter(Boolean)
            }
        },

        get(key) {
            return this.data[key];
        },

        set(key, value) {
            this.data[key] = value;
            window.FrameworkEventBus.emit('dataChanged', { key, value });
        },

        update(key, updates) {
            if (this.data[key]) {
                Object.assign(this.data[key], updates);
                window.FrameworkEventBus.emit('dataChanged', { key, value: this.data[key] });
            }
        }
    };

    // Performance monitoring for framework integration
    window.FrameworkPerformance = {
        timings: {},

        start(framework, operation) {
            this.timings[`${framework}.${operation}`] = { start: performance.now() };
        },

        end(framework, operation) {
            const key = `${framework}.${operation}`;
            if (this.timings[key]) {
                this.timings[key].duration = performance.now() - this.timings[key].start;
                console.log(`${framework} ${operation}: ${this.timings[key].duration.toFixed(2)}ms`);
            }
        }
    };

    // Example: task completion in Vue affects analytics in React
    window.FrameworkEventBus.on('taskCompleted', function () {
        window.FrameworkEventBus.emit('refreshAnalytics', {
            metric: 'tasks_completed',
            increment: 1
        });
    });

    // Error boundary for framework integration
    window.addEventListener('error', function (event) {
        let framework = 'unknown';
        if (event.filename && event.filename.includes('react')) {
            framework = 'react';
        } else if (event.filename && event.filename.includes('vue')) {
            framework = 'vue';
        } else if (event.filename && event.filename.includes('angular')) {
            framework = 'angular';
        }

        console.error(`Framework Error (${framework}):`, {
            message: event.message,
            filename: event.filename,
            lineno: event.lineno,
            colno: event.colno
        });
    });
</script>

Each widget mounts on its own container from its own script, the way the three examples above do; the shared code only gives them a bus and a store to talk through. The user’s roles are for the UI. Anything a widget reads or writes still goes through /_api, where table permissions apply.

Mixing frameworks like this is a demonstration, not a recommendation. Pick one for a given portal unless you have a strong reason - your bundle size and your future self will thank you.

How to make a mess and fix it

  1. Frameworks colliding - namespace isolation and version management
  2. Slow loads - watch bundle size and split your code
  3. State out of sync - decide who owns which data and make the flow explicit
  4. Authentication ignored by components - your framework code must respect Power Pages auth state, not work around it
  5. Search engines and screen readers seeing nothing - progressive enhancement, and server-rendered fallbacks where it matters

Five habits worth keeping

  1. Make the basics work without the framework - then enhance
  2. Measure loading and runtime performance, not just how it feels on your laptop
  3. Use error boundaries so one broken component doesn’t take the page with it
  4. Pin your framework versions across environments
  5. Test the integration, not just the components in isolation

Wrapping up

Frameworks let you build interfaces that feel like software rather than web forms. Keep the progressive enhancement discipline, watch performance, handle failure, and be explicit about where data comes from and who owns it.

Next: advanced security and authentication, and custom auth flows for the situations the defaults don’t cover.