Migrating to the @nuxtjs/prismic module

In this article we will show you how to migrate legacy projects using the old prismic-vue plugin to the new @nuxtjs/prismic module.

With the help of James Pegg and the team at Nuxt we worked to create a plugin to allow static deployment of Nuxt.js projects with a full set of Prismic features including previews.

Let us know if there's anything we forgot that might be necessary in your projects. OK! Let's go.

package.json

In you package.json file you need to make some changes.

Update: prismic-vue (at least 2.0.0). nuxt (2.11.0) + any other packages.

Copy
npm upgrade nuxt

Install: @nuxtjs/prismic (1.1.0)

Copy
npm i @nuxtjs/prismic

nuxt.config.js

In your Nuxt config file you'll need to make a lot of changes. Here's a link to a nuxt.config.js with the old setup. This is what your updated nuxt.config.js file should look like. Changes include:

  • Adding modules
  • Configuration settings for the plugin
  • Generating a fallback for the 404
Copy
export default {
  mode: 'universal',

  /*
  ** Headers of the page
  */
  head: {
    title: 'Prismic + Nuxt Blog example',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Prismic + Nuxt Blog example' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato:300,400,700,900' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },

  /*
  ** Global CSS
  */
  css: [
    '@/assets/css/resetr.css',
    '@/assets/css/common.css'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // modules for full static before `nuxt export` (coming in v2.12)
    '@/modules/static',
    '@/modules/crawler',
    // This is where you import the new plugin
    '@nuxtjs/prismic'
  ],

  // This is where you configure your settings for the new plugin
  prismic: {
    endpoint: 'https://your-repo-name.cdn.prismic.io/api/v2',
    linkResolver: '@/plugins/link-resolver',
    htmlSerializer: '@/plugins/html-serializer',
  },

  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      config.resolve.alias['vue'] = 'vue/dist/vue.common'
    }
  },

  // Netlify reads a 404.html, Nuxt will load as an SPA
  generate: {
    fallback: '404.html'
  }
}

Queries

Here's where some of the biggest changes in your project might come. While a query with the old setup might have looked like this:

Copy
async asyncData({context, error, req}) {
    try{
      // Query to get API object
      const api = await Prismic.getApi(PrismicConfig.apiEndpoint, {req})
      // Query to get blog home content
      const document = await api.getSingle('blog_home')
      let homepageContent = document.data
      // Query to get posts content to preview
      const blogPosts = await api.query(
        Prismic.Predicates.at("document.type", "post"),
        { orderings : '[my.post.date desc]' }
      )
      // Load the edit button
      if (process.client) window.prismic.setupEditButton()
      // Returns data to be used in template
      return {
        homepageContent,
        documentId: document.id,
        posts: blogPosts.results,
        image: homepageContent.image.url,
      }
    } catch (e) {
      // Returns error page
      error({ statusCode: 404, message: 'Page not found' })
    }
  },

Below is the same query using the syntax of the new plugin: (code comments explain further)

Copy
// Here we pass the new $prismic module, we no longer need the 'req'
async asyncData({ $prismic, error }) {
    try{
      // Here we query blog home content using $prismic which
			// has the api endpoint data from the nuxt.config.js
      const homepageContent = (await $prismic.api.getSingle('blog_home')).data

      // Query to get posts content, here we also change the 'predicates' query
      const blogPosts = await $prismic.api.query(
        $prismic.predicates.at("document.type", "post"),
        { orderings : '[my.post.date desc]' }
      )

      // Returns data to be used in template
      return {
        homepageContent,
        posts: blogPosts.results,
        image: homepageContent.image.url,
      }
    } catch (e) {
      // Returns error page
      error({ statusCode: 404, message: 'Page not found' })
    }
  },

So you'll notice, previously you had to query the api object first then query for the document. Now you only have to do one query for this const homepageContent. The other main change here is adding the $prismic method. This is the same for getByUid helper function.

NOTE: We also removed references to the edit button. You can read more about this below.

Templating

One last thing that you will need to change is how you template so of you text fields. If you want to deliver any of your Rich Text fields as simple plain text you will need change richTextAsPlain method to asText.

Change this (from the old plugin):

Copy
{{ $prismic.richTextAsPlain(document.title) }}

To this:

Copy
{{ $prismic.asText(document.title) }}

NOTE: This is the only templating change between the plugins, everything else stays the same.

EXTRA: Previews and edit buttons

Some older set ups used the old Prismic toolbar for the edit button and previews. We no longer need the following code to do that, so you can remove anything needed for that.

Copy
<!-- Button to edit document in dashboard -->
<prismic-edit-button :documentId="documentId"/>
Copy
// Load the edit button
if (process.client) window.prismic.setupEditButton()
Copy
//You don't need to return the document id anymore.
documentId: document.id,

NOTE: That's all you need to do, all the preview magic is now handled for you by the @nuxtjs/prismic module.

SUGGESTED: modules: crawler + static (optional)

These modules are for implementing full static deployment in preparation for the nuxt export feature (coming in v2.12), adding these now will help future-proof your project. https://github.com/prismicio/nuxtjs-blog/tree/master/modules

Summary

This might seem like a lot, but it's a quick process for the advantages that you gain. You should now be able to fully deploy your project statically on a service like Netlify.

Let us know if there is anything that we missed in this process to help people when changing over to the new plugin!