app.js unable to get environment variable when deploy using Laravel envoy

707 Views Asked by At

I want to deploy my application with envoy so to ensure there will be zero downtime. After some research i found that this script worked exactly what i want. https://github.com/papertank/envoy-deploy

Basically for backend everything worked well. I able to clone the project, execute all command and point it to latest project. After that i added a new task for npm for my vue components. This is the task

@task('deployment_assets')
   echo 'Running npm'
   cd {{ $release }}
   sudo npm ci --production
   sudo npm audit fix --only=prod
   sudo npm run prod
@endtask

To do this, i move my laravel mix related dependencies from devDependencies to dependencies.

"dependencies": {
        "laravel-mix": "^6.0.31",
        "resolve-url-loader": "^4.0.0",
        "sass": "~1.32.0",
        "sass-loader": "^11.0.1",
        "vue-loader": "^15.9.5",
        "webpack": "^5.23.0"
    },

When running the task, first issue happen, it seem like my webpack.mix.js unable to read the variable. When calling process.env.APP_URL it returned undefined. This is the syntax.

if (process.env.APP_URL.match(/https?:\/\/.*\/.+/)) {
   mix.setResourceRoot(process.env.APP_URL);
}

This is my .env look like

APP_DEBUG=true
APP_URL=http://homestead.test

After i checked laravel mix isssues, they suggest to use

require('dotenv').config({ path: '~/www/app/.env'});

to load the environment variable.

So i change webpack.mix.js to become

const mix = require('laravel-mix');
require('dotenv').config({ path: '~/code/app/.env'});

Ok it worked, now i able to retrieve all the variables via process.env. The task is completed. Then when i navigate to my project, second issue happened.

My app.js unable to get the process.env, it returned {} when i console.log(process.env)

if (process.env.APP_URL.match(/https?:\/\/.*\/.+/)) {
//
}

I can confirm that the .env was there, otherwise it gonna throw error when running npm run prod Just not sure why it unable to retrieve the env variable in app.js

I know this might be not the best practice to compile assets in production. But this is necessary for my case because my vue components shared the same environment variables from .env file, so i need to compile the assets in server to make sure it using the production .env file.

Does anyone know how to solve this?

1

There are 1 best solutions below

0
masterhunter On

Okay after some troubleshooting, can confirm to get the environment variables in mix, the prefixed with MIX_ is a must. Make sure you run php artisan config:cache after alternated the .env variable so that the variables was the latest version, at the begining i was confused why it still worked when the prefix MIX_ removed, turn out that is cache issue.