Use environment variables in your component code
When you have an environment variable configured in your component, and a value set for it either locally or through the component set, you can reference the variable within your JavaScript code server side. You can then implement some logic, behavior, or rendering based on the value in the environment variable.
To use an environment variable in your code:
-
Open the component main.cjs JavaScript file in your code editor.
-
For this example, BRAND_PRIMARY_COLOR is the variable. Update the code in your component main.cjs to the following code example:
module.exports = async function (input, info) { (1) const BRAND_PRIMARY_COLOR = info.set.environment.BRAND_PRIMARY_COLOR; (2) return `<div style="background: ${BRAND_PRIMARY_COLOR};"> ${input.text} </div>`; (3) }
1 The main function must have the info
object in its method signature.2 Access the value of the environment variable from info.set.environment.VARIABLE_NAME
.3 Add a <div>
tag to set the background of the output theBRAND_PRIMARY_COLOR
. -
Run the local development server, as described in Test using the local development server.
Test your code on the local development server
If you are testing locally with your local development server, you must set the environment variable locally, by running the following command:
BRAND_PRIMARY_COLOR=red dxp-next cmp dev ./
OR
Follow the instructions in Set environment variables locally.
Read Test using the local development server to learn how to test your component locally.
Test your code on the Squiz DXP
If you set your environment variable in the Squiz Digital Experience Platform (DXP) component set, you must deploy your component to the DXP to test it.
Read Deploy your component to the DXP to find out how to deploy your component to the DXP.
Next, you must add the component to a Squiz Content Management Service page to test the environment variable.
Read Add a component set to a site and Add your component to a Squiz Content Management Service page to find out how to test your component and environment variables in Squiz Content Management Service.
Like the image above, you will now see the component with a background color set by the BRAND_PRIMARY_COLOR environment variable.