Search code examples
node.jsauthenticationbasic-authenticationhttp-proxyvite

Basic Auth using Vite proxy


I tried to connect via basic auth to a URL using vite. Credentials are correct, but an empty form field opens up.

export default defineConfig({
  base: './',
  server: {
    proxy: {
      '/data': {
        target: 'https://user:password@example.com/foo',
        changeOrigin: true,
      }
    },
  }});

Sadly this is not working - here I found a related question https://serverfault.com/questions/371907/can-you-pass-user-pass-for-http-basic-authentication-in-url-parameters but it is not clear for me whether this feature is still supported or not.

Is it possible to modify the request header in vite config to inject the credentials directly in the request?

enter image description here


Solution

  • Vite server proxy is a http-proxy (https://www.npmjs.com/package/http-proxy). Therefor the same config settings can be applied.

    export default defineConfig({
      base: './',
      server: {
        proxy: {
          '/data': {
            target: 'https://example.com/foo',
            changeOrigin: true,
            configure: (proxy, options) => {
              // proxy will be an instance of 'http-proxy'
              const username = 'username';
              const password = 'password';
              options.auth = `${username}:${password}`;
            },
          }
        },
      },
    })