How do I get Heroku to run my node app that's in a subfolder?

Viewed 1618

I have a node app where the entry point is here

/backend/src/index.js

Locally, if I try to run node ./backend/src/index.js from the project root I get lots of pathing errors, but if I cd into the backend folder and run ./src/index.js my node app runs. I assume this is all due to the use of relative paths through the node app.

How can I deploy this app to heroku and have it run correctly? I'm currently getting 503 errors like this

2017-07-31T03:02:17.759410+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=[redacted] ... dyno= connect= service= status=503 bytes= protocol=https

Is there some way to tell heroku to cd into the backend folder before executing the start script? Can I do this with a Procfile?

2 Answers

Heroku requires a package.json and a lockfile in the root of the repository or they will fail the deploy.

However you can set up a package.json in the root of the repo which installs dependencies for the subdirectories and runs their related commands.

Using yarn for example (you can something similar with npm), you could put an empty yarn.lock in the root and a package.json like:

{
  "name": "my-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "postinstall": "yarn --cwd <subdirectory> --production=false install",
    "build": "yarn --cwd <subdirectory> serve"
  }
}

The --production=false is optional, but ensures that devDependencies will be installed, which otherwise wouldn't happen since NODE_ENV is set to production in Heroku's environment.

Heroku's buildpack installs devDependencies by default and then prunes them later, so if you need any of them to build your project as part of deploying it you will need that part.

Related