最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to expose .env variables to the client in NUXT 3? - Stack Overflow

programmeradmin0浏览0评论

I have a nuxt config file that tries to expose all my .env variables to the client. Some varibles are exposed and I can access them(i'm accessing using useRuntimeConfi()), and some just return "undefined" whenever i try to access them

I do not know what the cause might be, but here's my code to look at:

nuct.config.ts:

export default defineNuxtConfig({
    /*
     ** Runtime Variables
     */
    runtimeConfig: {
      apiVersion: process.env.API_VERSION || 'alpha',
      cmsUrl: process.env.CMS_URL || 'http://localhost:1337',
      cmsToken: process.env.CMS_TOKEN || 'token',
      public: {
        baseURL: process.env.BASE_URL || 'http://localhost:3000',
        auth0Domain: process.env.AUTH0_DOMAIN,
        auth0ClientID: process.env.AUTH0_CLIENT_ID,
        redirectUri: process.env.REDIRECT_URI || 'http://localhost:3000/',
        stagingUri: process.env.STAGING_URI,
        localDevUri: process.env.LOCAL_DEV_URI,
        cmsUrl: process.env.CMS_URL || 'http://localhost:1337',
      }
    },
});

my auth.js file:

import { createAuth0 } from '@auth0/auth0-vue';
import { useRuntimeConfig } from 'nuxt/app';

//the below console.log returns undefined
console.log(useRuntimeConfig().stagingUri, useRuntimeConfig().redirectUri;

export default defineNuxtPlugin((nuxtApp) => {
  const auth0 = createAuth0({
    domain: useRuntimeConfig().auth0Domain,
    clientId: useRuntimeConfig().auth0ClientID,
    authorizationParams: {
        redirect_uri: useRuntimeConfig().redirectUri || useRuntimeConfig().stagingUri,
    },
    logoutParams: {
      returnTo: useRuntimeConfig().redirectUri || useRuntimeConfig().localDevUri,
    },
    useRefreshTokens: true,
    cacheLocation: 'localstorage'
  });

  if (process.client) {
    nuxtApp.vueApp.use(auth0);
  }

  addRouteMiddleware('auth', () => {
    if (process.client) {
      auth0.checkSession();
      if (!auth0.isAuthenticated.value) {
        auth0.loginWithRedirect({
          appState: {
            target: useRoute().path,
          },
        });
      }
    }
  });
});

As you can see from the file, the redirectUri property is defined but the stagingUri and localDevUri is undefined. Why is that??

I have a nuxt config file that tries to expose all my .env variables to the client. Some varibles are exposed and I can access them(i'm accessing using useRuntimeConfi()), and some just return "undefined" whenever i try to access them

I do not know what the cause might be, but here's my code to look at:

nuct.config.ts:

export default defineNuxtConfig({
    /*
     ** Runtime Variables
     */
    runtimeConfig: {
      apiVersion: process.env.API_VERSION || 'alpha',
      cmsUrl: process.env.CMS_URL || 'http://localhost:1337',
      cmsToken: process.env.CMS_TOKEN || 'token',
      public: {
        baseURL: process.env.BASE_URL || 'http://localhost:3000',
        auth0Domain: process.env.AUTH0_DOMAIN,
        auth0ClientID: process.env.AUTH0_CLIENT_ID,
        redirectUri: process.env.REDIRECT_URI || 'http://localhost:3000/',
        stagingUri: process.env.STAGING_URI,
        localDevUri: process.env.LOCAL_DEV_URI,
        cmsUrl: process.env.CMS_URL || 'http://localhost:1337',
      }
    },
});

my auth.js file:

import { createAuth0 } from '@auth0/auth0-vue';
import { useRuntimeConfig } from 'nuxt/app';

//the below console.log returns undefined
console.log(useRuntimeConfig().stagingUri, useRuntimeConfig().redirectUri;

export default defineNuxtPlugin((nuxtApp) => {
  const auth0 = createAuth0({
    domain: useRuntimeConfig().auth0Domain,
    clientId: useRuntimeConfig().auth0ClientID,
    authorizationParams: {
        redirect_uri: useRuntimeConfig().redirectUri || useRuntimeConfig().stagingUri,
    },
    logoutParams: {
      returnTo: useRuntimeConfig().redirectUri || useRuntimeConfig().localDevUri,
    },
    useRefreshTokens: true,
    cacheLocation: 'localstorage'
  });

  if (process.client) {
    nuxtApp.vueApp.use(auth0);
  }

  addRouteMiddleware('auth', () => {
    if (process.client) {
      auth0.checkSession();
      if (!auth0.isAuthenticated.value) {
        auth0.loginWithRedirect({
          appState: {
            target: useRoute().path,
          },
        });
      }
    }
  });
});

As you can see from the file, the redirectUri property is defined but the stagingUri and localDevUri is undefined. Why is that??

Share Improve this question asked Apr 18, 2023 at 11:15 George MarwanqanaGeorge Marwanqana 4191 gold badge7 silver badges22 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Got similar issue when I had new data inside .env & runtimeConfig(). I got undefined for my new datas. My nuxt version was 3.2.3. I upgrade for the last nuxt version and it work now.

Inside .env : NUXT_PUBLIC_stagingUri=something

runtimeConfig: {
    public: {
      stagingUri: process.env.stagingUri
    },
  },

And use useRuntimeConfig().public.stagingUri to access indeed

The best way to use env vars in nuxt3 you need to set the VITE_VARIABLE in .env file and use import.meta.env

example to use

.env

VITE_BASE_URL=https://apiurl.

vue file

<script setup>
const baseUrl = `${import.meta.env.VITE_BASE_URL}`
console.log(baseUrl)
</script>

i think that helped you.

that way you can access the env vars outside nuxt scope, with another plugins ex. pinia

Include the public key in your useRuntimeConfig()

const auth0 = createAuth0({
    domain: useRuntimeConfig().public.auth0Domain, // Add the .public
    clientId: useRuntimeConfig().public.auth0ClientID, // Add .public
    authorizationParams: {
        redirect_uri: useRuntimeConfig().public.redirectUri || useRuntimeConfig().public.stagingUri, // Add .public
    },
    logoutParams: {
      returnTo: useRuntimeConfig().public.redirectUri || useRuntimeConfig().public.localDevUri, // Add .public
    },
    useRefreshTokens: true,
    cacheLocation: 'localstorage'
  });

Accessing the useRuntimeConfig().public will display all the available public config variables.

As your question, you have to move .env file's variables into the nuxt.config.js inside env object. For an example,

export default {
  mode: 'universal',
  env: {
    MY_VARIABLE: config.MY_VARIABLE,
  },
}

Then you can access those variables inside any ponents or classes.

puted: {
    myVeriable {
      return process.env.MY_VARIABLE
    },
  },

I found the way. You should use bination of NITRO variables and runtimeConfig - 100% works.

// nuxtconfig. add some variable in nuxtconfig.ts at runtimeConfig.

export default {
    runtimeConfig: {
        public: {
          YOUR_VAR: 'hello',
    },
  }
}

/// cmd. build nuxt project and serve it with passed new env "NITRO_PUBLIC_YOUR_VAR"

nuxt build

cross-env NITRO_PUBLIC_YOUR_VAR=bye node .output/server/index.mjs

// runtime. you can see here passed variable from serve script

console.log(useRuntimeConifg().public.YOUR_VAR) // 'bye'
发布评论

评论列表(0)

  1. 暂无评论