Filter by Site

How to fetch JSON:API resources filtered by site.


Note: This is available for Drupal 9.3.x only. See the change record here.

If you have multiple Next.js sites built from one Drupal source, you can filter JSON:API resources by site using the site `machine_name`.

Collection

You can filter resource collection using `FIELD_NAME.meta.drupal_internal__target_id`.

import { getResourceCollection } from "next-drupal"
// Fetch all Article nodes where the entity reference field `field_sites` has value blog.
const nodes = await getResourceCollection<DrupalNode[]>("node--article", {
params: {
filter: {
"field_sites.meta.drupal_internal__target_id": "blog",
},
},
})
  • `field_sites` is a Next.js site entity reference field on the `Article` content type.
  • `blog` is the ID of the Next.js site.

In `getStaticProps` you can use:

export async function getStaticProps(
context
): Promise<GetStaticPropsResult<IndexPageProps>> {
const nodes = await getResourceCollectionFromContext<DrupalNode[]>(
"node--article",
context,
{
params: {
include: "field_image,uid",
sort: "-created",
filter: {
"field_sites.meta.drupal_internal__target_id": "blog",
},
},
}
)
return {
props: {
nodes,
},
}
}

Dynamic Routes

In `getStaticPaths` you can filter by site by passing `params`:

export async function getStaticPaths(context): Promise<GetStaticPathsResult> {
const paths = await getPathsFromContext(["node--article"], context, {
params: {
filter: {
"field_sites.meta.drupal_internal__target_id": "blog",
},
},
})
return {
paths,
fallback: false,
}
}