Search code examples
javascriptreactjswebpackcreate-react-app

How to use webpack devServer proxy in create react app


I'm creating a new app by using create-react-app and I want to add some proxies for my code. Previously I have used webpacks devServer

module.exports = {
  ...
  devServer: {
    proxy: {
      '/api/context*': {
        target: 'http://some.endpoint.com',
        headers: myCustomerHeaders,
        pathRewrite: (path, res) => changeThePath
      }
    }
  }
  ...
}

I have tried using the same approach in both webpack.config.dev.js and the webpackDevServer.config.js as well as putting it start.js as proxyConfig that is being passed to the webpackDevServer.config.js.

I see writings of src/setupProxy.js but is it applicable without expressJs running somewhere? Anyway I tried it without any result. The paths I'm proxying to are test environment api's that I wish to use.

I have used create-react-app as a new skeleton for an old application to upgrade it, my old project works with the proxy settings.

Now that I'm using create-react-app, I expected the same way be plausible, but it seems I am wrong. Any takers of what I am doing wrong?


Solution

  • You can use "http-proxy-middleware"

    https://github.com/chimurai/http-proxy-middleware

    var express = require('express')
    var proxy = require('http-proxy-middleware')
    
    var app = express()
    
    app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
    app.listen(3000)