How to configure proxy in Vite?

Viewed 27184

I was trying to follow the docs and created vite.config.js like this:

const config = {
  outDir: '../wwwroot/',
  proxy: {
    // string shorthand
    '/foo': 'http://localhost:4567',
    // with options
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, '')
    }
  }
};

export default config;

And tried to test it with following calls:

fetch('/foo');
fetch('/api/test/get');

I was expecting to have actual requests as http://localhost:4567/foo and http://jsonplaceholder.typicode.com/test/get But both of them had my dev server as an origin like this: http://localhost:3000/foo and http://localhost:3000/api/test/get

Did I misunderstand it? How proxies should work?

I also created an issue in the Vite repo but it was closed and I did not understand the closing comment.

2 Answers

Turns out it's needed to specify secure flag to false like this:

 proxy: {
      '/api': {
           target: 'https://localhost:44305',
           changeOrigin: true,
           secure: false,      
           ws: true,
       }
  }

Related github issue

export default defineConfig({
 // add this line for server
  server: {
    proxy: {
      "/api": {
        target: "https://your-remote-domain.com",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  // some other configuration
})
Related