# Nuxt + Hygraph

## Overview

[Nuxt](https://nuxt.com/) is a free, open-source Vue framework. You can use it to create type-safe, performant and production-grade full-stack web applications and websites intuitively.

## Creating a new Nuxt app

To start, we need to initialize a new `Nuxt` project. Open up your terminal, navigate to where you want your project, and run the following command:

```bash
npx nuxi@latest init my-nuxt-project
```

The interactive setup will ask you questions to configure your project. Initialize with the following answers:
- **Current nuxt version, Ok to proceed:** Yes (y)
- **Choose package manager:** npm, pnpm, yarn, or bun (the guide will use yarn)
- **Anonymous usage data collection:** Yes or No
- **Initial git repository:** Yes or No

Change directory into your new project from your terminal:

```
cd my-nuxt-project
```

The interactive setup should install dependencies automatically using the package manager - yarn, pnpm, npm - of your choosing, but you can use the install command if needed:

```
npm install
```

Start your Nuxt app in development mode:

```
npm run dev
```

Your new Nuxt app is now available in the browser at `http://localhost:3000/`

![Nuxt](https://hygraph.com/images/classic-docs/implementations/nuxt/nuxt-locally.png)

### Configure Hygraph assets to work with Nuxt

To work with Nuxt image module, we need to specify Hygraph as an image provider by adding the base URL in the `nuxt.config.ts` file.

Your config file should contain the following code:

```js
// nuxt.config.ts
export default defineNuxtConfig({
... other configuration parameters here
  image: {
    providers: {
      hygraph: {
        baseurl: "https://media.graphassets.com"
      }
    }
  }
})
```
In the above config, we are using Hygraph as our image source.

## Getting data from Hygraph

Now that you have created your Nuxt project, it's time to add some data from Hygraph. Start by cloning our demo Hygraph project:

[Click here to clone the demo project](https://app.hygraph.com/clone/751a6bdf9431476c8b82c543895e6d16?name=Implementation%20Guides)

After cloning, you will have a simple project that contains one content model called **Page** that contains fields for `Title`, `Slug`, and `Body`; and one content entry.

If you navigate to the Schema builder and click on the **Page** model, you will see this:

![Demo project - Page model](https://hygraph.com/images/classic-docs/implementations/demo-project-page-model.png)

And if you navigate to the Content editor and view the sample entry details, you'll see this:

![Demo project - Sample content entry](https://hygraph.com/images/classic-docs/implementations/demo-project-sample-entry.png)

## Public content API

Before you can connect Nuxt to Hygraph, you will need to configure **Public Content API** access permissions for unauthenticated requests.

To do this, go **Project settings > Access > API Access > Public content API** in your Hygraph project, scroll to find the **Content Permissions** box that reads **Would you like us to initialize some defaults?**, and click `Yes, initialize defaults`:

[Video: Public Content API permissions](https://eu-central-1-shared-euc1-02.graphassets.com/AvHQ3RDvFSousA8iwElOKz/cmnn9wfbuhtlu07vxy7tyd8g4)

Finally, copy the `High Performance Content API` endpoint from **Project settings > Access > API Access > Endpoints**. You use it to connect Nuxt to Hygraph later on.

## Testing a query in the API playground

Next, you should test if you can fetch the information in the sample content entry that we showed you earlier. To do this, navigate to the API Playground in your project and use the following query:

  **Query**

```graphql
query Page {
  page(where: {slug: "hygraph-works-with-any-framework"}) {
    title
    body {
      text
    }
  }
}
```

  
  **Response**

```json
{
  "data": {
    "page": {
      "title": "Hygraph works with any framework!",
      "body": {
        "text": "No matter the framework you choose, Hygraph is there for you and all your content needs. "
      }
    }
  }
}
```


If you execute the query, the response should fetch the sample query in the demo project you cloned.

## Generating Hygraph content with Nuxt

[After enabling API access](https://hygraph.com/classic-docs/implementations/nuxt/nuxt#public-content-api), you can start using the **Pages** query with your Nuxt app to render content.

### Adding Tailwind CSS to Nuxt

Use the terminal to go back to your Nuxt app, and type the following command:

```
npm install @nuxtjs/tailwindcss
```

This will install Tailwind CSS, so you have a few base styles to use with your content.

### Installing Nuxt GraphQL Client

The next step is to add the `nuxt-graphql-client` module.

This helps with codegen for GraphQL functionality and types, and provides an easy way to use GraphQL API's in Nuxt.

To install the client, type the following command:

```
npm install nuxt-graphql-client
```

After the installation finishes, add the following to your `nuxt.config.ts` file:

```js
// nuxt.config.ts

export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: ['@nuxtjs/tailwindcss','nuxt-graphql-client']
})
```

The  `nuxt-graphql-client` module offers some convenient helpers for typing and querying.

Add the following to your `.env` file so the module knows how to connect to Hygraph for the introspection of the schema to make types, and to be able to query.

```
GQL_HOST=https://<HYGRAPH_CDN_LOCATION>.cdn.hygraph.com/content/<ID>/master
```

**Warning:**
Make sure that `<HYGRAPH_CDN_LOCATION>` and `<ID>` match your endpoint.

Want to see Nuxt and Hygraph in action? Watch a quick video on how to connect `Nuxt` and `Hygraph`:
[Video](https://www.youtube.com/watch?v=M8QFTViZSMw)
### Adding GraphQL queries

Now that you have all the packages installed, create a queries folder and add your GraphQL queries in there as files with a `.gql` extension:

**Query all pages** - file location & name: `./queries/pages.gql`
```graphql
# File name: pages.gql
# File location ./queries/pages.gql
query Pages {
  pages {
    title
    slug
    body {
      text
    }
  }
}
```
**Query single page by slug** - file location & name: `./queries/page.gql`
```graphql
# File name: page.gql
# File location: ./queries/page.gql
query Page($slug: String!) {
  page(where: { slug: $slug }) {
    title
    body {
      text
    }
  }
}
```

The  `nuxt-graphql-client` module finds this folder and automatically creates types and convenience functions for all queries it finds.

**Do you want to learn more about nuxt-graphql-client?:**
[We made a video about how it works!](https://www.youtube.com/watch?v=Keqn1RT8FwQ)

### Getting a list of pages for the homepage

After adding your `.env` file, go to your `index.vue` file in the `pages` directory and add the following code:

  **JavaScript**
```js
// File location: /pages/index.vue
// Homepage: Get a list of pages from the Hygraph
<script setup>
const { pages } = await GqlPages();
</script>
// Render the list of pages with links to each page by slug
<template>
  <div class="m-12">
    <h1 class="mb-4 text-5xl font-bold">Hygraph Implementation Guides demo</h1>
    <p class="mb-4 text-lg">Click the links below to see other pages</p>
    <ul class="mb-8 list-disc list-inside">
      <li v-for="page in pages" :key="page.slug">
        <nuxt-link :to="`/page/${page.slug}`" class="underline">{{
          page.title
        }}</nuxt-link>
      </li>
    </ul>

    <p>
      <a
        class="px-4 py-2 my-6 font-bold text-white bg-indigo-500 rounded hover:bg-indigo-700"
        href="https://hygraph.com/classic-docs/implementations"
        target="_blank"
      >
        Implementation Docs
      </a>
    </p>
  </div>
</template>
```
  
  **TypeScript**
```ts
// File location: /pages/index.vue
// Homepage: Get a list of pages from the Hygraph
<script setup lang="ts">
const { pages } = await GqlPages();
</script>
// Render the list of pages with links to each page by slug
<template>
  <div class="m-12">
    <h1 class="mb-4 text-5xl font-bold">Hygraph Implementation Guides demo</h1>
    <p class="mb-4 text-lg">Click the links below to see other pages</p>
    <ul class="mb-8 list-disc list-inside">
      <li v-for="page in pages" :key="page.slug"> <!-- Fix the variable name in the :key directive -->
        <nuxt-link :to="`/page/${page.slug}`" class="underline">{{
          page.title
        }}</nuxt-link>
      </li>
    </ul>

    <p>
      <a
        class="px-4 py-2 my-6 font-bold text-white bg-indigo-500 rounded hover:bg-indigo-700"
        href="https://hygraph.com/classic-docs/implementations"
        target="_blank"
      >
        Implementation Docs
      </a>
    </p>
  </div>
</template>
```
  

![Homepage](https://hygraph.com/images/classic-docs/implementations/next/next-homepage.png)

### Creating dynamic page routes with Nuxt

Now, that we have a list of pages in our homepage, we need to create a dynamic route for each page. To do this, create a new directory in the `pages` directory called `page` and a file called `[slug].vue` inside this directory.

Add the following code:

  **JavaScript**
```js
// file location & name: pages/page/[slug].vue
// Dynamic page: Get a single page by slug from the Hygraph

<script setup>
const route = useRoute();
const { page } = await GqlPage({ slug: route.params.slug });
</script>
// Render the page title and body text
<template>
  <div class="m-12">
    <h1 class="mb-4 text-5xl font-bold">{{ page.title }}</h1>
    <p class="mb-8 text-lg">{{ page.body.text }}</p>

    <p>
      <nuxt-link to="/" class="underline">Back to homepage</nuxt-link>
    </p>
  </div>
</template>
</script>

<template>
  <div class="m-12">
    <h1 class="mb-4 text-5xl font-bold">{{ page.title }}</h1>
    <p class="mb-8 text-lg">{{ page.body.text }}</p>

    <p>
      <nuxt-link to="/" class="underline">Back to homepage</nuxt-link>
    </p>
  </div>
</template>
```
  
  **TypeScript**
```ts
// file location & name: pages/page/[slug].vue
// Dynamic page: Get a single page by slug from the Hygraph
<script setup lang="ts">
const route = useRoute();
const { page } = await GqlPage({ slug: route.params.slug });
</script>
// Render the page title and body text
<template>
  <div class="m-12">
    <h1 class="mb-4 text-5xl font-bold">{{ page.title }}</h1>
    <p class="mb-8 text-lg">{{ page.body.text }}</p>

    <p>
      <nuxt-link to="/" class="underline">Back to homepage</nuxt-link>
    </p>
  </div>
</template>
```


### Code overview

The template section of our `Vue` component contains the markup that renders our content on the homepage.

In the script section, we use the `GqlPage()` function to ask Hygraph with our **Page** query to fetch the `title`, `slug`, and `body`.

![Dynamic page](https://hygraph.com/images/classic-docs/implementations/next/next-dynamic-page.png)

Congratulations! You have a homepage and a dynamic page route to render all pages and their content.

**Pro Tip:**
This was a simple and quick example of how to fetch and render content from Hygraph using Nuxt.

For more complete implementation examples, [clone a starter](https://app.hygraph.com/).
