After using the dotenv library for my .env file, I had to change the runtimeConfig in order to secure my project's secret key.
In my most recent project, I utilized nuxt version "^2.14" in SPA mode, so I only utilized "publicRuntimeConfig" in my nuxt.config.ts file like this:
.env
Test_BASE_URL:'https://test.org'
nuxt.config.ts
export default {
publicRuntimeConfig:{baseURL: process.env.Test_BASE_URL||''}
}
I was able to access the env variable in a vue file like this:
sample.vue
<script>
export default {
mounted(){
console.log(this.$config.baseURL)
}
}
</script>
However, I encountered difficulty accessing "$config" in the store's state. I attempted to do it but it always returned "undefined."
index.ts
export const state = (context) => ({
url:context.$config
})
Upon referring to some solutions from others and changing the state value through actions, especially since I was using SPA, I created a method like 'nuxtServerInit' as plugins.
plugins/clientInit.ts
import {Context} from "@nuxt/types";
export default function (context:Context) {
context.store.dispatch('initEnvURL', context.$config)
}
index.ts
interface State {
testURL: string
}
const state = () => ({
testURL:''
})
const mutations = {
setTestURl(state:State, config:any) {
state.testURL = config.baseURL
}
const actions = {
initEnvURL({commit}, $config) {
commit('setTestURl', $config)
}
}
export default {state, mutations, actions}
I did manage to successfully change the state value through the above actions methods, but I am still unsure why "context" cannot directly use store/state objects. Does anyone have insight on how to utilize $config in store/state? Or is the only way to use $config through actions method as shown above?