How to fetch content from Prismic when you’re using Nuxt.js

Nada Rifki
3 min readNov 13, 2018

--

When you don’t want to create your own system to manage your content, using a headless CMS is great! I recently played with Prismic and Nuxt.js (a web application framework based on Vue.js that makes it fun and easier to create server rendered applications) and this combination made me feel like I was living in a perfect world.

However, you can’t create a perfect world without banging your head.

At least, we only had to bang our heads for a few days before finding an optimal way to use Prismic with Nuxt.js.

The thing is that even if Prismic provides you with a custom Vue.js package (prismic-vue) to easily integrate and query its API , when you’re dealing with Nuxt.js, it’s a different story. Because you’ll have to:

  1. Use their Javascript development kit (prismic-javascript) instead of the one for vuejs (prismic-vue).
  2. Query the initial data to render in the asyncData hook.
  3. Pass the newly retrieve attribues of the data object to the right components using props.

It sounds simple… but it felt kind of complicated for me as I was new to the game and nobody else who did it before shared it (so, Stack Overflow wasn’t coming to my rescue this time).

I’ll now go into the details and give you the short step by step tutorial to make that unicorn magic happen:

  1. Go to your Prismic dashboard and create your content repository.
  2. Create a few custom types and publish some documents in your repository.
  3. Add the Prismic javascript kit as a dependency to your project (npm install prismic-javascript --save)
  4. Import Prismic into your page.

First, we’ll be using the created() lifecycle hook to query the API. (don’t forget to change the apiEndpoint’s repository name with your own!).

But folks, this is where it gets complicated. We’re able to query the documents in our repository and console log them but how can we tell our server to use our data in the Prismic repository before sending the content to the browser?

  • We first need to use async asyncData(context) instead of created().
  • Then move our template data from data() to our asyncData(context) and define it in a variable.
  • Tell our server to wait for the API response from Prismic and change our variable data with the result from our query.
  • And only then render our data in the browser.

That’s pretty much it. But you may still run into issues on how to query such or such data. I usually use the Visual Code Studio debugger (which is the recommended way of doing things) or simply console.log the result (which I also do when I feel extra lazy) to find out.

Last but not least: If you are using relationship linked content, here is how you have to proceed:

Have fun now!

If you’re trying to reach me, you can find me on Twitter or we can chat here.

--

--