Using process.env when react server side rendering

4.8k Views Asked by At

I have a react app that works pretty well client-side and am now attempting to have it work server-side.

I am using it with the create-react-app boilerplate: https://github.com/facebookincubator/create-react-app

I am running into an issue where I store some environment variables in .env, however on the server I cannot access these variables.

So a line such as axios.get(process.env.API_URL + 'something') will through a 404 because process.env.API_URL is undefined.

It is my understanding that .env is the file I should be using for stuff like this. Am I incorrect? Should I be using another method to store common environment variables? Or is there some way to get the node server to recognize these values?

2

There are 2 best solutions below

0
On BEST ANSWER

You can (should) serve the production build.

When you make npm run build webpack takes the entries on your .env file and replaces them on the build with the corresponding values.

For server-side rendering you'll have to define the environment variables in your node server, either as system environment variables or on a .env read by your back-end server (which could be the one webpack-dev-server is using).

0
On

According to Create React App docs, in order to expose environment variables to React both in static and SSR apps, the variable names must be prefixed with REACT_APP_. This prevents sensitive and/or unnecessary variables from being included in the javascript bundle.