#Fetching data from Directus using Next 13.4? SSG rendering

20 messages · Page 1 of 1 (latest)

solid garden
#

Hi. I'm a beginner working on my first project and I'm wondering how can I fetch data from my DIrectus repo project (it hasnt been deployed), and my Next 13.4 project?

It's a portfolio website containing products, within a 'products' collection.
I'd like to render all of the products within the collection by their slug.

Is this a good approach?


export default function Products({ products }) {
    return (
      <div>
        {products.map((product) => (
          <div key={product.id}>
            <h1>Product: {product.name}</h1>
            {/* Render other product details */}
          </div>
        ))}
      </div>
    );
  }
  

export async function getStaticProps() {
    const directus = await getDirectusClient();
    const response = await directus.items("products")
    const formattedProducts = response.data.map((product) => {
      return {
        ...product,
      };
    });
  
    return {
      props: {
        products,
      },
    };
  }

This code is from app/products/[slug]/page.tsx

hardy sigilBOT
#

Thanks for posting! This is a community powered server, so you may or may not get an answer based on available help and expertise. To increase your chances of somebody being able to help you, please help us help you making sure you:

  • Adding an explanation of exactly what you're trying to achieve.
  • Adding any and all related code or previous attempts.
  • Describing the exact issue or error you are facing.
  • Posting any screenshots if applicable.
  • Reading through https://stackoverflow.com/help/how-to-ask.

When you're done with this thread, please close it. Thanks! ✨

(If you have a support agreement and need help, please contact the core team via email.)

solid garden
#

How do I connect this Next repo to my Directus repo containing the Products collection? I've set that up already.

#

This code is from app/products/[slug]/page.tsx


export default function Products({ products }) {
    return (
      <div>
        {products.map((product) => (
          <div key={product.id}>
            <h1>Product: {product.name}</h1>
            {/* Render other product details */}
          </div>
        ))}
      </div>
    );
  }
  

export async function getStaticProps() {
    const directus = await getDirectusClient();
    const response = await directus.items("products")
    const formattedProducts = response.data.map((product) => {
      return {
        ...product,
      };
    });
  
    return {
      props: {
        products,
      },
    };
  }```
dense phoenix
#

Specific step by step instruction on how to fetch data using Next 13 and the Directus SDK

solid garden
#

Excellent, exactly what I'm looking for. Thanks.

dense phoenix
#

You got it 🤘

solid garden
#

Do I have to have the Directus CMS repo deployed to pull the data? It's not viable for me to sign up for Cloud until I'm making enough revenue to cover those expenses, so I have to take a cheaper route, though I'd like o spin up the servers locally and deploy when I've finished the build?

#

Is there a mono-repo method?

#

I'm interested to hear how I can get started using 2 repos or a mono-repo, without signing up for Cloud immedietly.

solid garden
#

With PayloadCMS, I'm famiiar with having to configure the .env files

Like this:

# Or you can change this variable to point to your own
NEXT_PUBLIC_CMS_URL=https://cms.payloadcms.com

NEXT_PUBLIC_CLOUD_CMS_URL=http://localhost:8001

NEXT_PUBLIC_SITE_URL=http://local.payloadcms.com:3000

# Used to revalidate pages on Vercel
NEXT_PRIVATE_REVALIDATION_KEY=

# The GitHub Access Token is used to dynamically fetch Payload docs from GitHub and write them to a JSON file within this repo
GITHUB_ACCESS_TOKEN=

# This is not necessary unless you want to work with Algolia Docsearch
NEXT_PUBLIC_ALGOLIA_DOCSEARCH_KEY=

NEXT_PUBLIC_GA_MEASUREMENT_ID=
NEXT_PUBLIC_FACEBOOK_PIXEL_ID=

# This will allow robots to crawl your site, etc
NEXT_PUBLIC_IS_LIVE=

# For cloud platform only
GITHUB_ACCESS_TOKEN=
NEXT_PUBLIC_GITHUB_REDIRECT_URI=http://local.payloadcms.com:3000/gh
NEXT_PUBLIC_GITHUB_CLIENT_ID=
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_SECRET_KEY=

DISCORD_TOKEN=
DISCORD_SCRAPE_CHANNEL_ID=

# Algolia Community Help Search - Only necessary if you want to use this feature
NEXT_PUBLIC_ALGOLIA_CH_ID=
NEXT_PUBLIC_ALGOLIA_PUBLIC_KEY=
NEXT_PRIVATE_ALGOLIA_API_KEY=
NEXT_PUBLIC_ALGOLIA_CH_INDEX_NAME=

# This is used to generate the sitemap, i.e. https://payloadcms.com
SITEMAP_URL=

# Vercel Cron Job
NEXT_PRIVATE_CRON_KEY=a-bunch-of-random-text-and-numbers

NEXT_PUBLIC_NEWSLETTER_FORM_ID=```

https://github.com/payloadcms/website/blob/main/.env.example
GitHub

The official Next.js website behind payloadcms.com - website/.env.example at main · payloadcms/website

dry crystal
#

Do I have to have the Directus CMS repo deployed to pull the data?

There has to be some Directus project running somewhere, yeah. I'd just do it as two separate things imo - run a directus project, and then run the frontend. I'm sure there's something fancy you can do to co-locate them, but that's really down to you

solid garden
#

Apologies if I wasn't clear. When I say deployed I mean on the internet, requiring the full deployment process that will I much rather tackle once I've got the project completed locally - that is something I don't want to do until the end.

I'd like to run Directus on it's port 'x', and Next on port 'y' and connect Next to fetch the data from the Directus port.

With Payload it's as simple as inputting the localhost address into the .env file.

How do I do it with Directus? (Running locally)

#

So I'd like both repos running locally, with the Directus data stored in a database, uch as SQLite.

#

Question 2 - I assume this is a common dev approach? To first build locally and later deploy?

dry crystal
#

OH RIGHT yeah that question makes way more sense

#

Again tho, I've always run them separately. Directus runs on ports 8055 (API) and 8080 (App). I store some env var for a base URL which changes in prod - in dev I make that http://localhost:8055

#

I think I'm answering your question

solid garden
#

Thanks. You are indeed, just not to the level of detail I'd like 😛 You're pointing me in the right direction which is helpful and I think I'll understand more once I try.

Does this approach work? If so, every time i want to fetch data from the Directus backend I need to include the import directusAPI
?

"Ensure that your Directus backend is up and running on a specific local port, such as localhost:3000, and that you can access it successfully through your browser or API testing tool.

In your Next.js application, you'll need to install a package that allows you to make API requests to the Directus backend. A popular choice is axios, a widely used HTTP client library. Install it by running the following command in your Next.js project directory:

bash
Copy code
npm install axios
Create a separate file in your Next.js application to define a function or utility for making API requests to the Directus backend. For example, you could create a file called directusAPI.js and define the following function:

import axios from 'axios';

const directusAPI = axios.create({
  baseURL: 'http://localhost:3000', // Replace with the correct URL for your Directus backend
});

export default directusAPI;
Adjust the baseURL to match the URL where your Directus backend is running.

In your Next.js components or pages, import the directusAPI utility and use it to make requests to the Directus API endpoints. For example, to fetch blog posts from Directus, you can create an async function:

import directusAPI from './directusAPI';

async function fetchBlogPosts() {
  try {
    const response = await directusAPI.get('/items/blogPosts');
    return response.data;
  } catch (error) {
    console.error('Error fetching blog posts:', error);
    return [];
  }
}
Adjust the endpoint /items/blogPosts to match the appropriate Directus endpoint for retrieving your blog posts.

Use the fetched data in your Next.js components to render the blog posts or other content as desired.
"