DEV Community

Fazail Alam
Fazail Alam

Posted on • Originally published at codef.site on

How to access .env variables in nuxt3

"Nuxt 3 env"

Create .env file

Create .env file in the root directory of your project. Add your necessary variables to it.

Add runtime config

Head over to nuxt.config.ts file. Under defineNuxtConfig, add runtimeConfig object and then public and pass the variables as key and value.

export default defineNuxtConfig({
    runtimeConfig: {
        ...,  // declare private variables here
        public: {
            MODE: process.env.MODE, // this is public 
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

useRuntimeConfig

To access the variables, use useRuntimeConfig() composable from nuxt. There are two properties to access by default. public and app. Since we added our variables in public we can get it from there.

const config = useRuntimeConfig();
console.log(config.public.MODE);
// config.SOME_PRIVATE_VAR
Enter fullscreen mode Exit fullscreen mode

Top comments (0)