Private API to fetch data from server on page load or navigation without exposing api to the client
Hello,
Is it possible to have a completely private API in Nuxt without exposing public server API?
We have a page called
example.vue
and we want to load data from the server when the client navigates to the page for the first time. All fetching processes should be on the server side, and the private API should not be visible to the clients.
we don't want to create server/api/get-data-from-external-api.ts
because anyone can hit this endpoint.
Any ideas?2 Replies
In the server endpoint you proposed that "anyone" can hit you want to use an API key that will be used to authenticate with the external backend. This key will then only be visible on your server.
Using
useAsyncData
with server: true
, the data fetching will only happen during the initial page load on the server. When the user navigates away from the page and then returns, the data will not be re-fetched from the server. That seems expected behavior of Nuxt.
I think you have to wrap () => $fetch("external api")
in an api in ~/server/routes
to make it private. API routes are for exposing data to the client, while server routes are useful for internal server-side logic.
And then manually trigger a re-fetch of the data using the refresh or execute methods provided by useAsyncData
:
Let me know what you think because I'm not totally sure.