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

next-tinacms-contentful

v0.7.15

Published

> TODO: description

Downloads

22

Readme

next-tinacms-contentful

A utility library for using Contentful with TinaCMS and Next.js

Usage

If you are looking to use Contentful in client-side JS, please see one of the following:

If you are looking to use Contentful inside of Next.js' build-time and serverless logic like API routes, getStaticProps and getServerSideProps, continue reading:

Installation

To install the package, run:

npm install next-tinacms-contentful react-tinacms-contentful tinacms-contentful contentful contentful-management

Fetching Entries On The Server

Fetching A Single Entry

To fetch a single entry, you can use getEntry:

import getEntry from 'next-tinacms-contentful'

const contentfulOptions = {
  spaceId: /* Contentful Space ID */,
  defaultEnvironmentId: /* Contentful environment ID to use by default. Default: master */,
  accessTokens: {
    delivery: /* Contentful delivery access token for the space */,
    preview: /* Contentful preview access token for the space */,
  }
  clientId: /* OAuth App Client ID */,
  redirectUrl: /* OAuth App Callback URL */,
  rateLimit: /* API Rate Limit for your Contentful Plan (Requests per second). Default: 4 */,
  insecure: /* If true, uses same-site HTTPS cookies to create a session. Default: false */
}

export async function getStaticProps() {
  try {
    const entry = await getEntry('EXAMPLE_ID', contentfulOptions);

    return {
      props: {
        entry
      }
    }
  } catch (error) {
    console.error(error)

    return {
      notFound: true
    }
  }
}

Fetching Many Entries

To fetch many entries, you can use getEntries:

import getEntries from 'next-tinacms-contentful'

const contentfulOptions = {
  spaceId: /* Contentful Space ID */,
  defaultEnvironmentId: /* Contentful environment ID to use by default. Default: master */,
  accessTokens: {
    delivery: /* Contentful delivery access token for the space */,
    preview: /* Contentful preview access token for the space */,
  }
  clientId: /* OAuth App Client ID */,
  redirectUrl: /* OAuth App Callback URL */,
  rateLimit: /* API Rate Limit for your Contentful Plan (Requests per second). Default: 4 */,
  insecure: /* If true, uses same-site HTTPS cookies to create a session. Default: false */
}

export async function getStaticProps() {
  try {
    const entry = await getEntries({ content_type: "EXAMPLE_CONTENT_TYPE_ID" }, contentfulOptions);

    return {
      props: {
        entry
      }
    }
  } catch (error) {
    console.error(error)

    return {
      notFound: true
    }
  }
}

Edit Mode

Server-side Sessions with Next.js Preview Mode

You can enable an "edit mode" for your site using server-side sessions with Next.js Preview mode, which uses HTTP only cookies to allow server-side logic to be run in front of requests, providing a user specific payload of data on context.previewData in getStaticProps, getServerSideProps, and in API routes, as well as allowing getStaticProps to work like getServerSideProps when users log in to edit pages to allow editing-specific business logic.

First, in pages/api add a new API route called editing.js with the following contents:

import { editModeHandler } from 'next-tinacms-contentful'

export const editingHandler = editModeHandler(60)

editModeHandler creates a serverless function that handles creating an "editing session" by enabling Next.js preview mode for the current user if it is not enabled, and adding metadata to Next.js' preview data to allow changing how the page behaves for editing.

Values

| Key | Type | Description | | --- | --- | --- | | context.previewData.tina_enabled | boolean | True if logged in, false if not | | context.previewData.contentful_bearer_token | string \| null | If defined, is the bearer token for the current logged in user |


Then, you need to update the CMS to enable edit mode when the user finishes logging in. We do this by adding some configuration to the ContentfulProvider, which is usually found in pages/_app.js:

import { toggleEditing } from 'next-tinacms-contentful'

export function MyApp({ pageProps, Component }) {
  const cms = useMemo(() => {
    ...
  }, [])

  return (
    <TinaProvider cms={cms}>
      <ContentfulProvider 
        onLogin={() => toggleEditing(true)}
        onLogout={) => toggleEditing(false)}
      >
        <Component {...pageProps} />
      </ContentfulProvider>
    </TinaProvider>
  )
}

toggleEditing makes a HTTP POST request to the api/editing route, enabling or disabling the cms based on the boolean value passed in, and logs any errors to the user's console.


Finally in any of your pages, you can use getStaticProps or getServerSideProps to check if edit mode is enabled:

export function getStaticProps(context) {
  const entry = getEntry('EXAMPLE_ID', { 
    ...contentfulOptions,
    mode: context.previewData.tina_enabled ? "preview" : "delivery"
  })

  return {
    props: {
      entry
    }
  }
}

APIs

The library has the following core APIs:

  • ContentfulClient: an API client for communicating with Contentful that integrates directly with the CMS.
  • ContentfulMediaStore: a media store that uses a ContentfulClient to manage media for a single space.
  • Provider: a React provider for official plugins and authorization.
  • Hooks: a series of React Hooks for interacting with Contentful in your React app and CMS Plugins.
  • Server-side Methods: utility methods for interacting with Contentful on the server.

There are other public APIs as well. To learn more, read the full Next.js API documentation or read the full JavaScript API documentation.

Server-side Methods

  • getEntry: fetch a published delivery, draft preview, or editable management entry.
  • getEntries: fetch multiple published delivery, draft preview, or editable management entries.
  • getAsset: fetch a published delivery, or draft preview asset.
  • getAssets: fetch multiple published delivery, or draft preview assets.
  • proxy: [EXPERIMENTAL] proxies requests to Contentful in server side logic, attaching bearer tokens from edit mode on the way.
  • toggleEditing: sends a fetch request to enable edit mode.
  • editModeHandler: a serverless request handler for toggling edit mode in a Next.js API function.