Created
November 29, 2023 09:35
-
-
Save Adam-Mould/252065e2a4e1abcee3fd22f381f018ad to your computer and use it in GitHub Desktop.
Using next-drupal in Next.js 14 app router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DrupalJsonApiParams } from "drupal-jsonapi-params"; | |
import { drupal, getResourceByParams } from "@/lib/drupal"; | |
const RESOURCE_TYPE = "node--landing_page"; | |
export default async function Page({ params }: { params: { slug: string[] } }) { | |
// Fetch a resource by params | |
const resource = await getResourceByParams(params); | |
return ( | |
<> | |
<h1>{resource.title}</h1> | |
<pre>{JSON.stringify(resource, null, 2)}</pre> | |
</> | |
); | |
} | |
// Dynamic metadata | |
// https://nextjs.org/docs/app/api-reference/functions/generate-metadata#generatemetadata-function | |
export async function generateMetadata({ | |
params, | |
}: { | |
params: { slug: string[] }; | |
}) { | |
// Fetch the resource, but cherry pick the fields we need. | |
const drupalParams = new DrupalJsonApiParams(); | |
drupalParams.addFields(RESOURCE_TYPE, ["title", "field_metatags"]); | |
const resource = await getResourceByParams(params, { | |
params: drupalParams.getQueryObject(), | |
}); | |
return { | |
title: resource.field_metatags?.title ?? resource.title, | |
description: resource.field_metatags?.description, | |
}; | |
} | |
// Statically generate pages at build time | |
// https://nextjs.org/docs/app/api-reference/functions/generate-static-params | |
export async function generateStaticParams() { | |
const paths = await drupal.getStaticPathsFromContext(RESOURCE_TYPE, {}); | |
// @ts-ignore | |
return paths.map((path) => ({ slug: path.params.slug })); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment