Watch our biggest AI launch event

Announcing Visual Copilot - Figma to production in half the time

Builder.io logo
Contact Sales
Contact Sales

Blog

Home

Resources

Blog

Forum

Github

Login

Signup

×

Visual CMS

Drag-and-drop visual editor and headless CMS for any tech stack

Theme Studio for Shopify

Build and optimize your Shopify-hosted storefront, no coding required

Resources

Blog

Get StartedLogin

‹ Back to blog

Creating a Blog

Create a drag-and-drop editable blog with Next.js

July 22, 2022

Written By Aziz Abbas

Creating your blog with Builder empowers your editors to build exciting blog articles in an intuitive drag-and-drop UI.

Setup

If you'd like to start with a pre-configured space and codebase, check out the full example on GitHub. This article goes through setting up a blog from scratch.

If you don't have one already, create an account over at builder.io/signup. It's free!

In this example we are also assuming you are a developer and will be connecting this blog to a custom website or app.

First, we need to make a model for our blog articles. Here's the how-to:

  1. Go to builder.io/models.
  2. Make a new model by clicking the + Create Model button and choosing Section.
  3. Name the model Blog article.
  4. Click the Create button.

5. Next, add some fields. Lots of blog posts usually include the following fields:

NameTypeNotes

Title

text

This is the article title when listing articles and for the page <title> tag for SEO; for example, "Announcing our new product line".

Handle

text

This is the URL handle; for example, new-product-line.

Image

file

This is the main image for the blog post—for example, when listing articles—as well as the og:image for previewing on social media sites like Facebook.

Date

timestamp

This is the date for displaying when this was posted and for filtering by date posted.

Blurb

text

Optional

This is the preview text when listing blog articles, and optionally can be the SEO meta description as well.

Author

reference

Optional

Use this to list info about authors. We recommend making a new data model—for example, with fields full name of type text and photo or type file—and using a reference type to reference the author for an article.

The following video shows how to add each of these fields to the model and specify each type. You can define the options of each field, such as default values or whether the field is required, to meet your particular needs. In practice, you might also want to fill in the Helper Text field so editors know the purpose of each field:

The image below shows a still screenshot of these fields in the Blog article model:

Tip: Consider marking some of those options, such as Title, Handle, Image, and Date required so the editor must enter those values to publish.

Now, you can query your Blog Articles using our Javascript SDK, Content API, or GraphQL API.

Displaying an article

Next, let's render an individual article.

Next.js Example

// pages/blog/[handle].jsx
import {
  builder,
  BuilderComponent,
  BuilderContent,
  useIsPreviewing,
} from "@builder.io/react";
import React from 'react';
import Head from "next/head";
import DefaultErrorPage from "next/error";

builder.init(YOUR_KEY);

function BlogArticle({ article }) {
  const isPreviewing = useIsPreviewing();
  if (!article && !isPreviewing) {
    return (
      <>
        <Head>
          <meta name="robots" content="noindex" />
        </Head>
        <DefaultErrorPage statusCode={404} />
      </>
    );
  }

  return (
    <BuilderContent
      content={article}
      options={{ includeRefs: true }}
      model="blog-article"
    >
      {(data, loading, fullContent) => (
        <React.Fragment>
          <Head>
            {/* Render meta tags from custom field */}
            <title>{data?.title}</title>
            <meta name="description" content={data?.blurb} />
            <meta name="og:image" content={data?.image} />
          </Head>

          <div>
            <div>{data?.title}</div>
            {/* Render the Builder drag/drop'd content */}
            <BuilderComponent
              name="blog-article"
              content={fullContent}
              options={{ includeRefs: true }}
            />
          </div>
        </React.Fragment>
      )}
    </BuilderContent>
  );
}

export async function getStaticProps({ params }) {
  const article = await builder
    .get("blog-article", {
      // Include references, like our `author` ref
      options: { includeRefs: true },
      query: {
        // Get the specific article by handle
        "data.handle": params.handle,
      },
    })
    .promise() || null;

  return {
    props: {
      article,
    },
    revalidate: 5,
  };
}

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: true,
  };
}

export default BlogArticle;

Tip: For more detailed instructions on integrating Builder with your site, check out Integrating Sections.

Searching for article

Builder.io API supports Mongodb style query of your data, for example to get a list of articles that has specific text in their title or description, you can do

import { builder } from '@builder.io/react';
export const search = (searchString) => builder.getAll('blog-article', {
  query: {
    '$or': [{
        'data.description': {
          $regex: `${searchString}`,
          $options: 'i'
        },
      },
      {
        'data.title': {
          $regex: `${searchString}`,
          $options: 'i'
        },
      },
    ]
  }
})

Once you get the code setup locally, let's connect your local site to the Visual Editor. This will allow for accurate previewing and editing as well as using your custom components directly in the editor.

  1. Go to Models.
  2. Open the Blog Article model.
  3. Click on the code icon, < > to the right of the Preview URL field. This opens a code editor with comments giving more context on this feature.
  1. Use the code below which tells the editor to show the page on the blog/[handle], then save model changes.
return `http://localhost:3000/blog/${content.data.handle || '_'}`

Tip: For more detailed instructions on using a preview URL, check out Editing and Previewing Your Site.

Now you can go to builder.io/content, click + New Entry and choose Blog Article. You should now see the drag and drop editor loaded right onto your local site.

You can now create articles with drag-and-drop and publish them when you're ready.

To create a blog article content entry, do this:

  1. Go to Content where you should see the Blog article model in the list on the left.
  2. Click the + New button and select Blog article. The recommended fields we added in the first section of the tutorial are in the Options tab, ready for you to fill out.
  3. Add some content and publish!

When you publish your site updates to production, make sure to update your editing URL to be a production URL, such as https://your-site.com/blog/_ and no longer localhost so other team members can create blog posts.

We've showed several key features here such as custom models, custom fields, and connecting to your website

If you have any questions, ask in our forum!

Share

Twitter
LinkedIn
Facebook
Hand written text that says "A drag and drop headless CMS?"

Introducing Visual Copilot:

A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot
Newsletter

Like our content?

Join Our Newsletter

Continue Reading
AI5 MIN
Introducing Visual Copilot 2.0: Design to Interactive
October 31, 2024
Design Systems8 MIN
Design Systems Explained
October 18, 2024
Visual Editing7 MIN
Visual editing is bridging the gap between developers and designers
October 11, 2024