nuxt-env
nuxt-env copied to clipboard
Get my secret value in a fetch method ?
Hi.
I'm trying to catch my secret value in a fetch method, can you tell me how to do that ? Env vars works well but the secret env doesn't work.
I have tryed this in my index.vue :
async fetch ({ app, store, params, error, app: { $axios } }) {
...
const oauthPassword = app.$env.OAUTH_API_PASSWORD => is empty
const oauthPassword = this.$env.OAUTH_API_PASSWORD => is empty
const oauthUser = app.$env.OAUTH_API_USER => Catch the good env from my kubernetes secrets
...
}
Here is my nuxt.config.js :
modules: [
...
['nuxt-env', {
keys: [
{ key: 'OAUTH_CLIENT_ID', default: 'abcd' },
{ key: 'OAUTH_API_HOST', default: 'https://oauth.io/' },
{ key: 'OAUTH_API_USER', default: 'my_user' },
{ key: 'OAUTH_API_PASSWORD', secret: true }
]
}]
...
Thx a lot.
Fetch will be executed on client side too when navigating between pages, so using secret wont work like this
Humm here is the doc : https://fr.nuxtjs.org/api/pages-fetch/
Extract from doc :
The fetch method, if set, is called every time before loading the component (only for page components). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
So normaly, the first time, I will be able to catch the secret env on the server side ?
up ! if someone has a solution ?
Same probleme with asyncdata method...
Your fetch should not rely on a secret. If it does, you should make a small API endpoint in the nuxt server.js. This backend has access to the secret without it ever getting into the frontend. You can then call that endpoint from your fetch to get the data.
Anything to do with sensitive keys should always be handled in the backend which the frontend can talk to through an API endpoint.
Thanks @Soviut, I would say the same. It does seem strange to me that you would want the API call to happen if you access the page from the server but not happen if you access the page from the client, but I don't know your specific use case so won't comment further.
@bat79a In your first example you have destructured app
to { $axios }
which would make app
itself undefined, I assume this is a typo.
I can't see any reason why app.$env
should not be populated at that point, if you still struggle please create an example in codesandbox so I can take a look.