Book consult
    Power BI

    Power BI Embedded: Integrating Analytics into Your Applications

    Prasanna Ravikumar
    October 27, 2024
    Power BI Embedded: Integrating Analytics into Your Applications

    Learn how to embed Power BI reports and dashboards into your custom applications, enabling white-label analytics solutions and seamless user experiences.

    Power BI Embedded: Integrating Analytics into Your Applications

    Power BI Embedded allows you to integrate interactive reports and dashboards directly into your web applications, creating seamless analytics experiences for your users. This comprehensive guide covers everything from basic embedding to advanced security and customization.

    What is Power BI Embedded?

    Power BI Embedded is a service that enables developers to integrate Power BI content—reports, dashboards, and tiles—into applications. It's ideal for:

    - ISVs building analytics into SaaS products - Enterprises creating internal portals - Consultancies delivering white-label solutions - Developers building custom applications

    Licensing Models

    Power BI Embedded vs Power BI Premium

    Power BI Embedded (Capacity-based) - Pay for compute capacity (SKU: A1-A6) - Pause/resume capability - Ideal for ISVs and external users - No per-user licensing needed

    Power BI Premium Per User - $20/user/month - Better for internal users - Full Power BI features

    Power BI Premium Capacity - Starting at $4,995/month - Unlimited users - Best for large organizations

    Architecture Overview

    Components

    1. Power BI Workspace - Contains reports and datasets 2. Azure AD App Registration - Handles authentication 3. Embed Token - Provides time-limited access 4. Power BI REST API - Manages embedding process 5. Client Application - Displays embedded content

    Embedding Flow

    ``` 1. User accesses your application 2. Application authenticates with Azure AD 3. Application requests embed token from Power BI API 4. Power BI generates token with RLS context 5. Application passes token to Power BI JavaScript library 6. Report renders in iframe within your application ```

    Setting Up Power BI Embedded

    Step 1: Create Azure AD App Registration

    ```bash Using Azure CLI az ad app create --display-name "MyApp-PowerBI-Embed" \\ --sign-in-audience AzureADMultiTenantAndPersonalMicrosoftAccounts

    Note the Application (client) ID and create a client secret ```

    Step 2: Grant API Permissions

    Required Microsoft Graph permissions: - `Dataset.Read.All` - `Report.Read.All` - `Workspace.Read.All` - `Content.Create`

    Step 3: Create Power BI Workspace

    ```powershell Using Power BI PowerShell Install-Module -Name MicrosoftPowerBIMgmt Connect-PowerBIServiceAccount

    New-PowerBIWorkspace -Name "Embedded Analytics Workspace" ```

    Step 4: Assign Service Principal to Workspace

    ```powershell Add-PowerBIWorkspaceUser -WorkspaceId <workspace-id> \\ -PrincipalId <service-principal-id> \\ -AccessRight Admin \\ -PrincipalType App ```

    Implementation Examples

    Backend: Node.js/Express

    ```javascript const express = require('express'); const msal = require('@azure/msal-node'); const axios = require('axios');

    const app = express();

    // MSAL configuration const msalConfig = { auth: { clientId: process.env.CLIENT_ID, authority: `https://login.microsoftonline.com/${process.env.TENANT_ID}`, clientSecret: process.env.CLIENT_SECRET } };

    const cca = new msal.ConfidentialClientApplication(msalConfig);

    // Get embed token endpoint app.get('/api/embed-token', async (req, res) => { try { // Get access token const authResult = await cca.acquireTokenByClientCredential({ scopes: ['https://analysis.windows.net/powerbi/api/.default'] });

    // Get embed token const embedUrl = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}/GenerateToken`; const embedTokenResponse = await axios.post( embedUrl, { accessLevel: 'View', identities: [ { username: req.user.email, roles: [req.user.role], datasets: [datasetId] } ] }, { headers: { 'Authorization': `Bearer ${authResult.accessToken}` } } );

    res.json({ token: embedTokenResponse.data.token, tokenId: embedTokenResponse.data.tokenId, expiration: embedTokenResponse.data.expiration, reportId: reportId, embedUrl: `https://app.powerbi.com/reportEmbed?reportId=${reportId}` }); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to generate embed token' }); } });

    app.listen(3000); ```

    Frontend: React

    ```jsx import React, { useEffect, useRef, useState } from 'react'; import { models } from 'powerbi-client'; import { PowerBIEmbed } from 'powerbi-client-react';

    function PowerBIReport() { const [embedConfig, setEmbedConfig] = useState(null);

    useEffect(() => { // Fetch embed token from backend fetch('/api/embed-token') .then(res => res.json()) .then(data => { setEmbedConfig({ type: 'report', id: data.reportId, embedUrl: data.embedUrl, accessToken: data.token, tokenType: models.TokenType.Embed, settings: { panes: { filters: { expanded: false, visible: false } }, background: models.BackgroundType.Transparent, navContentPaneEnabled: false } }); }); }, []);

    const eventHandlers = new Map([ ['loaded', () => console.log('Report loaded')], ['rendered', () => console.log('Report rendered')], ['error', (event) => console.error(event.detail)] ]);

    return embedConfig ? ( <PowerBIEmbed embedConfig={embedConfig} eventHandlers={eventHandlers} cssClassName="report-container" getEmbeddedComponent={(embeddedReport) => { window.report = embeddedReport; }} /> ) : ( <div>Loading report...</div> ); }

    export default PowerBIReport; ```

    Frontend: Vanilla JavaScript

    ```javascript // Include Power BI JavaScript library // <script src="https://cdn.jsdelivr.net/npm/powerbi-client@2.x/dist/powerbi.min.js"></script>

    async function embedReport() { // Get embed configuration from backend const response = await fetch('/api/embed-token'); const embedData = await response.json();

    // Embed configuration const config = { type: 'report', id: embedData.reportId, embedUrl: embedData.embedUrl, accessToken: embedData.token, tokenType: models.TokenType.Embed, permissions: models.Permissions.Read, viewMode: models.ViewMode.View, settings: { filterPaneEnabled: false, navContentPaneEnabled: true, layoutType: models.LayoutType.Custom, customLayout: { displayOption: models.DisplayOption.FitToWidth } } };

    // Get reference to the embedded container const reportContainer = document.getElementById('reportContainer');

    // Embed the report const powerbi = new pbi.service.Service( pbi.factories.hpmFactory, pbi.factories.wpmpFactory, pbi.factories.routerFactory );

    const report = powerbi.embed(reportContainer, config);

    // Handle report load event report.on('loaded', () => { console.log('Report loaded'); });

    // Handle report render event report.on('rendered', () => { console.log('Report rendered'); });

    // Handle errors report.on('error', (event) => { console.error(event.detail); });

    return report; } ```

    Advanced Features

    Row-Level Security (RLS)

    ```javascript // Define RLS context when generating embed token const embedTokenRequest = { accessLevel: 'View', identities: [ { username: user.email, roles: [user.department], // e.g., "Sales", "Marketing" datasets: [datasetId] } ] };

    // In Power BI Desktop, create roles and DAX filters // Example DAX filter: [Department] = USERPRINCIPALNAME() ```

    Dynamic Filtering

    ```javascript // Apply filters programmatically const filter = { $schema: "http://powerbi.com/product/schemabasic", target: { table: "Sales", column: "Region" }, operator: "In", values: ["West", "East"], filterType: models.FilterType.BasicFilter };

    report.setFilters([filter]); ```

    Report Customization

    ```javascript // Update settings after embed report.updateSettings({ panes: { filters: { visible: true }, pageNavigation: { visible: false } }, background: models.BackgroundType.Transparent, layoutType: models.LayoutType.Custom, customLayout: { pageSize: { type: models.PageSizeType.Custom, width: 1280, height: 720 }, displayOption: models.DisplayOption.FitToWidth } }); ```

    Capturing User Interactions

    ```javascript // Handle page changes report.on('pageChanged', (event) => { console.log('New page:', event.detail.newPage.displayName); // Send analytics to your backend trackPageView(event.detail.newPage.name); });

    // Handle data selection report.on('dataSelected', (event) => { console.log('Data selected:', event.detail); // Trigger actions based on selection });

    // Handle button clicks report.on('buttonClicked', (event) => { console.log('Button clicked:', event.detail); }); ```

    Security Best Practices

    Token Management

    1. Short-lived tokens - Set expiration to 10-60 minutes 2. Refresh before expiration - Implement token refresh logic 3. Secure transmission - Always use HTTPS 4. Server-side generation - Never generate tokens in frontend

    Authentication & Authorization

    ```javascript // Example: Multi-layered security async function getEmbedToken(userId, reportId) { // 1. Authenticate user const user = await authenticateUser(userId); // 2. Authorize access to specific report const hasAccess = await checkReportAccess(user, reportId); if (!hasAccess) throw new Error('Unauthorized'); // 3. Apply data-level security (RLS) const rlsRoles = await getUserRLSRoles(user); // 4. Generate embed token with RLS return await generateEmbedToken({ reportId, username: user.email, roles: rlsRoles }); } ```

    Performance Optimization

    Caching Strategies

    ```javascript // Cache embed tokens (with expiration awareness) const tokenCache = new Map();

    async function getCachedEmbedToken(reportId, userId) { const cacheKey = `${reportId}:${userId}`; const cached = tokenCache.get(cacheKey); if (cached && cached.expiration > Date.now()) { return cached.token; } const newToken = await generateEmbedToken(reportId, userId); tokenCache.set(cacheKey, { token: newToken, expiration: Date.now() + (50 60 1000) // 50 min }); return newToken; } ```

    Load Time Optimization

    1. Lazy loading - Load reports on-demand 2. Preload critical reports - Prefetch frequently accessed reports 3. Optimize report design - Reduce visual complexity 4. Use bookmarks - Navigate to specific report states quickly

    Monitoring and Analytics

    Track Usage

    ```javascript // Send usage analytics report.on('loaded', () => { analytics.track('Report Loaded', { reportId: reportId, userId: currentUser.id, timestamp: new Date() }); });

    report.on('dataSelected', (event) => { analytics.track('Data Interaction', { reportId: reportId, visual: event.detail.visual, selection: event.detail.dataPoints }); }); ```

    Error Tracking

    ```javascript report.on('error', (event) => { const errorDetails = { message: event.detail.message, detailedMessage: event.detail.detailedMessage, errorCode: event.detail.errorCode, reportId: reportId, userId: currentUser.id }; // Send to error tracking service errorTracking.captureException(errorDetails); }); ```

    Common Use Cases

    Multi-Tenant SaaS Application - Each tenant sees only their data via RLS - White-label branding - Usage-based billing - Tenant-specific customizations

    Customer Portal - Customer-specific dashboards - Self-service analytics - Secure data isolation - Custom navigation

    Internal Business Application - Departmental dashboards - Real-time KPI monitoring - Cross-functional reporting - Mobile-responsive views

    Troubleshooting

    Common Issues

    Token Expiration ```javascript // Auto-refresh tokens setInterval(async () => { const newToken = await fetchEmbedToken(); report.setAccessToken(newToken); }, 50 60 1000); // Refresh every 50 minutes ```

    CORS Errors - Configure proper CORS headers on backend - Use same-origin policy where possible

    Slow Loading - Optimize report queries - Reduce number of visuals - Use DirectQuery judiciously

    Conclusion

    Power BI Embedded transforms static reports into dynamic, integrated analytics experiences. Whether you're building a SaaS product, customer portal, or internal application, Power BI Embedded provides enterprise-grade analytics with the flexibility to match your brand and security requirements.

    Start with a simple embed scenario and gradually add advanced features like RLS, custom filtering, and interaction handling. The investment in properly implementing Power BI Embedded pays dividends in user satisfaction and business insights.

    Share this article