Gatsbyで記事に公開/非公開を設定できるようにする

September 16, 2023

Gatsbyで記事を公開、非公開できるようにしてみた。

ローカルで確認する場合は非公開の記事も表示し、本番にデプロイしたら公開の記事のみ表示されるようにしている。

環境

  • Gatsby v5.12
    • gatsby-starter-blogで生成したもの
  • Node.js v20.6.0
  • React v18.1.0

content/blog/xxxx/index.md

記事のFrontmatterにpublishedを追加し、公開したい記事は true、非公開にしたい記事はfalseにする

---
title: Gatsbyで記事に公開/非公開を設定できるようにする
date: "2023-09-16T19:15:00.000Z"
published: false
---

gatsby-node.js

Frontmatterに記事の公開/非公開を管理するpublischedBooleanとして追加する

createTypes(`
   ...
    type Frontmatter {
      title: String
      description: String
      date: Date @dateformat
      published: Boolean // ←追加
    }
   ...
  `)
}

Queryでfrontmatterを追加しpublishedを返すようにする

const result = await graphql(`
  {
     allMarkdownRemark(sort: { frontmatter: { date: ASC } }, limit: 1000) {
      nodes {
        id
        frontmatter { 
          title
          published
        }
        ...

あとはpublishedの状態に合わせて記事を生成するか決めればOK

if (posts.length > 0) {
  posts.forEach((post, index) => {
    // 本番環境でかつpublishedがfalseの場合は記事を生成しない
    if (process.env.NODE_ENV === "production" && !post.frontmatter.published) {
      return;
    }

src/pages/index.js

一覧ページに非公開記事のリンクを表示したくない場合は以下のようにする

{posts.map(post => {
  const title = post.frontmatter.title || post.fields.slug

  // ローカルでは一覧ページに非公開記事のリンクをつける
  if (process.env.NODE_ENV === "production" && !post.frontmatter.published) {
    return null;
} 

return(
  ...
)

Profile picture

Written by mofumofu3n Twitter Github