next-graphql-apollo-contentful

In progress: Next.js project using Typescript, Styled Components, Contentful’s GraphQL API and Apollo.

Static Generation

The portfolio and its contents are statically pre-rendered and revalidated every 24 hours.
To do so, the following steps are being followed:

Respective files:

  1. Project Page
  2. GraphQL

First step

Within getStaticPaths, fetch all project identifiers to tell Next.js what params to expect/pre-render:

export const getStaticPaths = async () => {
    const slugs = await getProjectSlugs();

    const paths = slugs.map(item => ({
        params: { slug: item.slug },
    }));

    // Pre-render only fetched paths at build time.
    // Server-side render on demand if the path doesn't exist.
    return { paths, fallback: "blocking" };
};

// query.ts
export const PROJECT_SLUGS = gql`
    query GetProjectSlugs {
        projectCollection {
            items {
                slug
            }
        }
    }
`;

// slugs.ts
export const getProjectSlugs = async (): Promise<Projects.ProjectSlug[]> => {
    const { data } = await client.query<ProjectSlugsCollection>({ query: PROJECT_SLUGS });
    return extractProjectsSlugsCollection(data);
};

Second step

Within getStaticProps, use params to fetch the respective product on build:

export const getStaticProps: GetStaticProps = async ({ params }) => {
    const slug = params?.slug;

    if (!slug || "string" !== typeof slug) {
        return {
            notFound: true,
        };
    }

    const project = await getProjectBySlug(slug);

    if (!project) {
        return {
            notFound: true,
        };
    }

    return {
        props: { project },
        revalidate: 60 * 60 * 24,
    };
};

Getting Started

Run the development server:

npm run dev
# or
yarn dev

Open http://localhost:3000 with your browser to see the result.

Visit original content creator repository
https://github.com/timfuhrmann/next-graphql-apollo-contentful

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *