Deployment & Previews

Beta

These docs rely on Slice Machine, which is in active development and subject to change. Content Relationships are not currently supported with Slices.

By the end of this final step you will learn how to statically deploy & rebuild your website. You will also learn how to preview Prismic content changes, saving build costs.


Deployment

We're going to deploy our Next.js application on Vercel, this process is super simple so let's get into it.

Connect to GitHub

The first step you'll need to take is to host your code on GitHub. When you create a repository on GitHub, you'll be able to do continuous deployments for your server.

Create a new repo for your project, make sure all of your local changes are committed, then push your project to GitHub.(Here's more info on what GitHub is and how to create a repo.).

Deploy with Vercel

Vercel is a deployment platform for Next.js projects made by the creator of Next.js, so it's only natural that the deployment experience feels as simple as the development experience.

1. To get started, make an account or log in If you don't already have an account.

2.Then, click Import Project. Then continue with import git repository.

3. Enter the URL of your GitHub repo. If necessary, adjust your GitHub app settings to allow Vercel access to the repo.

4. Click deploy. It will take a moment for your site to build.

That's it, your Next.js & Prismic website should now be live! You can learn more about the Vercel platform by consulting their documentation.


Rebuilding / Webhooks

Now that you have your website live, you'll want your content creators to be able to make changes; for that, you'll need your Next.js web app to rebuild when the content is updated. This again is really simple; we need to configure a webhook between Prismic and Netlify.

In your Vercel project, go to "Settings," then "Git Integration." Scroll down to "Deploy Hooks." Create a hook for your main git branch (note: your main branch could also be called master or something else). This will create a URL. Copy the URL.

Go to your Prismic repository, visit "Settings," and then click "Webhooks." Create a new webhook by choosing a name and pasting in the webhook URL you just copied from Vercel. You can leave the "Secret" empty.

Now, whenever you change your content in Prismic, the changes will be reflected on your site.

What are Webhooks?

Webhooks are how you tell external services when there are changes in your Prismic repo. Learn more in our guide to webhooks.


Preview your content changes

Now for the cherry on top. Rebuilding your website once the content changes is great, but if you want to see what these content changes might look like without publishing to your live site, which may incur building costs from your deployment service, then the solution is Prismic Previews. This feature builds your preview on top of the browser so that it's fast & free. Read our full Next.js previews docs here.

Enabling Prismic Previews with the Next Preview mode configuration involves setting up 2 routes in the pages directory:

1. Configure the preview.js route

First, you need to set the Next Preview mode configuration. If it doesn't already exist, create a folder called api and a file called preview.js in the pages directory ~/pages/api/preview.js. The preview configuration uses the Next.js setPreviewData method which sets cookies in the browser, turns on the preview mode, and redirects the request to the appropriate URL using the Link Resolver.

Add the following code in preview.js file:

Copy
import { Client, linkResolver } from "../../prismic-configuration"

export default async (req, res) => {
  const { token: ref, documentId } = req.query;
  const redirectUrl = await Client(req)
    .getPreviewResolver(ref, documentId)
    .resolve(linkResolver, '/');

  if (!redirectUrl) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  res.setPreviewData({ ref });

  res.write(
    `<!DOCTYPE html><html><head><meta http-equiv="Refresh" content="0; url=${redirectUrl}" />
    <script>window.location.href = '${redirectUrl}'</script>
    </head>`
  );
  res.end();
};

2. Configure the exit-preview.js route

This route is required file to exit a Next.js preview session correctly. Whenever you have an active preview session, and you want to exit you'll need to manually hit the /api/exit-preview route in the browser. Like in the following examples:

To configure this create a file called exit-preview.js in the pages directory~/pages/api/exit-preview.js, then add the following code which will clear the data and redirect to the application's homepage.

Copy
export default async (_, res) => {
  res.clearPreviewData();

  res.writeHead(307, { Location: "/" });
  res.end();
};

3. 'Exit Next.js Preview' button

You can create an exit preview component button <ExitPreviewButton /> to hit the exit preview route you just created above, which you only show if the preview data is present. This button will clear the _next_preview_data cookie from your application. You then include this component everywhere in your project using the Layout.js file we created in the last article.

  • ExitPreviewButton.js
  • Layout.js
Copy
import React from 'react'
import { useRouter } from 'next/router'

export default function  ExitPreviewButton({ children }) {
  const { isPreview } = useRouter()
  return (
    <div>
      {children}
      {isPreview ? (
        <a className="exit-button" href="/api/exit-preview">Exit Preview</a>
      ) : null}
      <style jsx>{`
      .exit-button {
        color: #fff;
        position: fixed;
        bottom: 0px;
        right: 60px;
        background-color: #262629;
        display: inline-flex;
        min-width: 120px;
        margin-right: 20px;
        margin-bottom: 20px;
        padding: 10px 20px;
        box-sizing: border-box;
        align-items: baseline;
        justify-content: center;
        font-size: 14px;
        line-height: 17px;
        font-weight: bolder;
        text-decoration: none;
        border: 1px solid #262629;
        border-radius: 4px;
        cursor: pointer;
      }
      `}</style>
    </div>
  )
}
Copy
import React from "react";
import Head from "next/head";
import Header from './Header'
import ExitPreviewButton from './ExitPreviewButton'

const Layout = ({ children, menu }) => {
  return (
    <div>
      <Head>
        <title> Prismic Next.js Multi Page Website </title>
      </Head>
      <Header menu={menu} />
      <main>{children}</main>
      <ExitPreviewButton />
    </div>
  );
};

export default Layout;

4. Add the toolbar / edit button script

The toolbar does multiple things for you, it will add an edit button to your website to quickly jump to the correct document in Prismic. It will show you a preview of the JSON response with Dev Mode. It will update the preview content when a change occurs and will allow you to clear the Prismic preview cookie.

To add the toolbar script for your repository go to the _document.js file in the directory at ~/pages/_document.js. Here we will import the API Endpoint from the sm.json file, extract the repo ID from this string using regular expressions and pass it to the toolbar script in the <head> component as a variable called prismicRepoName.

You can see the full code below:

Copy
import Document, { Html, Head, Main, NextScript } from "next/document";
import { createResolver } from "next-slicezone/resolver";

import { apiEndpoint } from "./../sm.json"; // import the endpoint name
const prismicRepoName = /([a-zA-Z0-9-]+)?(\.cdn)?\.prismic\.io/.exec(apiEndpoint)[1] //Regex to get repo ID

export default class extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    await createResolver();
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <script async defer src={`//static.cdn.prismic.io/prismic.js?repo=${prismicRepoName}&new=true`} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
};

5. Enable previews in your repository settings.

This is the final step to enable previews in your Prismic repository settings.

  1. Go to your repository, navigate to Settings > Previews and add the configuration for a preview.
  2. Enter the preview Site Name, Domain, and Link Resolver route. Add the /api/preview route for the Link Resolver field.
  3. You can add as many preview URL's as you need. This allows you to have a production server, staging server, development server, etc. Discover how to handle multiple environments in Prismic.
How your settings could look.

Now head over to your documents > enter a document > make a small change > save > click the eye icon to preview. It's that easy and now you can make as many content changes as you want with no cost. :)

You Can See the Full Process in the Video Below.


Congratulations!

Now that you can Preview your content changes you should have got some experience with using all the basic features of Slice Machine with Next.js.

You should also have a fully functioning website project which you can customize and build on top of. Below you'll find some suggested articles on what to learn next. I suggest starting to create some of your own unique Slices, once you've done this you can share them with us in the Prismic Community Forum or on Twitter with #PrismicSliceMachine.


Next and previous articles

Suggested Articles


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.