Notes-log on changing default port for React and Node.js on Windows
Note: This post is a details-post for the post: Learning web app development through free online tutorials – Organized Notes and Log, https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html .
Quick-Info
Starting React on specific port in VSCode
- In Terminal window, $env:port=4002 [followed by npm start]
- In package.json, "start": "set PORT=5000 && react-scripts start", [followed by npm start in Terminal]
Starting React on specific port in Command Prompt window (not Powershell window)
- set PORT=4001 [followed by npm start]
Notes-Log
React
How to Change the Default Port Number in React: React Tips, https://blog.stackademic.com/how-to-change-the-default-port-number-in-react-react-tips-1a957b54759e
set PORT=4001
Issuing 'set' command after that listed PORT with new value of 4001 (earlier value was 4000). echo %port% also works to show only port variable value.
Running npm start afterwards resulted in React using 4001 as the port, with the app opening in browser at: http://localhost:4001/
But VSCode terminal is a powershell terminal. 'set PORT=4001' does not seem to change PORT environment variable value.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-7.4 is useful.
'$Env:PORT' displays PORT env var value.
Following command:
$Env:PORT = "4002"
sets PORT to 4002. [$env:port=4002 also works.]
Tried above in VSCode terminal. It worked. Then invoked 'npm start'. React used 4002 as port with browser opening page URL: http://localhost:4002/ .
$Env:PORT = "4004"; npm start
Ref: https://stackoverflow.com/questions/1420719/powershell-setting-an-environment-variable-for-a-single-command-only
"start": "$Env:PORT = '4003'; react-scripts start",
But the following line in package.json, worked with 'npm start' opening app on http://localhost:5000/ :
"start": "set PORT=5000 && react-scripts start",
PORT=4010
did not work! Later I understood why it did not work. Environment variable set up for Create React App projects (like React blog tutorial app) is described in create react app documentation. It states that the name has to start with REACT_APP_. https://stackoverflow.com/questions/49579028/adding-an-env-file-to-a-react-project gives procedure for non create react app projects where dotenv package is used additionally (like in node express case, if I recall correctly).
In .env file, unquoted values are automatically quoted by dotenv. Ref: What rules does the parsing engine follow?, https://www.npmjs.com/package/dotenv?activeTab=readme#what-rules-does-the-parsing-engine-follow . An extract from it:
----
So it seems that it doesn't matter whether we quote the value or not, for .env files that are read by dotenv package. But I think it may be a good practice to quote environment variable values unless the example code we are following itself does not quote the value.
Comments
Post a Comment