0

So I've built a simple MERN app using create-react-app, that I want to deploy to Heroku. I build the front end in a client folder operating on localhost:3000, that sends requests to my express sever as a proxy to localhost:5000. My file structure is as follows:

+client
   |
   +-node_modules
   +-public
   +-src
     |
     +-components
        +-App.js
        +-index.js
//server
+-models
+-node-modules
+-package-lock.json
+-package.json
+-server.js

And I've set up the proxy in my package-json like this: "proxy": "http://localhost:5000",

So my main question is this: How do I configure my API endpoints for deployment?

At the moment, they're structured like this:

API call from react component:

  useEffect(() => {
    axios.get("http://localhost:5000/api/all-cafes")
      .then((cafe) => {
        setCafe(cafe.data);
      })
      .catch((err) => {
        console.log(err);
      })
  }, [])

Express function on server.js

app.get('/api/all-cafes', (req,res) => {
    Cafe.find()
    .then((result) => {
        res.send(result)
    })
    .catch(err => {
        console.log(err)
    })
})

My other question is what is the role of the .env file, and will I need to make one in order to solve this?

I've had a helpful suggestion saying that I can run the front end and back end on different servers, and adjust the code depending on whether it is in development or production, using the following code:

const prefix = process.env.NODE_ENV === 'production' ? "http://heroku_app_address" : "http://localhost:5000"
function getUrl(relativeUrl) {
   return prefix + "/" + relativeUrl;
}

fetch(getUrl('api/all-reviews'));

But I'm not sure how to implement this, whether I need a .env file, and if so, what to put in said file.

Josh Simon
  • 159
  • 1
  • 10
  • 27

1 Answers1

1

The .env file helps you specifiy certain credentials or endpoints that are either going to change based on deployment environment (dev,qa,prod may have differewnt API endpoints), or you want to provide certain secret keys or configurations, which otherwise should not be part of your code repository (clientSecret etc).

The create-react-app.dev/docs has detailed explanation to these.
If you have not bootstraped your app using create-react-app then you can use dot-env npm package. The steps are detailed here: Stack overflow :Adding an .env file to React Project

Rohit Khanna
  • 693
  • 5
  • 15