Steve Johnstone Steve Johnstone - 1 month ago 14x
Node.js Question

Error: Cannot find module './layer' when loading Express in Heroku

I'm currently building a Node.js Express application on Heroku. It works fine locally, but when I upload it to Heroku I get the following error:

2016-09-09T14:14:46.606481+00:00 app[web.1]: [DEBUG] Loading modules...
2016-09-09T14:14:46.607904+00:00 app[web.1]: [DEBUG] Loading express...
2016-09-09T14:14:46.632062+00:00 app[web.1]: module.js:457
2016-09-09T14:14:46.632064+00:00 app[web.1]: throw err;
2016-09-09T14:14:46.632065+00:00 app[web.1]: ^
2016-09-09T14:14:46.632065+00:00 app[web.1]:
2016-09-09T14:14:46.632066+00:00 app[web.1]: Error: Cannot find module './layer'

When I go to look in my local node_modules the file
is present.

I then ran
heroku run bash
and see :

~/node_modules/express/lib/router $ ls
index.js route.js

So I run:

~ $ rm -rf node_modules/
~ $ npm i
~ $ npm start

And it all works fine again. However logging out of heroku bash and it stops working. After that if I then log back in and run
npm start
, it fails with the first message again:

Running bash on little-owl... up, run.6609
~ $ npm start

> little-owl@0.0.1 start /app
> node server.js

[DEBUG] Loading modules...
[DEBUG] Loading express...
throw err;

Error: Cannot find module './layer'

Any ideas?


Heroku is not a VPS. When you heroku run bash, you aren't making any permanent changes to your app's filesystem. That's all done at build time, when you deploy.

From the symptoms here, it looks like your app may have checked in some incomplete node_modules at some time in the past. So first, remove node_modules from git:

$ echo 'node_modules' >> .gitignore
$ git rm -r --cached node_modules
$ git commit -am 'ignore node_modules'

Then, disable your app's cache and push:

$ heroku config:set NODE_MODULES_CACHE=false
$ git push heroku master