Home > front end >  How do I access Port Number?
How do I access Port Number?

Time:10-14

I have created .env file in my Reactjs project root directory.

my .env file contain:

PORT = 30001 
...

I'm accessing port in App.tsx file like as:

const PORT_NUMBER = process.env.PORT;

I got change the port number while run yarn start as expected. But I got "undefined" value of PORT_NUMBER

one fixes I know is using dotenv package but for now I don't want to use that one. How can I access port number for now?

CodePudding user response:

You need build your own .env parser if you don't want to use dotenv.

The reason that process.env.PORT result in an undefined is because that Node.js does not read environment variables from .env, Node.js only get the environment variables in your system. That's why you need dotenv or build your own .env parser...

CodePudding user response:

What most React developers don't realize is that the use of dotenv in React is a hack. dotenv is a configuration package for NodeJS applications only. It doesn't work for browser libraries like React. The Meta guys, though, made some scripting magic with Create React App so it somewhat can be used as a configuration mechanism. The whole thing is explained in their website.

Now, I don't really know why you want the port number in React, so I'll just say this much: If you want a configuration package for your React application, have a look at wj-config. It is a zero-dependency configuration library that works perfectly on both NodeJS and React, and probably most (if not all) other browser and server-side frameworks and libraries.

Finally, to complete answering you, I would do the following to get the port of the current page:

const currentUrl = new URL(window.location.href);
const port = currentUrl.port

You can read about the port property at MDN.

  • Related