How to access .env variables in nuxt3

How to access .env variables in nuxt3

Access environment variables in nuxt3 to use them in your application.

Fazail Alam
Frontend dev · Tue Jul 05 2022

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.

nuxt.config.ts
export default defineNuxtConfig({
	runtimeConfig: {
		public: {
			MODE: process.env.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);

Want frameworks news and updates?

Sign up for our newsletter to stay up to date.

Share on: