13 Nov 2020·3 min read

Netlify CMS & Next.js Series - Custom Previews

#netlify #nextjs #headless-cms #react

We can now edit data using Netlify CMS, while its functional I'm sure you'll agree its not exactly pretty!

Default Preview

Lets add some Tailwind CSS to show a Navbar and a Hero section with a custom preview so it looks as if we're editing the actual page when we're in the CMS.

We'll end up with the slightly prettier:

Home Page

If we take a look at the new design in the CMS we'll see that admin preview is still not great.

Default Admin Preview

Let's change that so the admin preview looks like the actual rendered page.

Admin Page CSS

To style the Admin preview we need to reference the main site CSS from the Admin pages. We can generate a CSS file using the Tailwind command line tool.

Add a script to the package.json file so we can easily generate the CSS and hook it into the Netlify deploy process using the export command.

filename: package.json

"scripts": {
    "generate-admin-css": "npx tailwindcss build styles/tailwind.css -o public/admin/main.css",
    "export": "yarn generate-admin-css && yarn build && next export"

We can now easily generate this file using the command:

yarn generate-admin-css

Once the CSS file is generated we need to reference it in our Admin page.

filename: pages/admin.tsx

import("netlify-cms-app").then((CMS: any) => {

Preview Page

With the CSS is in place the final step we need a preview component for the Index page:

filename: components / admin / IndexPreview.tsx;

import React from 'react';
import Index from '../../pages';

export const IndexPreview = ({ entry }) => {
  const data = entry.getIn(['data']).toJS();

  if (data) {
    return <Index hero={data.hero} />;
  } else {
    return <div>Loading...</div>;

Finally add the preview component to the Admin page:

filename: pages/admin.tsx

import React from "react";
import dynamic from "next/dynamic";
import { IndexPreview } from "../components/admin/IndexPreview";

const AdminWithNoSSR = dynamic(
  () =>
    import("netlify-cms-app").then((CMS: any) => {
      **CMS.registerPreviewTemplate("index", IndexPreview);**
    }) as any,
  { ssr: false }

export default AdminWithNoSSR;

We should finally have a pretty live preview:

Live Preview