title |
---|
Sourcing from Prismic |
In this guide, we'll walk through setting up a site with content management using Prismic.
Prismic is a hosted, proprietary Headless CMS (SaaS) with a web app for creating and publishing content. It's suitable for marketers, editors and developers as it has both a "Writing Room" and a fully-fledged API & Content backend. Besides the usual advantages of a SaaS CMS (hosting, security, updates) Prismic offers features like: Custom type builder, scheduling and content versioning and multi-language support.
The written instructions get accompanied by uncommented YouTube videos which will show the described steps in action. The video playlist can be found here.
Note: This guide uses the Gatsby Hello World starter to provide a very basic understanding of how Prismic can work with your Gatsby site. If you'd like to start with a full blown template, check out gatsby-starter-prismic. If you're not familiar with Prismic and its functionalities yet, we highly recommend to check out their official documentation which also includes user guides and tutorials. This guide assumes that you have basic knowledge of Prismic & Gatsby (See the official tutorial).
Before initializing the Gatsby project you should sign up for an account on Prismic.io. The free plan is a perfect fit for personal or smaller projects. Create a new blank repository to get to the content overview of your repository.
Create your first custom type (Repeatable Type) with the name Post
and add some fields to it. Choose rational names for the API ID
input while configuring a field because these names will appear in your queries. You should always add the uid
field in order to have a unique identifier. Then switch to the content overview and create a new document with your Post
type. Fill out the fields and publish the item.
So that Gatsby can grab all information from Prismic you'll need to generate an Access Token. Head over to Settings → API & Security
, fill out the Application name
field (the Callback URL one can be left empty), and press Add this application
.
First, open a new terminal window and run the following to create a new site. This will create a new directory called prismic-tutorial
that contains the starters site, but you can change "prismic-tutorial" in the command below to be whatever you like.
gatsby new prismic-tutorial https://github.com/gatsbyjs/gatsby-starter-hello-world
Now move into the newly created directory and install the Gatsby plugin for Prismic:
cd prismic-tutorial
npm install --save gatsby-source-prismic
In addition to that you also have to install the package dotenv
to securely use your access tokens locally as you should never commit secret API keys to your repository!
npm install --save-dev dotenv
Create a file called .env.development
at the root of your project with the following content:
API_KEY=your-secret-access-token-wou7evoh0eexuf6chooz2
Note: If you want to locally build your project you'll also have to create a .env.production
file with the same content.
Now you need to configure the plugin (See all available options). The repositoryName
is the name you have entered at the creation of the repository (you'll also find it as the subdomain in the URL). The linkResolver
function is used to process links in your content. Fields with rich text formatting or links to internal content use this function to generate the correct link URL. The document node, field key (i.e. API ID), and field value are provided to the function. This allows you to use different link resolver logic for each field if necessary (More information).
Add the following to register the plugin:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
plugins: [
{
resolve: `gatsby-source-prismic`,
options: {
repositoryName: `your-repository-name`,
accessToken: `${process.env.API_KEY}`,
linkResolver: ({ node, key, value }) => post => `/${post.uid}`,
},
},
],
}
The best way to create your queries now is to first develop them in GraphiQL at http://localhost:8000/___graphql
and then paste them into your files. For that start the local development server and experiment a bit with the available queries. You should be able to get this query:
Because you defined the custom type as Post
the query is called allPrismicPost
(and prismicPost
). You can also see the API IDs (from the field names) you created earlier.
With this information you can create pages/templates as usual:
const path = require("path")
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const pages = await graphql(`
{
allPrismicPost {
edges {
node {
id
uid
}
}
}
}
`)
const template = path.resolve("src/templates/post.jsx")
pages.data.allPrismicPost.edges.forEach(edge => {
createPage({
path: `/${edge.node.uid}`,
component: template,
context: {
uid: edge.node.uid,
},
})
})
}
import React from "react"
import { graphql } from "gatsby"
const Post = ({ data: { prismicPost } }) => {
const { data } = prismicPost
return (
<React.Fragment>
<h1>{data.title.text}</h1>
<div dangerouslySetInnerHTML={{ __html: data.content.html }} />
</React.Fragment>
);
}
export default Post
export const pageQuery = graphql`
query PostBySlug($uid: String!) {
prismicPost(uid: { eq: $uid }) {
uid
data {
title {
text
}
content {
html
}
}
}
}
`
Netlify can not only automatically start builds on pushes to a repository but also accepts webhooks to do so. Fortunately Prismic can trigger webhook URLs when publishing content. Hence new content will automatically appear on your Netlify site.
Setup your Netlify project and afterwards go to the Build hooks
setting at Settings → Build & deploy
. You'll receive an URL of the format https://api.netlify.com/build_hooks/-randomstring-
after clicking Add build hook
.
On your Prismic project visit the Webhooks
setting and insert the copied URL into the respective field. Confirm with Add this webhook
. Everytime you publish a new document now Netlify will re-build your site.
Prismic offers a Content Relationship field which is used to link to another document in your Prismic repository. You can use that in combination with a custom type to create a tagging system (in this example categories). And what's cool about that? You can edit your entries any time and they'll update in every post! Read the official docs on that or watch the video:
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/67yir-jQrFk?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>The video shows the usage of a group field and relationship field — if you only want to have one category skip the group field. Similar as to the Post
custom type the Category
one can also be queried. Furthermore the allPrismicPost
query also has the categories
node available:
When creating a new custom type you are able to choose Single Type
, too. In this example you'll fill the homepage with content from Prismic and therefore have complete control over the content of your site. The goal is to eliminate the need to change the website code, and rather your content in Prismic. Visit your Prismic repository and follow the video:
Single pages (like your homepage, privacy policy page etc.) don't need GraphQL connections (e.g. allPrismicHomepage
) due to the fact that only one document for that type exists in Prismic anyway. Therefore you need to use prismicHomepage
for your query. This also has the benefit that you don't need to map over an array. Your page could look something like this:
import React from 'react'
import { graphql, Link } from 'gatsby'
const Index = ({ data: { prismicHomepage } }) => (
<React.Fragment>
<h1>{prismicHomepage.data.title.text}</h1>
<div dangerouslySetInnerHTML={{ __html: prismicHomepage.data.content.html }} />
</React.Fragment>
)
export default Index
export const pageQuery = graphql`
query IndexQuery {
prismicHomepage {
data {
title {
text
}
content {
html
}
}
}
}
`
This was a very basic example meant to help you understand how Prismic works with Gatsby. As mentioned in the beginning of this guide, if you got stuck, you can compare your code to the gatsby-starter-prismic which is the project set up in the videos. A working example created by following this guide is available in the commit history of the aforementioned starter. More advanced usages of Prismic in Gatsby would, e.g. be Slices and Labels.