web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Power Platform Community / Forums / Power Apps / Get Value of Environme...
Power Apps
Answered

Get Value of Environment Variable using JavaScript

(1) ShareShare
ReportReport
Posted on by 2

How can I get the value of an Environment Variable using JavaScript?

I have the same question (0)
  • the365bit Profile Picture
    136 on at
    Spoiler (Highlight to read)
     
     

    What kind of environment variable and also where is your javascript sitting, is it a js running in a power apps model driven entity form, canvas app, or something else?

  • EricRegnier Profile Picture
    8,720 Most Valuable Professional on at

    Hi @alanodev,

    You can do this with the out-of-the-box client web api script, retrieveRecord.

     

    Xrm.WebApi.retrieveRecord("environmentvariablevalue", <GUID>, "?$select=value").then(successCallback, errorCallback);

     

    Note: the GUID of the environment variable value will be the same in the different environments if you imported the variable with a solution. If you want to fetch by the name and you need to query with EnvironmentVariableDefinition entity.

     

    More info on retrieve: https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrieverecord

    Hope this helps!

     

  • Verified answer
    EricRegnier Profile Picture
    8,720 Most Valuable Professional on at

    Hi @alanodev, I know this dates a while back but just thought I'll update this thread with the latest code sample to retrieved by environmental variable name:

    async GetEnvironmentVariableValue function (name) {
     let results = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", `?$filter=schemaname eq '${name}'&$select=environmentvariabledefinitionid&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)`);
    
     if (!results || !results.entities || results.entities.length < 1) return null;
     let variable = results.entities[0];
     if (!variable.environmentvariabledefinition_environmentvariablevalue || variable.environmentvariabledefinition_environmentvariablevalue.length < 1) return null;
    
     return variable.environmentvariabledefinition_environmentvariablevalue[0].value;
    }

    Note: users will need read privileges to Environment Variable Definition.

    Cheers

  • Kuyler Profile Picture
    4 on at

    To get the correct value use the "RetrieveEnvironmentVariableValueRequest" request with execute.
    Example can found here: https://mytrial365.com/2021/03/15/get-environment-variables-value-using-javascript/

  • EricRegnier Profile Picture
    8,720 Most Valuable Professional on at

    Thanks @Kuyler! Yup, there’s now an out of the box function for this: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveenvironmentvariablevalue
    cheers

  • Jens Borowy Profile Picture
    5 on at

    Here is another example, This code expects an environment variable type JSON, example { "Url":"<URL>", "Login":"<LOGIN>", "PW":"<Password>" }

     

     // Schemaname of the environment variable 
     var connectionDataEnVariable = "<YourEnviromentVariableSchemaName>";
     // var results = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", "?$filter=schemaname eq " + connectionDataEnVariable + "&$select=environmentvariabledefinitionid&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)");
    
     Xrm.WebApi.retrieveMultipleRecords("environmentvariablevalue", "?$select=value&$expand=EnvironmentVariableDefinitionId($select=schemaname)&$filter=EnvironmentVariableDefinitionId/schemaname eq '" + connectionDataEnVariable + "'").then(
     function success(results) {
    
     debugger;
     if (results && results.entities && results.entities.length >= 1) {
     var connectionData = results.entities[0].value;
     }
     else {
     // Die Umgebungsvariable existiert nicht
     alert("Umgebungsvariable " + connectionDataEnVariable + " wurde nicht gefunden.");
     return;
     }
    
     if (connectionData) {
     // Die Umgebungsvariable existiert
     var data = JSON.parse(connectionData);
     var url = data.Url;
     var login = data.Login;
     var pw = data.PW;
    
     console.log("URL: " + url);
     console.log("Login: " + login);
     console.log("Passwort: " + pw);
     }
     },
     function (error) {
     debugger;
     console.log(error.message);
     }
     );

     



  • knunde Profile Picture
    15 on at

    "Note: the GUID of the environment variable value will be the same in the different environments if you imported the variable with a solution."

    I know this is an old comment, but at this moment this statment is wrong. The GUID will differ based on the environments, even if you import it as part of a solution. Hopes this could save others some time.

  • Suggested answer
    dmb Profile Picture
    12 on at
    You can use these functions:
     
        /**
         * @param variableSchemaName string
         * @returns Returns undefined if env var doesn't exist.
         * Returns the default value if the currently value is null or if no value exists yet.
         * The default value can be null.
         */
        async function getEnvironmentVariableValueUsingFunction(variableSchemaName) {
            try {
                const request = {
                    'DefinitionSchemaName': variableSchemaName,
                    getMetadata: () => {
                        return {
                            boundParameter: null, // undefined = CRUD, null = no table bound, 'entityLogicalName' = if bound to a table
                            operationName: 'RetrieveEnvironmentVariableValue', // action, function or CRUD opetaion name ('Create', 'Retrieve', 'Update', or 'Delete')
                            operationType: 1, // 0 = Action, 1 = Function, 2 = CRUD
                            parameterTypes: {
                                'DefinitionSchemaName': {
                                    typeName: 'Edm.String',
                                    structuralProperty: 1 // 0 = Unknown, 1 = PrimitiveType, 2 =ComplexType, 3 = EnumerationType, 4 = Collection, 5 = EntityType
                                }
                            }
                        }
                    }
                };
                const response = await Xrm.WebApi.online.execute(request);
                const data = await response.json();
                return data.Value;
            } catch (error) {
                console.log(error);
                const baseUrl = Xrm.Utility.getGlobalContext().getClientUrl();
                const methodUrl = `/api/data/v9.2/RetrieveEnvironmentVariableValue(DefinitionSchemaName='${variableSchemaName}')`;
                const response = await fetch(baseUrl + methodUrl);
                const data = await response.json();
                return data.Value;
            }
        }
     
        /**
         * @param variableSchemaName string
         * @returns Returns undefined if env var doesn't exist.
         * Returns the default value if the currently value is null or if no value exists yet.
         * The default value can be null.
         */
        async function getEnvironmentVariableValueUsingQuery(variableSchemaName) {
            const result = await parent.Xrm.WebApi.retrieveMultipleRecords(
                `environmentvariabledefinition`,
                `?$select=displayname,schemaname,defaultvalue` +
                `&$expand=environmentvariabledefinition_environmentvariablevalue($select=value,createdon;$orderby=createdon desc)` +
                `&$filter=(schemaname eq '${variableSchemaName}')`
            );
            const value = result.entities[0]?.environmentvariabledefinition_environmentvariablevalue[0]?.value
            if (value === undefined || value === null) { // keep 0, false, '' as valid values
                return result.entities[0]?.defaultvalue
            } else {
                return value;
            }
        }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Season of Sharing Community Challenge Winners!

Congratulations to our community stars!

Kudos to our 2025 Community Spotlight Honorees

Expanding mentorship, skilling, and AI innovation

Congratulations to the June Top 10 Community Leaders!

These are the community rock stars!

Leaderboard > Power Apps

#1
WarrenBelz Profile Picture

WarrenBelz 352 Most Valuable Professional

#2
11manish Profile Picture

11manish 192

#3
Valantis Profile Picture

Valantis 128

Last 30 days Overall leaderboard