In progress: Next.js project using Typescript, Styled Components, Contentful’s GraphQL API and Apollo.
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:
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);
};
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,
};
};
Run the development server:
npm run dev
# or
yarn dev
Open http://localhost:3000 with your browser to see the result.
https://github.com/timfuhrmann/next-graphql-apollo-contentful
Leave a Reply