Skip to main content

Module: @headstartwp/next

Namespaces

Interfaces

API handlers

previewHandler

previewHandler(req, res, options?): Promise<void>

The PreviewHandler is responsible for handling preview requests.

Handling Previews requires the Headless WordPress Plugin.

Important: This function is meant to be used in a api route at /pages/api/preview.

Usage

// pages/api/preview.js
import { previewHandler } from '@headstartwp/next';

export default async function handler(req, res) {
return previewHandler(req, res);
}

Parameters

NameTypeDescription
reqNextApiRequestThe request object,
resNextApiResponse<any>The response object.
optionsPreviewHandlerOptionsThe PreviewHandlerOptions PreviewHandlerOptions

Returns

Promise<void>

A response object.

Defined in

packages/next/src/handlers/previewHandler.ts:120


revalidateHandler

revalidateHandler(req, res): Promise<void>

The RevalidateHandler is responsible for handling revalidate requests.

Handling revalidate requires the Headless WordPress Plugin.

Important: This function is meant to be used in a api route e.g: /pages/api/revalidate.

Usage

// pages/api/revalidate.js
import { revalidateHandler } from '@headstartwp/next';

export default async function handler(req, res) {
return revalidateHandler(req, res);
}

Parameters

NameTypeDescription
reqNextApiRequestThe request object,
resNextApiResponse<any>The response object.

Returns

Promise<void>

A response object.

Defined in

packages/next/src/handlers/revalidateHandler.ts:30

Data Fetching Hooks

useAppSettings

useAppSettings<T, P>(params?, options?): useAppSettingsResponse<T>

The useAppSettings hook

Usage

const { data, loading, error } = useAppSettings();

// check loading and error states

Server-Side-Rendering or Static-Site-Generation

export async function getServerSideProps(context) {
const useAppSettingsData = await fetchHookData(useAppSettings.fetcher(), context);
return addHookData([useAppSettingsData], {});
}

Important: You most likely want to fetch app settings on every route so that you can access global settings and menus in your pages & components

Type parameters

NameType
Textends AppEntity = AppEntity
Pextends EndpointParams = EndpointParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T>>Options for the SWR configuration

Returns

useAppSettingsResponse<T>

Defined in

packages/next/src/data/hooks/useAppSettings.ts:33


useAuthorArchive

useAuthorArchive<T, P>(params?, options?): usePostsResponse<T>

The useAuthorArchive hook. Returns a collection of post entities queried by author

This hook must be used with a catch-all route [...path].js (e.g: pages/author/[...path].js)

Important: Use a catch-all and not an optional catch-all route ([[...path]].js) as the author param in the url is required.

In order to automatically map URL params create a catch-all route named [...path].js. You can create the catch-all at any level e.g: pages/author/[...path].js, etc.

The pages/author/[...path].js route for instance would yield a URL like this: /author-name/page/2, /author-name/category/category-name/page/3, etc.

The following URL params are supported:

  • Category (/author-name/category/category-name)
  • Tag (/author-name/tag/tag-name)
  • Author (/author/author-name)
  • Pagination (/page/2)
  • Custom Taxonomy (/author//taxonomy/term-name)

Type parameters

NameType
Textends PostEntity = PostEntity
Pextends PostsArchiveParams = PostsArchiveParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T[]>>Options for the SWR configuration

Returns

usePostsResponse<T>

Defined in

packages/next/src/data/hooks/useAuthorArchive.ts:29


useMenu

useMenu(menuLocation, options?): useMenuResponse

The useMenu hooks. Returns a Menu object.

Important: This hook depends on useAppSettings. If you want to enable SSR;SSG for this hook you will need to fetch app settings on the server side.

Usage

Basic usage

export const Nav = () => {
const { data, loading, error } = useMenu('primary-menu');

// handle loading, error states

return <Menu items={data} css={navStyles} />;
}

Re-fetching client-side on focus and/or mount

If you are fetching app settings on the server, you can enable re-fetching on focus and/or mount to ensure menus are always up-to date even when using SSG/ISR.

export const Nav = () => {
const { data, loading, error } = useMenu('primary-menu', {
revalidateOnFocus: true,
revalidateOnMount: true,
});

// handle loading, error states

return <Menu items={data} css={navStyles} />;
}

Parameters

NameTypeDescription
menuLocationstringThe slug of the menu location you want to fetch
optionsFetchHookOptions<FetchResponse<AppEntity>>SWR configuration options

Returns

useMenuResponse

Defined in

packages/next/src/data/hooks/useMenu.ts:46


usePost

usePost<T, P>(params?, options?): usePostResponse<T>

The usePost hook. Returns a single post entity

In order to automatically map URL params create a catch-all route named [...path].js. You can create the catch-all at any level e.g: pages/[...path].js, pages/blog/[...path].js, etc.

The pages/[...path].js route for instance would yield a URL like this: /post-slug, /2020/01/01/post-slug, etc.

Type parameters

NameType
Textends PostEntity = PostEntity
Pextends PostParams = PostParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T>>Options for the SWR configuration

Returns

usePostResponse<T>

Defined in

packages/next/src/data/hooks/usePost.ts:18


usePostOrPosts

usePostOrPosts<T, P>(params?, options?): usePostOrPostResponse<T>

The usePostOrPosts hook

Type parameters

NameType
Textends PostEntity = PostEntity
Pextends PostOrPostsParams = PostOrPostsParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<PostOrPostsFetchStrategyResult<T>>>Options for the SWR configuration

Returns

usePostOrPostResponse<T>

Defined in

packages/next/src/data/hooks/usePostOrPosts.ts:18


usePosts

usePosts<T, P>(params?, options?): usePostsResponse<T>

The usePost hook. Returns a collection of post entities

In order to automatically map URL params create a catch-all route named [[...path]].js. You can create the catch-all at any level e.g: pages/[[...path]].js, pages/blog/[[...path]].js, etc.

The pages/blog/[[...path]].js route for instance would yield a URL like this: /blog, /blog/page/2, /blog/category/category-name/page/3, etc.

The following URL params are supported:

  • Category (/category/category-name)
  • Tag (/tag/tag-name)
  • Author (/author/author-name)
  • Pagination (/page/2)
  • Date (/YYYY/MM/DD)
  • Custom Taxonomy (/taxonomy/term-name)

Handling multiple WordPress routes in a single next.js route

The usePosts hook is very flexible and can handle multiple WordPress routes in a single next.js route when using the optional-catch-all route ([[...path]].js). Alongside with the actual data, usePosts also returns information about the current route so you can conditionally load different components.

const params = { postType: 'post' };
const Posts = () => {
const { data, pageType } = usePosts(params);

if (pageType.isAuthorArchive) {
return <AuthorArchive data={data} />
}

if (pageType.isCategoryArchive) {
return <CategoryArchive data={data} />
}

if (pageType.isTaxonomyArchive && pageType.taxonomy === 'my-custom-taxonomy' ) {
return <TaxonomyArchive data={data} />
}

return (
<div>
<ul>
{data.posts.map((post) => (
<li key={post.id}>
{post.title.rendered}
</li>
))}
</ul>
</div>
);
};

Type parameters

NameType
Textends PostEntity = PostEntity
Pextends PostsArchiveParams = PostsArchiveParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T[]>>Options for the SWR configuration

Returns

usePostsResponse<T>

Defined in

packages/next/src/data/hooks/usePosts.ts:62


useSearch

useSearch<T, P>(params?, options?): useSearchResponse<T>

The useSearch hook. Returns a collection of search entities

In order to automatically map URL params create a catch-all route named [...path].js. You can create the catch-all at any level e.g: pages/search/[[...path]].js

The pages/search/[[...path]].js route for instance would yield a URL like this: /search/[term]/page/[number], /search/[term] etc

Type parameters

NameType
Textends PostEntity = PostEntity
Pextends PostsArchiveParams = PostsArchiveParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T[]>>Options for the SWR configuration

Returns

useSearchResponse<T>

Defined in

packages/next/src/data/hooks/useSearch.ts:18


useSearchNative

useSearchNative<T, P>(params?, options?): useSearchNativeResponse<T>

The useSearchNative hook. Returns a collection of search entities retrieved through the WP native search endpoint.

In order to automatically map URL params create a catch-all route named [...path].js. You can create the catch-all at any level e.g: pages/search/[[...path]].js

The pages/search/[[...path]].js route for instance would yield a URL like this: /search/[term]/page/[number], /search/[term] etc

Type parameters

NameType
Textends PostSearchEntity | TermSearchEntity = PostSearchEntity | TermSearchEntity
Pextends SearchParams = SearchParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T[]>>Options for the SWR configuration

Returns

useSearchNativeResponse<T>

Defined in

packages/next/src/data/hooks/useSearchNative.ts:18


useSeo

useSeo(format): Record<string, any> | null

The useSeo hook. Returns the current SEO object

Usage

const seo = useSeo();

Parameters

NameTypeDescription
format"json"how to return the seo object. Defaults to 'json'

Returns

Record<string, any> | null

Defined in

packages/next/src/data/hooks/useSeo.ts:18

useSeo(format): string | null

Parameters

NameType
format"html"

Returns

string | null

Defined in

packages/next/src/data/hooks/useSeo.ts:19

useSeo(): Record<string, any> | null

Returns

Record<string, any> | null

Defined in

packages/next/src/data/hooks/useSeo.ts:20


useTerms

useTerms<T, P>(params?, options?): useTermsResponse<T>

The useTerms hook. Returns a collection of term entities

Usage

const { loading, data } = useTerms({ taxonomy: 'category', slug: 'cat-name' });

Type parameters

NameType
Textends TermEntity = TermEntity
Pextends TaxonomyArchiveParams = TaxonomyArchiveParams

Parameters

NameTypeDescription
paramsPartial<P>The parameters accepted by the hook
optionsFetchHookOptions<FetchResponse<T[]>>Options for the SWR configuration

Returns

useTermsResponse<T>

Defined in

packages/next/src/data/hooks/useTerms.ts:19

Next.js Data Fetching Utilities

addHookData

addHookData<P>(_hookStates, nextProps): Object

The addHookData function is responsible for collecting all of the results from the fetchHookData function calls and prepares the shape of the data to match what the frameworks expects (such as setting initial values for SWR and collecting SEO data).

Usage

export async function getServerSideProps(context) {
try {
const usePostsHook = await fetchHookData(usePosts.fetcher(),context);
const useAppSettingsHook = await fetchHookData(useAppSettings.fetcher(),context);
return addHookData([usePostsHook, useAppSettingsHook], {});
} catch (e) {
return handleError(e, context);
}
}

Type parameters

NameType
P{ [key: string]: any; }

Parameters

NameTypeDescription
_hookStatesHookState<FetchResponse<Entity | Entity[]>>[]
nextPropsNextJSProps<P>Any additional props to pass to Next.js page routes.

Returns

Object

NameType
notFound?boolean
props{ fallback: {} ; seo: { yoast_head: string = seo; yoast_head_json: {} = seo_json } ; themeJSON: {} }
props.fallback{}
props.seo{ yoast_head: string = seo; yoast_head_json: {} = seo_json }
props.seo.yoast_headstring
props.seo.yoast_head_json{}
props.themeJSON{}
redirect?Redirect
revalidate?number | boolean

Defined in

packages/next/src/data/server/addHookData.ts:59


convertToPath

convertToPath(args): string

Creates a path from array of arguments

Parameters

NameTypeDescription
argsundefined | string[]Array of catch-all arguments

Returns

string

Defined in

packages/next/src/data/convertToPath.ts:8


fetchHookData

fetchHookData<T, P, R>(fetchStrategy, ctx, options?): Promise<{ additionalCacheObjects: any ; data: FetchResponse<R> ; isMainQuery: boolean ; key: string }>

A function that implements data fetching on the server. This should be used in getServerSideProps or getStaticProps.

Data fetching will be performed by the specified strategy and URL params will be automatically extracted from `context

Usage

export async function getServerSideProps(context) {
try {
const usePostsHook = await fetchHookData(usePosts.fetcher(),context);

return addHookData([usePostsHook], {});
} catch (e) {
return handleError(e, context);
}
}

@param fetchStrategy The fetch strategy to use. Typically this is exposed by the hook e.g: usePosts.fetcher() @param ctx The Next.js context, either the one from getServerSideProps or getStaticProps @param options See {@link FetchHookDataOptions}

@returns An object with a key of data and a value of the fetched data.

Type parameters

NameType
Tunknown
Pextends EndpointParams = EndpointParams
RT

Parameters

NameType
fetchStrategyAbstractFetchStrategy<T, P, R>
ctxGetServerSidePropsContext<any, PreviewData> | GetStaticPropsContext<any, PreviewData>
optionsFetchHookDataOptions<P, T>

Returns

Promise<{ additionalCacheObjects: any ; data: FetchResponse<R> ; isMainQuery: boolean ; key: string }>

Defined in

packages/next/src/data/server/fetchHookData.ts:81


handleError

handleError(error, ctx, rootRoute?): Promise<GetServerSidePropsResult<{}>>

The handleError function is responsible for handling errors that occur during data fetching in getServerSideProps or getStaticProps.

It also handles redirects if redirectStrategy is set to 404 in headless.config.js

If error is of type NotFoundError it will redirect to the 404 page. Otherwise it will return a server error (500) page

Usage

export async function getServerSideProps(context) {
try {
const usePostsHook = await fetchHookData(usePosts.fetcher(),context);
return addHookData([usePostsHook], {});
} catch (e) {
return handleError(e, context);
}
}

Parameters

NameTypeDefault valueDescription
errorErrorundefinedThe error object
ctxHeadlessGetServerSidePropsContext<ParsedUrlQuery> | HeadlessGetStaticPropsPropsContext<ParsedUrlQuery>undefinedThe Next.js context
rootRoutestring''The root route (deprecated/unnecessary). This needs to be revisited

Returns

Promise<GetServerSidePropsResult<{}>>

Defined in

packages/next/src/data/server/handleError.ts:61

Other

HeadlessAppProps

Ƭ HeadlessAppProps: Object

The props supported by HeadlessApp.

Type declaration

NameTypeDescription
children?ReactNode-
handleYoast?booleanIf true, will automatically load yoast seo metadata into the head Default true
pagePropsanyThe page props from next.js. It should contain fallback, themeJson and other props. Those props are added when using fetchHookData and addHookData See - fetchHookData - addHookData
settingsSettingsContextPropsSupported settings by the framework. Such as custom image component, custom link component etc. See SettingsContextProps
swrConfigDataFetchingProviderProps["swrConfig"]Pass any configuration to the SWR library. Globally. These settings can be overridden at the hook level.
useYoastHtml?booleanIf true, will make the Yoast component use the yoast_head raw html to populate meta tags instead of yoast_head_json. yoast_head is the default and preferable option.

Defined in

packages/next/src/components/HeadlessApp.tsx:18


HeadlessGetServerSideProps

Ƭ HeadlessGetServerSideProps<P, Q>: GetServerSideProps<P, Q, PreviewData>

Type parameters

NameType
Pextends Object = { [key: string]: any; }
Qextends ParsedUrlQuery = ParsedUrlQuery

Defined in

packages/next/src/data/types.ts:16


HeadlessGetServerSidePropsContext

Ƭ HeadlessGetServerSidePropsContext<Q>: GetServerSidePropsContext<Q, PreviewData>

Type parameters

NameType
Qextends ParsedUrlQuery = ParsedUrlQuery

Defined in

packages/next/src/data/types.ts:10


HeadlessGetStaticProps

Ƭ HeadlessGetStaticProps<P, Q>: GetStaticProps<P, Q, PreviewData>

Type parameters

NameType
Pextends Object = { [key: string]: any; }
Qextends ParsedUrlQuery = ParsedUrlQuery

Defined in

packages/next/src/data/types.ts:21


HeadlessGetStaticPropsPropsContext

Ƭ HeadlessGetStaticPropsPropsContext<Q>: GetStaticPropsContext<Q, PreviewData>

Type parameters

NameType
Qextends ParsedUrlQuery = ParsedUrlQuery

Defined in

packages/next/src/data/types.ts:13


HookState

Ƭ HookState<T>: Object

Type parameters

Name
T

Type declaration

NameType
additionalCacheObjects?HookState<T>[]
dataT
isMainQueryboolean
keystring

Defined in

packages/next/src/data/server/addHookData.ts:10


NextJSProps

Ƭ NextJSProps<P>: Object

Type parameters

Name
P

Type declaration

NameType
notFound?boolean
props?P
redirect?Redirect
revalidate?number | boolean

Defined in

packages/next/src/data/server/addHookData.ts:17


PreviewData

Ƭ PreviewData: Object

The shape of the preview data that's stored in the preview data cookie

Index signature

[k: string]: unknown

Type declaration

NameTypeDescription
authTokenstringThe auth token that should be used to fetch the data
idnumberThe id of the resource
postTypestringThe post type
revisionbooleanWhether the preview data is on a revision

Defined in

packages/next/src/handlers/types.ts:4


PreviewHandlerOptions

Ƭ PreviewHandlerOptions: Object

The options supported by previewHandler

Type declaration

NameType
getRedirectPath?(defaultRedirectPath: string, post: any, postTypeDef: CustomPostType) => string
onRedirect?(req: NextApiRequest, res: NextApiResponse, previewData: PreviewData, defaultRedirect?: PreviewHandlerOptions["onRedirect"], redirectpath?: string) => void
preparePreviewData?(req: NextApiRequest, res: NextApiResponse, post: PostEntity, previewData: PreviewData) => PreviewData

Defined in

packages/next/src/handlers/previewHandler.ts:11


VIPCustomImageLoader

Ƭ VIPCustomImageLoader: ImageLoaderProps & { aspectRatio?: string }

Defined in

packages/next/src/components/ImageComponent.tsx:30


seoKey

Const seoKey: "@seo"

Defined in

packages/next/src/data/hooks/useSeo.ts:3


VIPImageLoader

VIPImageLoader(props): string

Custom Image loader for WordPress VIP leveraging Photon's API. This can't be made a global loader because of the local loader used on the custom image component.

Parameters

NameTypeDescription
propsVIPCustomImageLoaderThe loader props

Returns

string

Defined in

packages/next/src/components/ImageComponent.tsx:42


convertUrl

convertUrl(url, hostUrl, sourceUrl): string

Parameters

NameType
urlstring
hostUrlstring
sourceUrlstring

Returns

string

Defined in

packages/next/src/components/Yoast.tsx:15


getPathName

getPathName(resolvedUrl): string

Extracts the path name out of the Next.js resolvedUrl

Parameters

NameTypeDescription
resolvedUrlstringThe full resolved URL

Returns

string

Defined in

packages/next/src/data/server/handleError.ts:23


getSiteFromContext

getSiteFromContext(ctx): HeadlessConfig | { customPostTypes: CustomPostTypes ; customTaxonomies: CustomTaxonomies ; debug: undefined | { devMode?: boolean ; redirects?: boolean ; requests?: boolean } ; hostUrl: string ; integrations: undefined | Integrations ; redirectStrategy: RedirectStrategy ; sites: HeadlessConfig[] ; sourceUrl: undefined | string ; useWordPressPlugin: boolean }

Get site using context

Parameters

NameType
ctxGetServerSidePropsContext<ParsedUrlQuery, PreviewData> | GetStaticPropsContext<ParsedUrlQuery, PreviewData>

Returns

HeadlessConfig | { customPostTypes: CustomPostTypes ; customTaxonomies: CustomTaxonomies ; debug: undefined | { devMode?: boolean ; redirects?: boolean ; requests?: boolean } ; hostUrl: string ; integrations: undefined | Integrations ; redirectStrategy: RedirectStrategy ; sites: HeadlessConfig[] ; sourceUrl: undefined | string ; useWordPressPlugin: boolean }

HeadlessConfig

Defined in

packages/next/src/data/server/getSiteFromContext.ts:10


usePrepareFetch

usePrepareFetch<T, P>(_params?, options?): Object

Prepares params and options for useFetch hooks

Type parameters

NameType
Textends Entity | Entity[]
Pextends EndpointParams

Parameters

NameTypeDescription
_paramsPartial<P>The fetch params
optionsFetchHookOptions<FetchResponse<T>>The fetch options

Returns

Object

NameType
optionsFetchHookOptions<FetchResponse<T>>
paramsPartial<P>
pathstring

Defined in

packages/next/src/data/hooks/usePrepareFetch.ts:13

React Components

HeadlessApp

HeadlessApp(props): Element

The HeadlessApp component is the top level component for the Headless framework.

Should be used in pages/_app.js

Usage

import { HeadlessApp } from "@headstartwp/next";

const MyApp = ({ Component, pageProps }) => {
const { fallback = {}, themeJson = {}, ...props } = pageProps;

return (
<HeadlessApp
pageProps={pageProps}
settings={{
// Pass your own link components here
linkComponent: Link,
}}
>
<Layout>
<Component {...props} />
</Layout>
</HeadlessApp>
);
};

export default MyApp;

Parameters

NameTypeDescription
propsHeadlessAppPropsComponent props. See HeadlessAppProps

Returns

Element

Defined in

packages/next/src/components/HeadlessApp.tsx:96


ImageComponent

ImageComponent(props): Element

An implementation of the ImageBlock (core/image).

If width, height or src are not provided, this component will not be used.

Usage

import { BlocksRenderer, ImageBlock } from "@headstartwp/core/react";
import { ImageComponent } from "@headstartwp/next";

<BlocksRenderer html={html}>
<ImageBlock component={ImageComponent} />
</BlocksRenderer>

Parameters

NameTypeDescription
propsImagePropsImageBlockProps

Returns

Element

Defined in

packages/next/src/components/ImageComponent.tsx:98


LinkBlock

LinkBlock(props): Element

The Link Block converts a anchor tag node into a next/link component if it's an internal link

Usage

import { BlocksRenderer } from "@headstartwp/core/react";
import { LinkBlock } from "@headstartwp/next";

<BlocksRenderer html={html}>
<LinkBlock />
</BlocksRenderer>

Parameters

NameTypeDescription
propsOmit<IBlock<LinkBlockProps>, "component">Link Block Props

Returns

Element

The next/link component

Defined in

packages/next/src/blocks/LinkBlock.tsx:33


TwitterBlock

TwitterBlock(props): Element

Renders a twitter embed

Usage

import { BlocksRenderer } from "@headstartwp/core/react";
import { TwitterBlock } from "@headstartwp/next";

<BlocksRenderer html={html}>
<TwitterBlock />
</BlocksRenderer>

Parameters

NameTypeDescription
propsOmit<IBlock<IBlockAttributes>, "component">Link Block Props

Returns

Element

Defined in

packages/next/src/blocks/TwitterBlock.tsx:25


Yoast

Yoast(props): Element

The Yoast component renders the Yoast SEO meta tags. This component is automatically rendered by HeadlessApp so you don't have to manually render it.

Parameters

NameTypeDescription
propsPropsComponent props. Expects a single seo prop

Returns

Element

Defined in

packages/next/src/components/Yoast.tsx:61