Hyrule
Hyrule

Reputation: 645

How to connect webpack dev server to express?

I'm running BOTH an express and create-react-app app. They are seperate entities during development and express is just an endpoint which we communicate through 'proxy' field in package.json proxy: 'http://localhost:5000. During production, I run yarn build and serve the static index.html inside build folder through catch-all-route in Express.

// RENDER REACT STATIC INDEX.HTML FROM BUILD
if(process.env.NODE_ENV === 'production') {
  app.get('/*', (req, res) => {
    res.sendFile(path.join(__dirname, '../client/build', 'index.html'))
  })
}

Okay so, there is huge difference during production and development. For instance, if I navigate to /pages/plainhtmlfile during production, I can serve the .EJS file if route matches. Because during production there is only Express running, which serves static files including React build folder index.html.

//THIS WORKS DURING PRODUCTION, NOT WORKING DURING DEVELOPMENT.
app.get('/plainhtmlfile', (req, res) => {
  res.render('nonreactpage')
})

How to do development where it's possible to serve '/plainthtmlfile'? Right now create-react-app is a seperate process running on port 3000 and express port 5000 during dev.

Upvotes: 3

Views: 5687

Answers (1)

jordiburgos
jordiburgos

Reputation: 6302

Use the webpack-dev-server proxy. It works in the development environment redirecting the URLs to the server you point to.

For example, your config should look like this, as the express server is in the port 5000

proxy: {
  "/plainhtmlfile": "http://localhost:5000"
}

The keys can contain wildcards so, this one will redirect all the URLs that start with /api/

proxy: {
  "/api/**": "http://localhost:5000"
}

https://webpack.js.org/configuration/dev-server/#devserverproxy

Upvotes: 8

Related Questions