Skip to content

Optional chaining operator gives SyntaxError when building my application to Heroku but works on my machine

I am using the optional chaining operator in my application, for instance:

object?.optionalField && this.doSomething(object.optionalField)

(checks if optionalField exists, then do something with it)

The above code works perfectly on my machine but it gives me an error when I try to build this code on Heroku. Here is what the logs say:

2020-08-06T06:39:09.697171+00:00 app[web.1]: > node app.js
2020-08-06T06:39:09.697171+00:00 app[web.1]:
2020-08-06T06:39:09.760703+00:00 app[web.1]: (node:23) ExperimentalWarning: The ESM module loader is experimental.
2020-08-06T06:39:09.905459+00:00 app[web.1]: file:///app/domain/roots/User.js:49
2020-08-06T06:39:09.905462+00:00 app[web.1]:     changes?.biography && this.setBiography(changes.biography)
2020-08-06T06:39:09.905462+00:00 app[web.1]:             ^
2020-08-06T06:39:09.905463+00:00 app[web.1]:
2020-08-06T06:39:09.905463+00:00 app[web.1]: SyntaxError: Unexpected token '.'
2020-08-06T06:39:09.905464+00:00 app[web.1]:     at Loader.moduleStrategy (internal/modules/esm/translators.js:122:18)
2020-08-06T06:39:09.915755+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-08-06T06:39:09.917824+00:00 app[web.1]: npm ERR! errno 1
2020-08-06T06:39:09.920740+00:00 app[web.1]: npm ERR! [email protected] start: `node app.js`
2020-08-06T06:39:09.920870+00:00 app[web.1]: npm ERR! Exit status 1
2020-08-06T06:39:09.920998+00:00 app[web.1]: npm ERR!
2020-08-06T06:39:09.921159+00:00 app[web.1]: npm ERR! Failed at the [email protected] start script.
2020-08-06T06:39:09.921732+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-08-06T06:39:09.933019+00:00 app[web.1]:
2020-08-06T06:39:09.933279+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-08-06T06:39:09.933437+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-08-06T06_39_09_923Z-debug.log

Does anyone know why is that? I suspect I should compile the code first using Babel and then deploy to Heroku? Is it even related to Babel?


Does anyone know why is that?

Locally you’re using a recent version of Node.js that supports the optional chaining operator. Apparently Heroku is using an older version of Node.js that doesn’t. (Optional chaining is fairly new.)

I suspect I should compile the code first using Babel and then deploy to Heroku? Is it even related to Babel?

That’s one option. Or you might look to see if Heroku offers options for what Node.js version is used in hopes that a more recent version of Node.js is available. I see the “ExperimentalWarning: The ESM module loader is experimental.” which tells us the version Heroku is using is < v14. Or if this is the only place you’re using optional chaining, you could use

object && object.optionalField && this.doSomething(object.optionalField);

or preferably

if (object && object.optionalField) {