Search code examples
node.jsbashherokunestjsmicroservices

How to deploy nestjs monorepo to heroku by changing the start screipt?


I have a nestjs monorepo (microservice) project structured like

Project
| .git
| package.json
|
|____app 1
|
|____app 2

The git will push the entire project to the Heroku server and my idea is to build and start each app according to the environment variable.

My attempt is, in Heroku app1, I have configured the environment variable MSERVICE = APP1, In my package.json, the start script is "start": "if [[ $MSERVICE == APP1 ]];then node dist/apps/app1/main;else node dist/apps/app2/main;fi", which works fine in my Macbook.

However, The Heroku throw an error when starting:

 > [email protected] start
 > if [[ $MSERVICE == WEB ]];then node dist/apps/web/main;else node dist/apps/admin-web/main;fi
 /tmp/start-a3a234c5.sh: 1: [[: not found
 node:internal/modules/cjs/loader:959
   throw err;
   ^

I have tried put this start script in to a single start.sh and get the same result.

Seems like Heroku cannot recognize the bash if condition syntax here. Is there anything I missed here or any other solution?


Solution

  • Did some brainstorming, I found the answer actually is quite simple. Using the bash command eval works like a charm.

    First, edit the build and start script in the package.json to

     "build": "eval nest build $BUILD",
     "start": "eval node $MSERVICE",
    

    Second, add the environment variable to the Heroku app 1, in Settings -> Config Vars , BUILD: APP_1_NAME, MSERVICE: dist/apps/APP_1_NAME/main

    Third, set other Heroku microservice app env variables like the second step.

    These steps can help you achieve, push one git commit and deploy all the microservice apps on Heroku accordingly.