How to create & use environment variables in Craft CMS

Oscar de la Hera Gomez
A flower that represents Craft CMS. Beneath it sits the text "Environment Variables."

Add the variable to the .env file in capital letters and use it through the control panel or in code through App::env('ENV_VAR_NAME'), where ENV_VAR_NAME is the name of your variable.

The following tutorial walks you through how to add and use environment variables in Craft CMS.

Please note that you must restart your Craft CMS project for the environment variable to register in the Control Panel.

Step One: Add your variable

A screenshot of the .env file in VSCode.

Open the .env file at the root of your project and add your environment variable.

It is recommended that you use capital letters with "_" for spaces. i.e. my environment variable becomes MY_ENVIRONMENT_VARIABLE.

Step Two: Use your variable

A screenshot of VSCode showing you how to use an environment variable in Craft CMS.

Environment variables can be used in the control panel or in code.

In the Control Panel

If you wish to use it in the control panel, restart your Craft CMS instance by deploying your code or stopping and starting your local environment.

In Code

To use it in code, first import the App craft helper functionality using the following line:

use craft\helpers\App;

Then use the following snippet, replacing ENV_VAR_NAME with the environment variable name that you used in Step One.

App::env('ENV_VAR_NAME')

A sample use of this code can be found in the config/app.php of our starter project.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.

delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details