Skip to main content

Adding Prismic data

tip

This tutorial assumes you have completed the basic tutorial and have the artifacts from that already present in Uniform.

Let's add some content data from Prismic into your Uniform Canvas-powered Next app. To do this we will need to add a new Prismic-powered parameter to your component type, and then tell your Next app how to fetch and parse the Prismic data to display it. Canvas provides a framework for enhancing data in your Canvas composition with data from other tools, like CMSes, DAMs, commerce, and search indexes. This enhancement is done on the app side, leaving full flexibility to the developer as to the best and most efficient way to get the data.

First let's connect Uniform to Prismic by installing the integration. You'll need a Prismic account to do this (a free one is fine).

  1. Go to Settings on your on https://uniform.app project, then click Integrations
  2. Find the Prismic integration and add it
  3. Click the button to add a content source
  4. Provide the Repository ID, Access Token for the Prismic project that you want to bring content from into Canvas

Now that we're connected to Prismic, we can add a new parameter to our Canvas component type that links to a Prismic document.

  1. Go to your Component Library settings
  2. Open your component type (there should be only one, if you've been following along)
  3. Click (+) next to Parameters
  4. Name your parameter something like 'Prismic Document', choose Prismic Document as the type, pick a Prismic source (repository) from which documents will be selected, pick Prismic custom type(s) that can be linked, and as before choose a public ID to use as the name in code. (e.g. prismicDocument)

Now that the parameter is added to the component type, we need to link the composition we have been rendering to an actual Prismic document:

  1. Click Compositions, then open your composition from earlier
  2. You should see a Prismic parameter alongside the text parameter we created before
  3. Choose a Prismic document to link to and save your composition
  4. That's it - you've linked to a Prismic document in your composition

With the data schema setup complete, now let's set up Next.js. Right now we're doing nothing with the Prismic data - the Next app will look exactly the same as it did before, except it has a new parameter we're doing nothing with. To get the Prismic data, we need to add an enhancer to the Next app's data fetching so that Canvas knows what to do with Prismic parameters.

  1. If your Prismic API is secured (by default the Prismic API is not secured), you will need your Prismic access token, which can be found in your Prismic project settings for the content source you selected in the Prismic Canvas integration settings.

  2. Install the @uniformdev/canvas-prismic and @prismicio/client and prismic-dom packages, which contains the Canvas Prismic enhancer and the Prismic Client and the Prismic DOM helpers respectively.

  3. Open your pages/index.js file and import the Prismic enhancer, and add enhance to the existing canvas import:

    import {
    createPrismicEnhancer,
    CANVAS_PRISMIC_PARAMETER_TYPES,
    PrismicClientList,
    } from '@uniformdev/canvas-prismic';
    import { enhance, CanvasClient, EnhancerBuilder } from '@uniformdev/canvas';
    import * as Prismic from '@prismicio/client';
    import PrismicDOM from 'prismic-dom';
  4. In getStaticProps, create the enhancer and configure it to connect to Prismic and enhance your composition data:

    // ...fetching the composition here

    // NOTE: for production code ensure you use environment variables to
    // configure Prismic, not hard-coded values.
    const endpoint = Prismic.getRepositoryEndpoint('you-prismic-repository-id');
    const client = Prismic.client(endpoint, {
    // note: accessToken is only necessary if your API is secured
    accessToken: 'your-prismic-access-token',
    });

    // create the Prismic enhancer
    const prismicEnhancer = createPrismicEnhancer({ clients: new PrismicClientList({ client }) });

    // apply the enhancers to the composition data, enhancing it with external data
    // In this case, the _value_ of the Prismic parameter you created is enhanced
    // with data from the Prismic document you selected in the Prismic document selector.
    // You can create your own enhancers easily; they are a simple function.
    await enhance({
    composition,
    enhancers: new EnhancerBuilder().parameterType(CANVAS_PRISMIC_PARAMETER_TYPES, prismicEnhancer),
    context: {},
    });

    // ...returning the props

    The Next app should still be working, but we're not rendering any of the Prismic data yet. Let's do that!

  5. In the Home component implementation, get the Prismic parameter value and pick a field from it:

    export default function Home({ composition }) {
    return (
    <Composition data={composition}>
    {/* note: `prismicDocument` is the "public id" value you provided for
    the Prismic Document parameter. */}
    {({ greeting, prismicDocument }) => (
    <article>
    <p>{greeting}</p>
    {/* we assume your document type has a field called 'title' on it */}
    <p>{PrismicDOM.RichText.asText(prismicDocument.data.title)}</p>
    </article>
    )}
    </Composition>
    );
    }
  6. That's it - now you're rendering data from Prismic! The default structure of the enhancer result is that of a single Prismic document fetched from the Prismic REST API.

tip

Use TypeScript? So do we. Here's the same code with TypeScript.

TypeScript Code
import { enhance, CanvasClient, EnhancerBuilder, ComponentInstance } from '@uniformdev/canvas';
import { Composition } from '@uniformdev/canvas-react';
import {
PrismicEnhancerResult,
createPrismicEnhancer,
PrismicClientList,
CANVAS_PRISMIC_PARAMETER_TYPES,
} from '@uniformdev/canvas-prismic';
import * as Prismic from '@prismicio/client';
import PrismicDOM from 'prismic-dom';
import { GetStaticProps } from 'next';

type HomeProps = {
composition: ComponentInstance;
};

type MyCanvasComponentType = {
greeting: string;
prismicDocument: PrismicEnhancerResult;
};

export default function Home({ composition }: HomeProps) {
return (
<Composition<MyCanvasComponentType> data={composition}>
{({ greeting, prismicDocument }) => (
<article>
<p>{greeting}</p>
<p>{PrismicDOM.RichText.asText(prismicDocument.data.title)}</p>
</article>
)}
</Composition>
);
}

export const getStaticProps: GetStaticProps<HomeProps> = async () => {
// create the Canvas client
const canvasClient = new CanvasClient({
// if this weren't a tutorial, ↙ should be in an environment variable :)
apiKey: 'your-api-key-here',
// if this weren't a tutorial, ↙ should be in an environment variable :)
projectId: 'your-project-id-here',
});

// fetch the composition from Canvas
const { composition } = await canvasClient.getCompositionBySlug({
// if you used something else as your slug, use that here instead
slug: '/',
});

// NOTE: for production code ensure you use environment variables to
// configure Prismic, not hard-coded values.
const endpoint = Prismic.getRepositoryEndpoint(prismicRepositoryId);

const client = Prismic.client(endpoint, {
// note: accessToken is only necessary if your API is secured
accessToken: 'your-prismic-access-token',
});

const prismicEnhancer = createPrismicEnhancer({ clients: new PrismicClientList({ client }) });

await enhance({
composition,
enhancers: new EnhancerBuilder().parameterType(CANVAS_PRISMIC_PARAMETER_TYPES, prismicEnhancer),
context: {},
});

return {
props: {
composition,
},
};
};