Search code examples
webpackproxywebpack-dev-serverhttp-proxy-middleware

Proxy request to local file


I have proxy config like that:

proxy: {
  "/api/smth": {
    target: "http://api.example.com/",
    secure: false,
    changeOrigin: true,
  },
}

Now I want to redirect api calls /api/*/meta to local files %PROJ_ROOT%/meta/*.json.

How can I configure that?


Solution

  • Simple version:

    proxy: {
      "/api/*/meta": {
        selfHandleResponse: true,
        bypass(req, resp) {
          const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
          resp.header("Content-Type", "application/json");
          fs.createReadStream(`./meta/${id}.json`).pipe(resp);
        },
      },
      "/api/smth": {
        target: "http://api.example.com/",
        secure: false,
        changeOrigin: true,
      },
    }
    

    Version with status code:

    proxy: {
      "/api/*/meta": {
        selfHandleResponse: true,
        bypass(req, resp) {
          const id = req.url.match(/api\/([-\w]+)\/meta/)[1];
          const jsonStream = fs.createReadStream(`./meta/${id}.json`);
    
          jsonStream.on("open", () => {
            resp.header("Content-Type", "application/json");
            jsonStream.pipe(resp);
          });
    
          jsonStream.on("error", err => {
            resp.status(err.code === 'ENOENT' ? 404 : 500);
            resp.send(err);
          });
        },
      },
      "/api/smth": {
        target: "http://api.example.com/",
        secure: false,
        changeOrigin: true,
      },
    }