Search code examples
javascriptreactjscreate-react-app

Create React App: how to get final port dev-server running on


From https://facebook.github.io/create-react-app/docs/advanced-configuration you can provide your own script to BROWSER environment variable.

On this script, I want to open link to some other page, with a query parameter to redirect to port the dev-server is running on localhost.

Even if I do BROWSER=open.js PORT=4000 npm run start, port 4000 may be taken, which is what choosePort from https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/start.js#L87 does; it finds the first port available around the provided port.

My question is this: given my open.js, how can I find the actual PORT the dev-server is running on?


Solution

  • I found that that the process.argv does in fact contain the URL (with port) of your dev-server.

    console.log(process.argv)
    

    Provides:

    [ '/usr/local/bin/node',
      '/path/to/my/custom/openBrowser.js',
      'http://localhost:3000/' ]