#Use different proxy url for production and dev

1 messages · Page 1 of 1 (latest)

gray remnant
#
// File: nuxt.config.ts
  vite: {
    server: {
      proxy: {
        '/api': {
          target: 'http://192.168.40.100:8080',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => {
            console.log(path)
            return path.replace(/^\/api/, '')
          },
        },
      },
    },

For development I use config as above to proxy request to local backend server. But in prod I need to use the real backend server url. How do I set it in nuxt.config.ts or should I set it somewhere else?

tired raven
#

This is difficult to do because loadNuxtConfig is called waaaaay before anything else is loaded or set, process.dev doesn't exist yet

#

Maybe raise an issue

#

Otherwise you could do

#
{
    server: {
      proxy: {
        '/api': {
          target: process.dev ? 'http://192.168.40.100:8080' : 'other option',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => {
            console.log(path)
            return path.replace(/^\/api/, '')
          },
        },
      },
  }
gray remnant
#

Thanks for the reply! I found there is a process.env.NODE_ENV variable that takes on different value depending on the environment.

const appEnv = process.env.NODE_ENV || 'development'

const baseUrl = {
  development: XXX,
  production: YYY,
}
nitro: {
    devProxy: {
      '/api': {
        target: baseUrl[appEnv as keyof typeof baseUrl],
        changeOrigin: true,
      },
    },
  },

novel yarrow
#

You could use routeRules with the proxy option and conditionally configure?

#

For example:

const BASE_URL = process.env.NODE_ENV === 'production' ? 'https://example.com' : 'http://localhost:8080'

export default defineNuxtConfig({
  routeRules: {
    '/api/**: { proxy: `${BASE_URL}/api/**` }
  }
})