How to Use Env Variables in Nuxt 3

· 1 min read June 15, 2022

banner

Storing config in env variables is one of the most important aspect of the twelve factor design .

Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally.

And unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

Lets See how to use Env Variables in your Nuxt3 app .

Initialize a barebones nuxt 3 app using :

  npx nuxi init nuxt-demo

Inside the root directory add a .env file and add some variables inside it .

STRIPE_API_KEY=pk_livexxxxxxxxxxxxxx
STRIPE_SECRET_KEY=pk_liveufhrXXXXXXX

A nuxt app has two faces i.e A server and a client side app . So one of the biggest concerns is to separate the config or env vars for server and client .

Like the api_id needs to be available for both the client and the server but the api_secret should be not made available to client , that would be a security disaster .

Nuxt helps us with this by not making the env vars available to the app automatically . But rather we have to explicitly tell the app which config vars should be public( available for both server and client side) and which should be private( available only for server side ).

Lets see how to do it .

To specify the public config vars add the publicRuntimeConfig key inside the nuxt-config object in nuxt.config.ts . Inside the config we can access env vars using process.env .

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({

  publicRuntimeConfig: {
    stripeKey: process.env.STRIPE_API_KEY,
  },

  // other config

To add private config vars ( thats only available server side) ,Add runtimeConfig key inside nuxt config

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({

  publicRuntimeConfig: {
    stripeKey: process.env.STRIPE_API_KEY,
  }, // availabe for both server and client


  runtimeConfig :{
    stripeSecret: process.env.STRIPE_SECRET_KEY
  } , // availabe only server side

  // other config

Now we can access our env or config vars using useNuxtConfig() composable inside your app .


// in app.vue


<script setup >
  const {stripeKey} = useNuxtConfig()
</script>

You can also access the server side config the same way

// in server/api/checkout.vue

const {stripeSecret} = useNuxtConfig()

Thanks .

Some Thing to say ?