Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create-react-app + nodejs (express) server

I am using NodeJs + React in my application. I am using express in NodeJs. I created my sample app using 'create-react-app' npm.

I used NodeJs for calling the oauth token from react app. I mentioned this approach in this post Calling a secured REST api from Javascript without user login screen .

I added this command below to start the NodeJs together with my react app. It works.

"scripts": {
  "node": "react-scripts-ts build & node server"
}

The issue is that I don't get the real time tracking feature that comes with 'create-react-app' because I am not starting the webpack-dev-server. If I made some changes, I have to run 'yarn node' to recomple and start the node js server.

My question is how to start the nodejs express without losing the 'create-react-app''s live tracking feature.

If I need to eject the 'create-react-app' and customize the script, I am fine as long as I got the following feature.

  • start nodejs express - api
  • load my react-app
  • if there is any change in my react or nodejs express file, it should auto-reload.

Feel free to let me know if you have any question.

Thanks,

like image 603
Michael Sync Avatar asked Feb 06 '18 03:02

Michael Sync


1 Answers

There's an excellent tutorial on a good way to handle this setup: https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/

To summarize: you can write your node+express server in whatever way you're accustomed to - we'll say this lives in a directory called project - then nest within it a frontend directory created using create-react-app, e.g. project/client.

When you're developing, you'll actually run two servers: the backend server (npm start) and the webpack-dev-server that comes with your nested create-react-app (cd client && npm start). In your browser, you'll navigate to the url being served by webpack-dev-server (localhost:3000 by default).

In production, you don't need to run two servers. You'll bundle your frontend (cd client && npm run build), then your backend server just needs to serve the bundle, for example via express's static middleware:

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'))
}

I skipped over a few details, so do check out the tutorial I linked if this setup sounds right for you.

like image 84
Tyler Hsu Avatar answered Oct 16 '22 04:10

Tyler Hsu