getResourceFromContext
Fetch a resource from getStaticProps or getServerSideProps context.
const resource = await drupal.getResourceFromContext<T = JsonApiResource>( input, context, options?: { params, withAuth, deserialize, locale, defaultLocale, pathPrefix, isVersionable, }): Promise<T>input: string | DrupalTranslatedPath- Required
- The resource type
node--articleor the translated path fromtranslatePathFromContext.
context: GetStaticPropsContext | GetServerSidePropsContext- Required
- The context from
getStaticPropsorgetServerSideProps.
options- Optional
params: JsonApiParams: JSON:API params such asfilter,fields,includeorsort.withAuth: boolean | DrupalClientAuth:- Set the authentication method to use. See the authentication docs.
- Set to
trueto use the authentication method configured on the client.
deserialize: boolean: Set to false to return the raw JSON:API response.locale: string: The locale to fetch the resource in.defaultLocale: string: The default locale of the site.pathPrefix: string: Set the pathPrefix if you're calling from a subdir. Example: for/articles/[...slug].tsx, usepathPrefix: "/articles".isVersionable: boolean: Set to true if you're fetching the revision for a resource. Automatically set to true for node entity types.
Notes
The localized resource will be fetched based on the
localeanddefaultLocalevalues fromcontext.If you pass in a
DrupalTranslatedPathfor input,getResourceFromContextwill take thetypeandidfrom the path and make agetResourcecall to Drupal.
export async function getStaticProps(context) { const path = await drupal.translatePathFromContext(context)
const node = await drupal.getResourceFromContext(path, context)
return { props: { node, }, }}If you pass in a
stringinout, such asnode--article,getResourceFromContextwill make a subrequest call to Drupal to translate the path and then fetch the resource.You will need both the Subrequests and Decoupled Router modules.
export async function getStaticProps(context) { const node = await drupal.getResourceFromContext("node--article", context)
return { props: { node, }, }}Examples
- Fetch a resource from context.
pages/[[...slug]].tsx
export async function getStaticProps(context) { const node = await drupal.getResourceFromContext("node--page", context)
return { props: { node, }, }}- Fetch a resource from context in a sub directory.
pages/articles/[[...slug]].tsx
export async function getStaticProps(context) { const node = await drupal.getResourceFromContext("node--page", context, { pathPrefix: "/articles", })
return { props: { node, }, }}TypeScript
- Using
DrupalNodefor a node entity type.
import { DrupalNode } from "next-drupal"
const node = await drupal.getResourceFromContext<DrupalNode>( "node--page", context)- Using
DrupalTaxonomyTermfor a taxonomy term entity type.
import { DrupalTaxonomyTerm } from "next-drupal"
const term = await drupal.getResourceFromContext<DrupalTaxonomyTerm>( "taxonomy_term--tags", context)See the TypeScript docs for more built-in types.