Morten Sæther

← Blog

Site Settings & Configuration

#17 · 4 June 2026

Environment config, feature toggles, and not hardcoding your way into a corner

Every portal that’s lasted a few years has the same scar: a value hardcoded in three places that now needs to be different in test and production.

Configuration management is the boring discipline that prevents it. Settings that know which environment they’re in, feature toggles that let you ship something dark and turn it on for one group of users first, and a hierarchy that makes it obvious which value wins.

Step by step

1. Set up the hierarchy

Power Pages has one configuration store: site settings. Each setting is a name and a string value, scoped to the website, and Liquid reads it with settings['Name']. There is no nested configuration object, so the hierarchy is a naming convention:

Site setting Value
Environment/Name production
Environment/DebugMode false
Environment/PerformanceMonitoring true
Feature/AdvancedSearch/Enabled true
Feature/NewDashboard/Enabled true
Feature/NewDashboard/Roles Beta Testers,Administrators
Integration/Crm/Timeout 30000

Values come back as strings. The boolean and integer filters turn them into something you can test:

{% assign environment = settings['Environment/Name'] | default: 'development' %}
{% assign debug_mode = settings['Environment/DebugMode'] | boolean | default: false %}
{% assign monitoring_enabled = settings['Environment/PerformanceMonitoring'] | boolean | default: false %}

{% if debug_mode %}
    <div class="debug-panel">
        <h4>Debug Information</h4>
        <p>Environment: {{ environment | escape }}</p>
        <p>User ID: {{ user.id }}</p>
        <p>User Roles: {{ user.roles | join: ', ' | escape }}</p>
        <p>Language: {{ language.code }}</p>
    </div>
{% endif %}

<script>
    window.PORTAL_CONFIG = {
        environment: '{{ environment | escape }}',
        debug: {{ debug_mode }},
        monitoring: {{ monitoring_enabled }},
        crmTimeout: {{ settings['Integration/Crm/Timeout'] | integer | default: 30000 }}
    };

    window.trackFeatureUsage = function (feature, action, metadata) {
        if (window.PORTAL_CONFIG.debug) {
            console.log('Feature usage:', feature, action, metadata || {});
        }
    };

    if (window.PORTAL_CONFIG.monitoring) {
        window.addEventListener('load', function () {
            const [navigation] = performance.getEntriesByType('navigation');
            if (navigation) {
                window.trackFeatureUsage('page', 'load', { milliseconds: Math.round(navigation.duration) });
            }
        });
    }

    window.addEventListener('error', function (event) {
        console.error('Error:', event.message, event.filename, event.lineno);
    });
</script>

Environment-specific values do not come from a per-environment config file. With the enhanced data model, a site setting can take its value from a Power Platform environment variable: set the setting’s source to Environment Variable in the Power Pages Management app, give the variable a value per environment, and the setting resolves at runtime. The site has to be in an environment where the enhanced data model is enabled. Secrets go in environment variables backed by Azure Key Vault, so they never sit in a setting as plain text. After changing a variable value, clear the cache with Sync in design studio or Clear cache on /_services/about.

2. Build feature toggles

A toggle is a site setting read with the boolean filter:

{% assign advanced_search_enabled = settings['Feature/AdvancedSearch/Enabled'] | boolean | default: false %}

{% if advanced_search_enabled %}
    <form class="advanced-search-form" method="get" action="/search">
        <label for="keywords">Keywords:</label>
        <input type="text" id="keywords" name="q" value="{{ request.params.q | escape }}">

        <label for="category">Category:</label>
        <select id="category" name="category">
            <option value="">All Categories</option>
            <option value="articles" {% if request.params.category == 'articles' %}selected{% endif %}>Articles</option>
            <option value="documents" {% if request.params.category == 'documents' %}selected{% endif %}>Documents</option>
            <option value="videos" {% if request.params.category == 'videos' %}selected{% endif %}>Videos</option>
        </select>

        <button type="submit" class="btn btn-primary">Search</button>
    </form>

    <script>
        document.querySelector('.advanced-search-form').addEventListener('submit', function (e) {
            window.trackFeatureUsage('advanced_search', 'search_performed', {
                has_category: e.target.category.value !== ''
            });
        });
    </script>
{% else %}
    <form class="search-form" method="get" action="/search">
        <input type="text" name="q" placeholder="Search..." value="{{ request.params.q | escape }}">
        <button type="submit" class="btn btn-primary">Search</button>
    </form>
{% endif %}

A beta toggle adds a second setting with the web roles that get it. Leave Feature/NewDashboard/Roles out to open the feature to everyone; otherwise list role names separated by commas, no spaces:

{% assign new_dashboard_on = settings['Feature/NewDashboard/Enabled'] | boolean | default: false %}
{% assign new_dashboard_roles = settings['Feature/NewDashboard/Roles'] %}
{% assign new_dashboard_enabled = false %}

{% if new_dashboard_on %}
    {% if new_dashboard_roles %}
        {% assign role_list = new_dashboard_roles | split: ',' %}
        {% for role in role_list %}
            {% if user.roles contains role %}
                {% assign new_dashboard_enabled = true %}
            {% endif %}
        {% endfor %}
    {% else %}
        {% assign new_dashboard_enabled = true %}
    {% endif %}
{% endif %}

{% if new_dashboard_enabled %}
    <div class="beta-feature-notice">
        <span class="beta-badge">BETA</span>
        <h4>New Dashboard Experience</h4>
        <p>You're seeing our new dashboard design. <a href="/feedback/dashboard">Share your feedback</a></p>
    </div>
    {% include 'Dashboard v3' %}
    <script>
        window.trackFeatureUsage('new_dashboard', 'viewed');
    </script>
{% else %}
    {% include 'Dashboard' %}
{% endif %}

Dashboard and Dashboard v3 are web templates; include takes a web template name. What this leaves out is the percentage rollout. Power Pages Liquid has no hashing filter, so a toggle is on or off per site and per web role. If you need a smaller slice, put a yes/no column on the contact and read it as user.<column logical name>.

Toggles let you deploy and release separately, which is the biggest reduction in deployment anxiety you can buy. They also accumulate - budget time to remove the dead ones.

3. Keep integration settings out of your code

The portal reaches Dataverse through its own /_api route, not through https://<org>.crm.dynamics.com/api/data/v9.2/. The browser has no OAuth token for Dataverse; it has a portal session, and every /_api call, reads included, carries the anti-forgery token from shell.getTokenDeferred() in the __RequestVerificationToken header. The table needs Webapi/contact/enabled set to true, Webapi/contact/fields listing the columns, and a table permission for the user’s web role.

{% assign crm_timeout = settings['Integration/Crm/Timeout'] | integer | default: 30000 %}

<script>
    window.CRM_CONFIG = {
        timeout: {{ crm_timeout }}
    };

    function getToken() {
        return new Promise(function (resolve, reject) {
            shell.getTokenDeferred().done(resolve).fail(reject);
        });
    }

    async function portalApi(path, options = {}) {
        const token = await getToken();
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), window.CRM_CONFIG.timeout);

        try {
            const response = await fetch('/_api' + path, {
                ...options,
                credentials: 'same-origin',
                signal: controller.signal,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'OData-MaxVersion': '4.0',
                    'OData-Version': '4.0',
                    '__RequestVerificationToken': token,
                    ...(options.headers || {})
                }
            });

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

            return response.status === 204 ? null : response.json();
        } finally {
            clearTimeout(timer);
        }
    }

    window.crmClient = {
        getContact(contactId) {
            return portalApi(`/contacts(${contactId})?$select=firstname,lastname,emailaddress1`);
        },
        updateContact(contactId, data) {
            return portalApi(`/contacts(${contactId})`, {
                method: 'PATCH',
                body: JSON.stringify(data)
            });
        }
    };
</script>

An update returns 204 with no body, so there is nothing to parse. There is no retry loop either: a retried PATCH is a repeated write. Endpoints for other systems, such as an email provider, live in settings the same way, but their keys belong in a Key Vault-backed environment variable and the call is made from a cloud flow or server logic, never from the browser.

4. Security settings

Session length, password rules and lockout are not things page JavaScript decides. A timer in the browser cannot extend or end the server session, and a client-side password check is a convenience the server does not trust. They are site settings:

Site setting What it controls Default
Authentication/ApplicationCookie/ExpireTimeSpan How long the authentication cookie stays valid 24:00:00
Authentication/ApplicationCookie/SlidingExpiration Reissue the cookie on requests past the halfway point True
Authentication/UserManager/PasswordValidator/RequiredLength Minimum password length 8
Authentication/UserManager/PasswordValidator/RequireNonLetterOrDigit Require a special character False
Authentication/UserManager/PasswordValidator/RequireDigit Require a number False
Authentication/UserManager/PasswordValidator/RequireUppercase Require an uppercase letter False
Authentication/UserManager/MaxFailedAccessAttemptsBeforeLockout Failed sign-ins before lockout 5
Authentication/UserManager/DefaultAccountLockoutTimeSpan How long the lockout lasts 24:00:00
Authentication/LoginThrottling/MaxInvaildAttemptsFromIPAddress Failed sign-ins allowed from one IP address in the throttling window

The password and lockout settings apply to local accounts, which Microsoft recommends you retire in favour of an external identity provider. Once you do, the provider owns password policy and MFA, and the cookie settings are what remain on the portal side.

5. Content and language settings

Languages are not something you configure in a custom setting. Enable them on the website, and the language object tells you which one the request is in:

<div class="language-settings">
    <p><strong>Current language:</strong> {{ language.name }} ({{ language.code }})</p>
    {% include 'Languages Dropdown' %}
</div>

<script>
    window.CONTENT_CONFIG = {
        language: '{{ language.code }}'
    };
</script>

What this leaves out is content versioning and automatic translation. Neither is a portal feature, so a toggle for them is a toggle for something you would have to build elsewhere.

What this looks like in practice

The site header for a corporate portal, driven by settings:

<!-- Header web template -->
{% assign env = settings['Environment/Name'] | default: 'development' %}
{% assign debug_mode = settings['Environment/DebugMode'] | boolean | default: false %}
{% assign monitoring_enabled = settings['Environment/PerformanceMonitoring'] | boolean | default: false %}
{% assign advanced_search_enabled = settings['Feature/AdvancedSearch/Enabled'] | boolean | default: false %}
{% assign new_dashboard_enabled = settings['Feature/NewDashboard/Enabled'] | boolean | default: false %}

{% unless env == 'production' %}
    <div class="environment-banner {{ env | escape }}">
        <span class="env-label">{{ env | upcase | escape }} ENVIRONMENT</span>
        <span class="env-warning">This is not the live site</span>
        {% if debug_mode %}
            <span class="debug-indicator">DEBUG MODE ENABLED</span>
        {% endif %}
    </div>
{% endunless %}

<nav class="main-navigation">
    <div class="nav-brand">
        <a href="/">{{ website.adx_name | escape }}</a>
    </div>

    <div class="nav-links">
        <a href="/">Home</a>
        <a href="/products">Products</a>
        <a href="/support">Support</a>

        {% if advanced_search_enabled %}
            <a href="/search/advanced">Advanced Search</a>
        {% endif %}

        {% if new_dashboard_enabled %}
            <a href="/dashboard/v3" class="beta-link">Dashboard <span class="beta-badge">BETA</span></a>
        {% else %}
            <a href="/dashboard">Dashboard</a>
        {% endif %}

        {% if user %}
            <a href="/profile">{{ user.fullname | escape }}</a>
            {% if user.roles contains 'Administrators' %}
                <a href="/admin">Administration</a>
            {% endif %}
            <a href="{{ website.sign_out_url_substitution }}">Logout</a>
        {% else %}
            <a href="{{ website.sign_in_url_substitution }}">Login</a>
        {% endif %}
    </div>
</nav>

{% if user.roles contains 'Administrators' and debug_mode %}
    <div class="admin-feature-panel">
        <h4>Feature Toggles</h4>
        <ul>
            <li>Advanced search: {{ advanced_search_enabled }}</li>
            <li>New dashboard: {{ new_dashboard_enabled }}</li>
            <li>Performance monitoring: {{ monitoring_enabled }}</li>
        </ul>
        <p>Change these under Site Settings in the Power Pages Management app, then clear the cache.</p>
    </div>
{% endif %}

{% case env %}
    {% when 'development' %}
        <div class="dev-notice">
            <p>Development environment. Logging level: {{ settings['Environment/LoggingLevel'] | default: 'warn' | escape }}</p>
        </div>
    {% when 'staging' %}
        <div class="staging-notice">
            <p>Staging mirrors production for final testing. Data may be reset.</p>
        </div>
{% endcase %}

<script>
    window.PORTAL_CONFIG = {
        environment: '{{ env | escape }}',
        debug: {{ debug_mode }},
        monitoring: {{ monitoring_enabled }},
        features: {
            advancedSearch: {{ advanced_search_enabled }},
            newDashboard: {{ new_dashboard_enabled }}
        },
        crmTimeout: {{ settings['Integration/Crm/Timeout'] | integer | default: 30000 }}
    };

    window.trackFeatureUsage = function (feature, action, metadata) {
        if (window.PORTAL_CONFIG.debug) {
            console.log('Feature usage:', feature, action, metadata || {});
        }
    };

    if (window.PORTAL_CONFIG.monitoring) {
        window.addEventListener('load', function () {
            const [navigation] = performance.getEntriesByType('navigation');
            if (navigation) {
                window.trackFeatureUsage('page', 'load', { milliseconds: Math.round(navigation.duration) });
            }
        });
    }

    window.addEventListener('error', function (event) {
        console.error('Error:', event.message, event.filename, event.lineno);
    });
</script>

What this leaves out is anything that writes configuration from the page. Toggles change in the Management app or through environment variables in a pipeline, and health checks for integrations live with the integrations, not in the header.

How to make a mess and fix it

  1. Wrong environment detected - check which value the site setting resolved to, and clear the cache after changing an environment variable
  2. Toggles fighting each other - look for conflicting dependencies and overlapping role lists
  3. Integration failing - you need health checks and a fallback, not just a try/catch
  4. Config drift between environments - automate validation, or it will happen
  5. Config loading costing you time - environment variables are for ALM settings and secrets; binding every site setting to one degrades performance

Governance, briefly

Put configuration in version control like everything else. Keep environments as similar as you can afford. Test config changes automatically. Have a rollback that works. And document the options, because “what does this setting do” is a question someone will ask at 2am.

Wrapping up

Good configuration architecture is what lets you deploy on a Tuesday afternoon without a knot in your stomach. Hierarchy, toggles, environment awareness, and enough governance to keep it honest.

Next: JavaScript frameworks, and building interactive interfaces on top of Power Pages.