Setting environment variables for React scripts can be done by leveraging the process.env object

Currently, I am in the process of developing a project that encompasses both backend and frontend components. It struck me as a great idea to have both sets of code housed within the same directory, complemented by another npm script responsible for running them simultaneously.

The only issue I encountered is the inability to configure the port setting specifically for the frontend package. Within my main package.json file, I have included the following:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start-app": "cross-env SERVER_PORT=8080 npm start --prefix ./frontend",
    "start-server": "cross-env SERVER_PORT=8080 npm start --prefix ./backend"

This setup functions perfectly for the backend, yet falls short when applied to the frontend section.

It should be noted that the frontend boasts a standard configuration:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"

Upon examining the project's environment variables, it becomes apparent that while the SERVER_PORT value is present in the backend, it remains absent from the frontend set-up.

(Typical scripts found within a new npm package are utilized for the Backend):

"scripts": {
    "start": "node main.js",
    "test": "echo \"Error: no test specified\" && exit 1"

Answer №1

In the context of CRA, the PORT variable is used to define the port. To run it, use the following command:

"start": "PORT=8000 react-scripts start"

Furthermore, since CRA is essentially a static site, it does not have its own concept of environment variables - these are specific to NodeJS. Some predefined variables like PORT and NODE_ENV are automatically available and utilized in the development server. If you need to use custom environment variables within your React components, you can do so by defining them with the prefix: REACT_APP_, for example, REACT_APP_SITENAME.

For more information, refer to the documentation here: https://create-react-app.dev/docs/adding-custom-environment-variables/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data from the Sequelize database where the createdAt date matches the current date

When working with the Express framework and Sequelize, I encountered an issue while trying to select a user's first name and last name based on a specific date that matches the createdAt field. Below is the query I used: const userData = models.users ...

`Is it possible to modify the background color of InputAdornment in Material-UI TextField?`

For the first 10% of the text field, one background color is used, while for the remaining 90%, another background color is applied. <TextField className={classes.root} type="text" placeholder="username" var ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

How to import a node module into an Angular app through Angular CLI and load children in

My goal is to import a module from the node modules. This particular node module contains routes that I need to access. Here's what I want to achieve: I aim to configure my app.module to incorporate loadChildren from the module within my node module ...

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Node.js request body is not returning any data

UPDATE: @LawrenceCherone was able to solve the issue, it's (req, res, next) not (err, res, req) I'm in the process of building a MERN app (Mongo, Express, React, Node). I have some routes that are functioning well and fetching data from MongoDB. ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Retrieving data from MongoDB for rendering on an HTML page

I have successfully inserted data into my MongoDB database, but I am facing issues with the "get" function to display this data on my HTML page. My current setup involves using Node.js with Express framework and Angular for front-end development and routi ...

Rendering EJS templates and smoothly scrolling to a specific section on a webpage

I need to display my index page and automatically scroll down to the form section. One way I thought of doing this is by: app.post('/rsvp', (req, res) => { res.render('index/#rsvp', { errors: { email: 'Your email has already ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

Understanding the differences between npm install and npm update

I've been diving into the nuances between package.json and package-lock.json Recently, I decided to experiment with a package that has only one dependency called chance Upon initial installation using npm i <a href="/cdn-cgi/l/email-protection" c ...

Using either Google Maps or a customized mapping solution in a React Native application

I am currently developing an application that allows users to input addresses and locate them on a map. I am wondering if implementing AI technology or utilizing specific libraries is necessary in order for this feature to function properly within a reac ...

Mistakes While Running Cordova Commands (Maka-CLI Application on an Android Device)

Recently, I attempted to launch a Maka-CLI web application on my Android device using the command "maka run android-device". Unfortunately, I encountered an error that persists and displays the following message: => Errors executing Cordova commands: Whi ...

Issue with third-party react module (effector) causing Webpack error

UPDATE: After struggling with my own custom Webpack setup, I decided to switch to using react-scripts, and now everything is compiling smoothly. It seems like the issue was indeed with my Webpack/Babel configuration, but I still can't pinpoint the exa ...

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from Following their documentation, I ran the command: npm install chart.js ...