alt j
alt j

Reputation: 11

how to use proxy in react build?

this is the api call i want to make

http://localhost:3000/api/getUserName

but i am using it in proxy in package.json. i tried to build the app but then call goes to

http://localhost:5000/api/getUserName

i am serving on 5000 so its taking api call also on 5000. so i want to mention 3000 om build. also i have check on google and it says mention it in .ENV cause proxy is not for production, but can anyone provide me .ENV structure that can show to me how to use it from env?

Upvotes: 1

Views: 1368

Answers (1)

Rohan Dhar
Rohan Dhar

Reputation: 1837

During development, the practice is to use to two servers; one server for the client side, generally localhost:3000, and a second one for the server, generally localhost:5000. When you build for production, reactjs compiles and builds such that it becomes a static resource for the server and the server serves these files.So, your app will be served, wherever you host your server. The production config will depend on what you folder structure looks like. If you are using CRA for your application, you can use this piece of code:

I am assuming that you have your client directory inside your server directory.

if(process.env.NODE_ENV === 'production'){
      app.use(express.static('client/build') //path to your build directory
      const path = require('path');
      app.get('*', (req, res)=>{
         res.sendFile(path.resolve(__dirname, 'build','public','index.html');
}
}

Again, I am assuming that you are using CRA to bootstrap your react application and have your client directory inside your server directory. If you are using webpack, then the config will change to indicate the path of the build directory.

Upvotes: 1

Related Questions