·
1 min read

Nuxt Tip: Fetch Data on the Server Before App Start

Nuxt Tip: Fetch Data on the Server Before App Start Image

In configuration driven applications it's a common requirement to load a configuration from an API before the app starts. In these scenarios you usually want to fetch the data on the server to avoid leaking the endpoint URL or API key to the client.

In Nuxt 3+ you can achieve this by using a server plugin and providing the data in the Nuxt payload:

plugins/init.server.ts
export default defineNuxtPlugin(async (nuxtApp) => { let config = null; try { const response = await $fetch( `https://your-api.com/configuration` ); config = response.data; } catch (error) { console.error('Failed to fetch configuration', error); } nuxtApp.payload.data = { ...nuxtApp.payload.data, configuration: config, }; });

With the filename suffix .server.ts we tell Nuxt to run this plugin only on the server. The plugin fetches the configuration from the API and adds it to the Nuxt payload. You can then access the configuration in your components like this:

app.vue
<script setup lang="ts"> const nuxtApp = useNuxtApp(); const user = nuxtApp.payload.data.userData; </script> <template> <div> <span>User: {{ user }}</span> </div> </template>

StackBlitz Example

Try it yourself in the following StackBlitz example:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.