Reputation: 579
I'm saving my API credentials in the privateRuntimeConfig
option of the nuxt.config.js
file. I want these keys secure in server, I don't want these in client.
Now, I want to send a request to the API after the user click a button, but I need to use that keys, but they are not in client. So, I don't know how to do it. I have something like this:
index.vue
<template>
<form method="post" action="#" @submit.prevent="sendRequest">
<input v-model="someUserData">
<button type="submit">Send some data :D</button>
</form>
</template>
<script>
...
data() {
return() {
someUserData: ""
}
},
methods: {
sendRequest() {
// Here I should send the request using the API Keys
}
}
...
</script>
My main idea was that when the user click the button, a request must be sent to the Nuxt server with the user data introduced in the form, so, in the Nuxt server I can access to the API credentials and then send the request to the API... but sincerely I don't know how to access to the Nuxt server, I don't know if I can create routes inside the Nuxt server to send request form the Nuxt client 🤔
Can you help me?
Upvotes: 3
Views: 3007
Reputation: 46814
TLDR: you cannot hide things on client side.
Here, the code that you're sharing is isomorphic (or universal) meaning that it will work on server and client.
This is hence not a place where you can use a private variable. Those are for the code running only on server like the serverMiddleware
, nuxtServerInit
, when building/generating your app (buildModules
) or alike.
Basically, anything that is on the server
lifecycle only (and not both in server + client).
One thing to bear in mind is that Nuxt is still a frontend app. Meaning that you cannot use private keys just like that, without it being public.
If your frontend needs it, you gonna need to have it exposed somewhere. Or use a backend proxy/serverless function to hide it (having a non client-side middleware basically).
So you need to either have some kind of auth (with JWT for example), store them somehow during the build and reuse them later, use a backend server as a proxy, use API keys that can be exposed publicly (a lot of APIs are giving you those kind of keys for frontend) etc...
You may google/look on other questions on stackoverflow explaining this, but even if Nuxt does have a Node.js server, it's main usage is aimed towards SPA (public code).
Upvotes: 4