Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables in Nuxt 3 with Pinia

I'm trying to render env variable in Pinia store within defineStore() using useRuntimeConfig(), but the store can't use the method, throwing error: "Nuxt instance is not unavailable".

I came up with a workaround and created a composable function where useRuntimeConfig() can be used and returns my environment variables. This composable is then called within the store state.

It sounds way too complicated for something what used to be as trivial as using process.env. What's the best practice in using Nuxt 3 + Pinia and env variables?

like image 268
Marek Miś Avatar asked Oct 20 '25 12:10

Marek Miś


2 Answers

In Nuxt 3 is way "harder" to do than in Nuxt 2.

Because the Nuxt Instance is not available in places that are not "native" from Nuxt, for example Pinia and it's store or any folder you create in the project that is not /server, /components, /composables, etc.

At the moment Pinia doesn't come by default in Nuxt, because of this some features like the one you are asking is not available "out of the box". Maybe in a (near) "future" the team will incorporate it, but we don't know.

At the moment my personal way to solve the issue is by doing what you've done, a combination of useRuntimeConfig(), the .env file and a composable.

Remember that Nuxt 3 is a Release Candidate and Many things can change in a near future.

Many packages wait until v1.0 release to integrate and then document how to work with frameworks, may it will be the case with pinia.

like image 170
Guille Avatar answered Oct 23 '25 07:10

Guille


To use env vars with pinia you need set the VITE_VARIABLE in .env env file antes use import.meta.env

example to use

.env

VITE_BASE_URL=https://apiurl.com

store.js

const baseUrl = `${import.meta.env.VITE_BASE_URL}`
like image 44
fabiovaz Avatar answered Oct 23 '25 08:10

fabiovaz