Laravel Mix environment variables in GitHub Actions workflows

Published on

You can use Laravel Mix to inject environment variables from your .env file into your JavaScript bundle. When building your application in a CI pipeline like GitHub Actions, you need to set the variables before you run npm run production.

Environment variables

Laravel Mix makes two types of variables available in your JavaScript bundle:

Variables defined in your environment take precedence over variables from your .env file. For example, if you run this in your terminal:

MIX_PUSHER_APP_KEY="FROM_BASH"  

And your .env file contains:

MIX_PUSHER_APP_KEY="FROM_DOT_ENV"

Then this is the result in your JavaScript bundle:

process.env.MIX_PUSHER_APP_KEY === "FROM_BASH"

Using variables in your GitHub Actions workflow

You can set environment variables in a build step of your GitHub Actions workflow with the env key. Any variable defined will be available in your JavaScript bundle via the process.env object.

- name: Build JavaScript bundle
  run: |
    npm ci
    npm run production
  env:
    MIX_PUSHER_APP_KEY: "a13bb07667096c3f82"
    MIX_PUSHER_APP_CLUSTER: "eu"

Using defaults from your .env.example

You can also define default values in your .env.example file. You can use these defaults in your workflow by turning the example file into the real .env file:

- name: Build JavaScript bundle
  run: |
    cp .env.example .env  
    npm ci
    npm run production
  env:
    MIX_PUSHER_APP_KEY: "this value takes precedence"    

Remember that any value defined in the env key will override what is in your .env file.

Multiple environments

If you deploy multiple environments with the same workflow, they might need different variables. The example below shows how to build your bundle for two different branches.

- name: Build JavaScript bundle for production
  if: github.ref == 'refs/heads/main'
  run: |
    npm ci
    npm run production
  env:
    MIX_PUSHER_APP_KEY: "a13bb07667096c3f82"
    MIX_PUSHER_APP_CLUSTER: "eu"

- name: Build JavaScript bundle for staging
  if: github.ref == 'refs/heads/develop'
  run: |
    npm ci
    npm run production
  env:
    MIX_PUSHER_APP_KEY: "c611e00e2ab864a1ef"
    MIX_PUSHER_APP_CLUSTER: "us"

Don't use secrets

Any variable that you use in your javascript bundle will be exposed to the user on the front-end. This means you should never use secrets in your javascript. Secrets belong in the back-end.

Since the variables aren't secrets, you can put them in plain text in your workflow file. This more convenient than defining them as workflow secrets in your repository.

Do you want to deploy Laravel with GitHub Actions?

I've spent an unreasonable amount of time making the perfect deployment script for Laravel.

Deploy Laravel with GitHub Actions