To use environment variables in Nuxt 3, we need to use
runtimeConfig
in nuxt.config
.
import { defineNuxtConfig } from "nuxt";
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
runtimeConfig: {
// The private keys which are only available within server-side
apiSecret: "123",
// Keys within public, will be also exposed to the client-side
public: {
apiBase: process.env.API_BASE || "default_api_url",
otherUrl: process.env.OTHER_URL || "default_other_url"
}
}
});
So now if environment variables are present, their values will be stored in apiBase
and otherUrl
. If environment variables are not present, default values will be used for apiBase
and otherUrl
.
To access this within components/plugins/server routes use useRuntimeConfig().
<template>
<div>
API Base - {{ runtimeConfig.public.apiBase }} <br />
Other URL -
{{ runtimeConfig.public.otherUrl }} <br />
</div>
</template>
<script lang="ts" setup>
const runtimeConfig = useRuntimeConfig();
</script>
Here is the codesandbox to see it in action,
Top comments (11)
Also to mention that if you need to use them into a composable, you need to import it inside of it. 👍🏻
@kissu Could you please elaborate what should we import inside the composable?
Because I'm facing a problem when I use
useRuntimeConfig
oruseNuxtApp
inside composable I getserver error 500
I'm using compossables directory to store all of my fetch functions that I'm going to use globally in my project
I saw a similar question on Stackoverflow but I was not able to find out a solution (probably doable by checking the Github issues/discussions tho).
Sorry for not more helpful on that one.
No worries, you've already helped me alot with my questions on Stackoverflow ^^
Ah ? Happy to help anytime! 😉 ♥
import { useRuntimeConfig } from "#app";
See if this helps.
Also are you using it correctly?
github.com/nuxt/framework/discussi...
@cengdpu
Also can't seem to access
apiSecret
or add new private variables here? Docs seem confusing.Private variables are accessible only in server-side i.e server directory
See this
nuxt.com/docs/guide/directory-stru...
Nice!
What about outside of the Nuxt wrapper?
ie in api, middelware files or plain .ts file?