Environment variables in Nuxt3

There are a few way to access environment variables in Nuxt3. How depends on where you are trying to access them.

Middleware & Plugins

// middleware/auth.global.ts
export default defineNuxtRouteMiddleware((to, from) => {
    const runtimeConfig = useRuntimeConfig();
    // extract as needed
    const { baseURL, AUTH_TOKEN_KEY, LOGIN_PATH } = runtimeConfig.public;
})
export default defineNuxtPlugin(() => {
  return {
    provide: {
      myPlugin: () => {
        const runtimeConfig = useRuntimeConfig();
        // extract as needed
        const { baseURL, AUTH_TOKEN_KEY, LOGIN_PATH } = runtimeConfig.public;
        return 'pluginValue';
      },
    },
  };
});

Pages, Components & Layouts

Within the <script setup> block.

<script setup>
    const config = useRuntimeConfig();
    console.log(config.public.API_BASE_URL);
</script>

Store files

Has to be called inside an action or getter

    const config = useRuntimeConfig();
    console.log(config.public.API_BASE_URL);

Service files (GRPC)

This seems trickier on a server or deployment pipeline. As these files (our are GRPC) are not ‘inside’ the Nuxt container the variables are not available when the file is loaded. They will be available in a called method.

This does work locally with a .env file. I will updated any findings for remote deploying in this case later.

To access variables here they need to be prefixed with VITE_

const baseURL = import.meta.env.VITE_API_URL;

Posted

in

, ,

by

Tags:

Comments

Leave a Reply