Bad Son
Bad Son

Reputation: 151

How to proxy request in Docusaurus v2?

I'm trying to config my Docusaurus web app to proxy the request to my api endpoint. For example, if I make a fetch request in my app fetch(/api/test), it will proxy the request from localhost:3000/api/test to my {{api_endpoint}}/api/test, but I'm still struggling to do it.

What I've done:

These 2 are based on the Proxying API Requests in Development

webpack plugin

Does anyone have experience on this problem ? Thanks for reading, I really appreciate your help.

Upvotes: 0

Views: 1762

Answers (1)

Kyle Bihler
Kyle Bihler

Reputation: 41

I went down the exact same path. Ultimately Docusaurus runs its Webpack dev server under the hood which is why the proxy field and setupProxy.js were not working as expected. I was able to get the outside API call by proxy and solved CORS errors by creating a Docusaurs plugin like you are attempting. Adding the "mergeStrategy" and "changeOrigin" were the keys to getting it all working.

// plugins/webpack/index.js
module.exports = function (context, options) {
  return {
    name: "cusotm-webpack-plugin",
    configureWebpack(config, isServer, utils) {
      return {
        mergeStrategy: { "devServer.proxy": "replace" },
        devServer: {
          proxy: {
            "/YOUR_COOL_ROUTE": {
              target: "https://YOUR_COOL_API/",
              secure: false,
              changeOrigin: true,
              logLevel: "debug",
            },
          },
        },
      };
    },
  };
};

Upvotes: 2

Related Questions