Node.js 12 applications failing by Optional chaining

1 minute read | By Edison Garcia

Node.js version 14 has included Optional Chaining (?.) operator as part of the updates/hightlights, which enable JavaScript developers to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

This change can be affecting Node.js <=12 applications which have npm modules dependencies that are implementing optional chaining in their code.

Nodejs12-chaining-operator

(Screenshot taken from https://node.green)

Some scenarios are described below:

npx serve -s

When running npx serve -s without having installed the module before, it will fetch the latest version (currently v14). This new version requires at least Node.js 14 version to run, otherwise it will fail with the following error:

npx serve -s
npx: installed 91 in 29.345s
file:///root/.npm/_npx/108/lib/node_modules/serve/build/main.js:130
      url.port = url.port ?? "3000";
                           ^
SyntaxError: Unexpected token '?'
    at Loader.moduleStrategy (internal/modules/esm/translators.js:140:18)
    at async link (internal/modules/esm/module_job.js:42:21)

Mitigation

You can mitigate this error with the following options:

  1. Run npx serve@13 -s, which will pull the latest 13 version (13.0.4) Or
  2. Install server@13.x version with npm install serve@13.0.4 --save and then you can use npx serve -s and it will pull the version from node_modules folder Or
  3. Upgrade your application to use Node.js 14 version.

Other scenarios

You can find other issues reported by the community: