Nuxt ignores proxy.pathRewrite when `yarn generate`

Viewed 1163

I use inside nuxt.config.js:

  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    'cookie-universal-nuxt',
    'nuxt-vue-select'
  ],
  axios: {
    proxy: true,
    credentials: false,
    baseURL: 'https://api.example.com'
  },
  proxy: {
    '/api/': { target: 'https://api.example.com', pathRewrite: {'^/api/': ''} }
  },

unfortunately if I deploy webapp with yarn generate it's using https://example.com/api/... and ignoring pathRewrite rules into https://api.example.com/....

how to solve it?

2 Answers

Currently only working workaround for this issue is avoiding using yarn generate and always use yarn build; yarn start on production.

however it's truly disappointing workaround and sometimes even impossible to use (if one hosting doesn't provide explicit support for node webapps).

Has anyone else found a better solution?

The problem with yarn generate ist, that it is used for static hosting where you don't have your server side proxy. The only workaround I found was writing your own "pathRewrite" logic in an axios OnRequest interceptor, so that it behaves similary to the proxy "pathRewrite".

plugin/axios.js

const prod = process.env.NODE_ENV === "production";
const prefix = "/api/";

export default function({ $axios }) {
  
  $axios.onRequest(config => {
    
    // The proxy is disabled in prod mode => write own rewritePath here
    if (prod && config.url.startsWith(prefix)) {
      config.url = config.url.replace(prefix, process.env.API_BASEURL);
    }

    return config;
  });
}

nuxt.config.js

 /*
  ** Nuxt.js modules
  */
  env:{
   API_BASEURL:'https://api.example.com'
  },
  plugins:[
    '~/plugins/axios.js'
  ],
  modules: [
    '@nuxtjs/axios',
    "@nuxtjs/proxy",
  ],
  axios: {
    credentials: false,
  },
  proxy: {
    '/api/': { target: 'https://api.example.com', pathRewrite: {'^/api/': ''} }
  },

Related