npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cmpsr/nextjs-contentful-renderer

v24.0.31

Published

Utility functions to retrieve and render content from contentful in mdx format

Downloads

562

Readme

What it is

This is a library to render content from contentful into a nextjs application.

Using the library

The library exposes the following:

  • getPageContent(context: GetServerSidePropsContext, domain?: string). This method takes the nextjs' context object and get the page slug to use it to retrieve the content from contentful. To avoid collisions between similar routes in different projects stored in the same contentful space you can pass domain parameter to this function, or you can set the SITE_DOMAIN env variable to avoid having to pass it in every single call. To retrieve content in preview you can enable nextjs preview mode or you can append ?preview=anything as a query param to the page (anything will enable preview mode, we only check that the query param exists).
  • getStaticPageContent(slug: string, preview = false, domain: string | undefined = undefined). The main difference between this method and the previous one is that it will not look for previously visited pageId or randomize the variant returned (will always return the first one). It is intended to be used from nextjs getStaticProps (see the docs).
  • generateMdx(blocks: Block[], globalVariables: PropsValue = {}): Promise<Model[]>. This function takes the output of the getPageContent/getStaticPageContent and compiles the code to MDX using mdx-bundler.
  • MdxRenderer component. Takes the compiled MDX code from generateMdx and renders the content using react. The component accepts the content to render and a custom componentMap that can be used to render custom components.
  • getDefaultTheme(preview: boolean, domain: string) retrieve the default theme for a given domain or undefined if no default theme is defined. By default preview is set to false and domain to process.env.SITE_DOMAIN. This call use a cache first approach for data fetching. Taking into account that the default theme can not be loaded at the app level because nextjs Custom app does not support data fetching we strongly recommend that each page has a theme associated to avoid a second request to contentful.
  • getStaticRoutes(domain?: string, preview?: string). Returns the list of routes (ids and slugs) that has been defined as static in contentful. This function can be used in the nextjs getStaticPaths function to generate the page at build time. By default it will use process.env.SITE_DOMAIN for the domain and false for the preview mode.

Global variables

Using the CML syntax we provide a mechanism for defining placeholders that are replaced during the mdx generation phase. Those placeholders are replaced by the values provided in the Block or by global variables than can be defined at a top level, in the replica/page for example. This allows us to avoid having to define the same value multiple times in the same page.

The global variables are responsive values defined using the PropsValue format:

const globalVariables = {
  base: {
    variableName: "variable value",
  },
  lg: {
    variableName: "variable value for lg+ breakpoints",
  },
};

Requirements

You will need to define this environment variables to make the library work:

CONTENTFUL_SPACE_ID=
CONTENTFUL_ACCESS_TOKEN_DELIVERY=
CONTENTFUL_ACCESS_TOKEN_PREVIEW=
SITE_DOMAIN=

The CONTENTFUL_ACCESS_TOKEN_PREVIEW is only needed if you will be rendering non published content.

Peer dependencies

The following dependencies should be provided to the library:

  • @apollo/client >= 3.6.2
  • @cmpsr/components version matching package.json definition
  • next >= 12.1.6
  • react >= 18.1.0
  • react-dom >= 18.1.0

Example of usage

import { generateMdx, getPageContent } from "@cmpsr/nextjs-contentful-renderer";
import { MdxRenderer } from "@cmpsr/nextjs-contentful-renderer/client";
import { ComposerProvider } from "@cmpsr/components";

const Page: NextPage<PageProps> = ({ content, title, metaConfiguration }) => {
  const metaTags = Object.values(metaConfiguration) || [];

  const Wrapper = ({ children }) =>
    theme ? (
      <ComposerProvider theme={theme}>{children}</ComposerProvider>
    ) : (
      <>{children}</>
    );

  return (
    <Wrapper>
      <Head>
        <title>{title}</title>
        {metaTags.map((metaTag) => {
          const props = {
            [metaTag.propertyName]: metaTag.propertyValue,
            content: metaTag.content,
          };
          return <meta key={metaTag.propertyValue} {...props} />;
        })}
      </Head>
      {content.map((block, index) => (
        <MdxRenderer key={index} content={block} componentMap={components} />
      ))}
    </Wrapper>
  );
};

export const getServerSideProps: GetServerSideProps<PageProps> = async (
  context: GetServerSidePropsContext
) => {
  const page = (await getPageContent(context)) || pageNotFound;
  const theme =
    page.theme ??
    (await getDefaultTheme(context.query.preview !== undefined)) ??
    null;

  const content: Model[] = await generateMdx(
    page.content,
    page.globalVariables
  );
  return {
    props: {
      title: page.title,
      content,
      metaConfiguration: page.metaConfiguration,
      theme,
    },
  };
};

export default Page;