CORS issues when developing locally against a separate API server

Hi Friends!

i’m setting up a redwoodjs app that is supposed to interact with a flask api server running on port 5000.

i typically add a line to my package.json to proxy requests to a localhost:5000
to avoid CORS problems when developing locally
and that doesnt seem to work with Redwood.

image

any ideas? i played around with the redwood.toml and just managed to break graphql :blush:

Thanks for posting this here @tessier0ashpool. We actually solved on discord, but posting here to help others looking for a solution.

Solution currently is to tweak the webpack dev server config.

Step 1: Create webpack config

This should be placed in web/config/webpack.config.js

Step 2: Let’s add our proxy changes

We’re going to add /other-api to proxy to localhost:5000/other-api inour dev server config

module.exports = (config) => {
  config.devServer = {
    ...config.devServer,
    proxy: {
      ...config.devServer.proxy,
      '/other-api': 'http://localhost:5000',
    },
  }

  return config
}

All this is doing is preserving all of the dev server config, but also adding a new proxy path

Step 3: Restart dev server

Stop your RW dev server and run it again yarn rw dev


On a separate note, if you want to proxy in netlify, this is what you use https://docs.netlify.com/configure-builds/file-based-configuration/#redirects

1 Like

this works wonderfully!

my only problem was that i set it up like the above, and if i had a route like ‘/dropdowns’
i was getting requests to ‘/other-api/dropdowns’. so just being mindful of how that works broke it on through for me. cheers @danny!

As @danny mentioned, when deployed to Netlify, the api proxy redirect can handle that via “splats”

/api/* https://api.example.com/:splat 200

So in your case, a /api/dropdowns request can redirect to https://api.example.com/dropdowns and not https://api.example.com/api/dropdowns which I think is what you want (?).

Had a quick look at webpack proxy docs:

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/api' : ''}
      }
    }
  }
};

I think if you

module.exports = {
  //...
  devServer: {
    proxy: {
      '/other-api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/other-api' : ''}
      }
    }
  }
};

That will rewrite the path so the other-api isn’t passed along.

2 Likes