How to access environment variables of .env in pinia store in Nuxt 4
Currently in .env
In pinia store
testApiKey is empty. If I change to just include everything in process.env then following is showed
2 Replies
Hi @ATL. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To access environment variables from your
Prefix your variable with
You can leave the value empty; Nuxt will automatically use the environment variable if it matches the name: See example in the docs 3. Access the variable in your Pinia store
Use the
-
- Use
.env
file in a Pinia store in Nuxt 4, you should not use process.env
directly inside your store or application code. Instead, you need to define your variables in the runtimeConfig
section of your nuxt.config.ts
and access them using the useRuntimeConfig()
composable. This is because, in Nuxt 3/4, only variables defined in runtimeConfig.public
are exposed to the client-side and are accessible in your application code, including Pinia stores.
Here's how you can do it:
1. Update your .env
filePrefix your variable with
NUXT_PUBLIC_
to make it available client-side:
2. Update your nuxt.config.ts
You can leave the value empty; Nuxt will automatically use the environment variable if it matches the name: See example in the docs 3. Access the variable in your Pinia store
Use the
useRuntimeConfig()
composable:
See usage in the docs
Why your current approach doesn't work:-
process.env
is only populated with a very limited set of variables on the client-side (like NODE_ENV
).
- Only variables prefixed with NUXT_PUBLIC_
and defined in runtimeConfig.public
are exposed to the client and thus available in your Pinia store or any client-side code.
Summary:- Use
NUXT_PUBLIC_
prefix in .env
- Define the variable in runtimeConfig.public
- Access it via useRuntimeConfig().public
in your store
For more details, see the official documentation: Nuxt 4 Runtime Config and Environment Variables, useRuntimeConfig composable, and Directory Structure: .env
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@110720190056013824> Kapa.ai is still learning and improving, please let me know how I did by reacting below.