3

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?

Kousha
  • 32,871
  • 51
  • 172
  • 296

2 Answers2

1

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/' ]
Kousha
  • 32,871
  • 51
  • 172
  • 296
0

To get current port you can use:

console.log(window.location.port)

window.location also provides more useful information.

Jakub Słowikowski
  • 1,063
  • 1
  • 8
  • 13