Implementation of a JAM Stack App using NextJS and Prismic CMS.
Just decided to document this implementation because I've found a lot of overly complex and outdated implementations of this.
Used Chakra UI to make styling more simple.
-
Listing all existing posts in the Prismic Database
-
Displaying each individual post with it's own slug using NextJS dynamic routing
const endpoint = 'https://your-repo-name.prismic.io/api/v2'
const accessToken = 'your-access-token-here'
prismic = Prismic.createClient(endpoint, { accessToken })
export { prismic }
It's recommended to create the client in a separate file (or also even inside a factory method), so that you don't need to create it every time you want to query data.
const response = await client.getByType('post')
const posts = response.results.map(post => {
return {
slug: post.uid,
title: RichText.asText(post.data.title),
content: RichText.asText(post.data.content),
image: post.data.image.url
}
})
return posts
const response = await client.getByUID('post', slug)
const post = {
slug: response.uid,
title: RichText.asText(response.data.title),
content: RichText.asText(response.data.content),
image: response.data.image.url
}
return post
On the examples above "client" stands for the Prismic Client. You can name it however you want.
For this you'll need to create a special kind of file, using [ ].tsx to wrap the file name. You can read more about this here: https://nextjs.org/docs/routing/dynamic-routes. On this example i've created a folder with the name "[slug]" and then created a index.tsx file inside of it.
Inside of this file you'll need to add something like this:
export const getStaticPaths = async () => {
const posts = await prismic.getByType('post')
const paths = posts.results.map(post => {
return {
params: {
slug: post.uid,
}
}
})
return {
paths,
fallback: true
}
}
This will to define a list of paths to be statically generated by Next.
If you have any questions or doubts about the implementation feel free to make an issue!!
=====================================================
Prismic Docs: https://prismic.io/docs
@prismicio/client Technical Reference: https://prismic.io/docs/technical-reference/prismicio-client
Nextjs Docs: https://nextjs.org/docs/getting-started
ChakraUI docs: https://chakra-ui.com/docs/getting-started