Quick Start

Get started by creating a quick demo with the SpaceX GraphQL API.

Setup

  1. Add nuxt-graphql-client dependency to your project
npx nuxi@latest module add graphql-client
  1. Enable the module in your nuxt configuration
nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],
})
  1. Provide the URL to your GraphQL API

This can be done in either the nuxt configuration or via a .env file.

However though, Adding the GQL_HOST variable to your .env would overwrite the GQL_HOST value defined in the nuxt configuration.

nuxt.config.ts
import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  modules: ['nuxt-graphql-client'],

  runtimeConfig: {
    public: {
      GQL_HOST: 'https://api.spacex.land/graphql' // overwritten by process.env.GQL_HOST
    }
  }
})
.env
GQL_HOST="https://api.spacex.land/graphql"
  1. Write your GraphQL queries / mutations
Must be written within in .gql / .graphql files. Writing Operations with SFC components is not supported.

nuxt-graphql-client will automatically parse your GraphQL documents and generate the corresponding GraphQL queries / mutations.

./nuxt-app/queries/starlink.gql - This will query the SpaceX API to retrieve the launches for Starlink missions.

starlink.gql
query launches($limit: Int = 5) {
  launches(limit: $limit) {
    id
    launch_year
    mission_name
  }
}

Given the query above, A Gql Function named GqlLaunches() will be generated and accessible within the app. The Operation name (launches) in this example.

  1. Code Generation

Run yarn dev for the module to generate the necessary types and functions for all GraphQL queries / mutations.

Your data will be fully-typed based on it's pertinent GraphQL Document.

  1. You're ready to go! ⚡️

Below is an example using the launches query written earlier in step 4.

app.vue
<template>
  <div>
    <h2>Starlink Launches</h2>

    <p v-for="(entry, i) of data?.launches" :key="entry.id">
      {{ i + 1 }}. Mission Name: {{ entry.mission_name }} ({{
        entry.launch_year
      }})
    </p>
  </div>
</template>

<script lang="ts" setup>
const { data } = await useAsyncGql({
  operation: 'launches',
  variables: { limit: 5 }
});

// Or: based on your preference
// const { data } = await useAsyncGql('launches', { limit: 5 });
</script>

Preview

Loading Sandbox...
Table of Contents