azurenuxt.jsnuxt3.jsnitro

Nuxt 3 app deployed to Azure. Environment variables are ignored in nitro section of nuxt.config.ts


I've found that my Nuxt 3 app deployed to Azure is ignoring environment variables in nuxt.config.ts.

This is what I have in local:

nitro: {
    storage: {
      redis: {
        driver: 'redis',
        port: REDIS_PORT,
        host: REDIS_HOST,
        username: '',
        password: REDIS_PASS,
        db: 0
      }
    }
  },

But if I want it to work on the production machine, I have to remove the 3 environment variables and hardcode them. Which is totally inconvenient, as I have a modified nuxt.config.ts file that I can never push. And when switching branches, I have to copy that section, discard the file, switch to the new branch, and paste the section.

I saw an example in the docs, but I wonder if the environment variables being ignored is a known issue or if I'm missing something really obvious.

Thanks in advance to anyone who might help :)


Solution

  • I created a sample nuxt application which prints environment variables as output.

    REDIS_PORT=<port>
    REDIS_HOST=<Hostname>
    REDIS_PASS=<password>
    
    import  'dotenv/config'
    require('dotenv').config()
    

    Complete nuxt.config.ts:

    import { defineNuxtConfig } from  'nuxt/config'
    import  'dotenv/config'
    require('dotenv').config()
    export  default  defineNuxtConfig({
    nitro: {
    storage: {
    redis: {
    driver:  'redis',
    port:  process.env.REDIS_PORT,
    host:  process.env.REDIS_HOST,
    username:  '',
    password:  process.env.REDIS_PASS,
    db:  0
    }
    }
    },
    runtimeConfig: {
    public: {
    redisPort:  process.env.REDIS_PORT,
    redisHost:  process.env.REDIS_HOST,
    redisPass:  process.env.REDIS_PASS,
    }
    }
    })
    

    pages/index.vue:

    <template>
      <div>
        <h1>Environment Variables</h1>
        <ul>
          <li>REDIS_PORT: {{ redisPort }}</li>
          <li>REDIS_HOST: {{ redisHost }}</li>
          <li>REDIS_PASS: {{ redisPass }}</li>
        </ul>
      </div>
    </template>
    <script setup>
    import { useRuntimeConfig } from '#imports'
    const config = useRuntimeConfig()
    const redisPort = config.public.redisPort
    const redisHost = config.public.redisHost
    const redisPass = config.public.redisPass
    </script>
    

    Here, the environment variables are displayed by the Vue component by using useRuntimeConfig.

    This way Nuxt3 application uses and loads environment variables both in development and production.

    Output after deployment:

    enter image description here