Next.js/microCMS/GithubActions/GithubPages で静的ブログを作る
2023-09-04T09:49:03.453Z
はじめに
コーポレートサイトやブログ等、動的コンテンツが一部しかない場合
サーバ管理の必要がなくヘッドレスCMSから内容を編集するだけでサイトに反映されるためエンジニアでない方でも運用が簡単になると思い、試してみました。
構成
・mainブランチのコードが変更された時
・microCMSのコンテンツが変更された時
にGithubActionsが実行され、出力された静的ファイル群がGithubPagesにデプロイされます。
開発環境
Node.js v18.16.1
next.js 13.4.10
※Node.jsはnodebrewを使用しローカルで開発しました。
アプリケーション
SSG対応
・next.config.jsにoutput項目を追加
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
}
module.exports = nextConfig
・Imageタグは使用しないため削除
.eslintrc.json
{
"extends": "next/core-web-vitals",
"rules": {
"@next/next/no-img-element": "off"
}
}
環境ファイルの作成
.envファイルを作成して、API _KEYとサービスポイントを記入
NEXT_PUBLIC_API_KEY=xxxxxxxxxxx
NEXT_PUBLIC_SERVICE_DOMAIN=xxxxxxxxxxx
ライブラリの追加
・@types/marked 5.0.1
・microcms-js-sdk 2.5.0
Github
レポジトリの作成
レポジトリ名を必ず[user].github.ioにしてください
Tokenの取得
microCMSにWebhookを設定するためのトークンを生成します。
https://github.com/settings/tokens
microCMS
microCMSのアカウントを無料枠で作成します
APIは無料枠で3つまで作成できますが、今回は1つの一覧用のAPIを作成して一覧と詳細機能が実装できます。
Webhookの設定
Githubで作成したトークンを入力して、microCMSで任意の操作を行った際にGithubActionsを実行するよう設定します。
環境変数の設定
レポジトリ内にAPI情報を持たせたくないので
microCMSで作成したAPIキーとサービスポイントを
・アプリケーションの.envファイル
・レポジトリの「Settings」→「Secrets and variables」→「Actions」
に保存します。
GithubActions
GithubPages
「Settings」→「Pages」のSource項目をGithubActionsに選択します。
theme項目はコードから自動的にNext.jsに判定されます。
nextjs.ymlに認証情報の追加
デフォルトで生成されているGithubActionsのyamlファイルをコミットする前に認証情報の項目を追記します。
またmicroCMSの動作に応じてGithubActionsが実行されるようにrepository_dispatchも追記します。
追記後、コミットするとビルドが走るようになります。
nextjs.yml
```yaml # Sample workflow for building and deploying a Next.js site to GitHub Pages # # To get started with Next.js see: https://nextjs.org/docs/getting-started # name: Deploy Next.js site to Pageson: repository_dispatch: types: [microCMSで命名したWebhook名]
Runs on pushes targeting the default branch
push: branches: ["main"]
Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions: contents: read pages: write id-token: write
Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency: group: "pages" cancel-in-progress: false
jobs:
Build job
build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Detect package manager id: detect-package-manager run: | if [ -f "${{ github.workspace }}/yarn.lock" ]; then echo "manager=yarn" >> $GITHUB_OUTPUT echo "command=install" >> $GITHUB_OUTPUT echo "runner=yarn" >> $GITHUB_OUTPUT exit 0 elif [ -f "${{ github.workspace }}/package.json" ]; then echo "manager=npm" >> $GITHUB_OUTPUT echo "command=ci" >> $GITHUB_OUTPUT echo "runner=npx --no-install" >> $GITHUB_OUTPUT exit 0 else echo "Unable to determine package manager" exit 1 fi - name: Setup Node uses: actions/setup-node@v3 with: node-version: "16" cache: ${{ steps.detect-package-manager.outputs.manager }} - name: Setup Pages uses: actions/configure-pages@v3 with: # Automatically inject basePath in your Next.js configuration file and disable # server side image optimization (https://nextjs.org/docs/api-reference/next/image#unoptimized). # # You may remove this line if you want to manage the configuration yourself. static_site_generator: next - name: Restore cache uses: actions/cache@v3 with: path: | .next/cache # Generate a new cache whenever packages or source files change. key: ${{ runner.os }}-nextjs-${{ hashFiles('/package-lock.json', '/yarn.lock') }}-${{ hashFiles('.[jt]s', '.[jt]sx') }} # If source files changed but packages didn't, rebuild from a prior cache. restore-keys: | ${{ runner.os }}-nextjs-${{ hashFiles('/package-lock.json', '/yarn.lock') }}- - name: Install dependencies run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }} - name: Build with Next.js run: ${{ steps.detect-package-manager.outputs.runner }} npm run build env: NEXT_PUBLIC_API_KEY: ${{ secrets.NEXT_PUBLIC_API_KEY }} NEXT_PUBLIC_SERVICE_DOMAIN: ${{ secrets.NEXT_PUBLIC_SERVICE_DOMAIN }} - name: Upload artifact uses: actions/upload-pages-artifact@v2 with: path: ./out
Deployment job
deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest needs: build steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v2
</details>
<a id="markdown-デプロイ" name="デプロイ"></a>
### デプロイ
デプロイに成功後[user].github.ioにアクセスするとサイトが表示されます。
<a id="markdown-microCMSからのデータ取得" name="microCMSからのデータ取得"></a>
### microCMSからのデータ取得
・/src/app/post/[id]/page.tsxにファイルを作成することでlocalhost:3000/post/****へのリクエストは全てこのファイルにルーティングされます。
・ビルド時に各記事のファイルを動的に生成するためにgenerateStaticParams関数を実装しています。
・microCMSの管理画面では記事の内容をマークダウンで記載できますがAPIで取得した際にHTMLに変換されてしまうので
マークダウンの文字列を保存しておき、markedというライブラリを使って文字列をマークダウンに変換して表示しています。
<details>
<summary>記事詳細画面</summary>
```javascript
import { createClient } from "microcms-js-sdk";
import { notFound } from "next/navigation";
import { marked } from 'marked';
import type {
MicroCMSQueries,
MicroCMSImage,
MicroCMSDate,
} from "microcms-js-sdk";
export const client = createClient({
serviceDomain: process.env.NEXT_PUBLIC_SERVICE_DOMAIN || "",
apiKey: process.env.NEXT_PUBLIC_API_KEY || "",
customFetch: (input, init) => {
if (typeof input === 'string') {
const newInput = new URL(input)
const time = new Date()
newInput.searchParams.set('cacheclearparam', `${time.getMinutes()}`)
return fetch(newInput.href, init)
}
return fetch(input, init)
},
});
//ブログの型定義
export type Blog = {
id: string;
title: string;
body: string;
markdown: string;
eyecatch?: MicroCMSImage;
} & MicroCMSDate;
// ブログ一覧を取得
export const getList = async (queries?: MicroCMSQueries) => {
const listData = await client.getList<Blog>({
endpoint: "blogs",
queries,
});
return listData;
};
export async function generateStaticParams() {
const posts = await getList();
return posts.contents.map((post:Blog) => ({
id: post.id,
}))
}
// ブログ詳細を取得
export const getObject = async (contentId: string, queries?: MicroCMSQueries) => {
const objectData = await client.get({
endpoint: "blogs",
contentId: contentId,
queries,
})
.then((res) => {
// console.log(res)
return res;
})
.catch((res) => {
return {
notFound: true,
};
});
return objectData;
};
export default async function Post({
params: { id },
}: {
params: { id: string };
}) {
const blog = await getObject(id);
if(blog.id == undefined) {
notFound();
}
return (
<main className="flex min-h-screen flex-col items-center justify-start p-6 w-full">
<div className="w-full place-items-center z-10 max-w-5xl justify-center font-mono flex">
<p className="text-2xl font-bold font-mono flex justify-center border-b border-gray-300 w-auto rounded-xl border bg-gray-200 p-4 dark:bg-zinc-800/30">
{blog.title}
</p>
</div>
<div className="flex flex-col items-center justify-start ">
<div className="mt-2">
<p>{blog.revisedAt}</p>
</div>
</div>
<div className="w-full sm:w-full md:w-5/6 lg:w-1/2">
<div className="prose">
<div className="py-5" dangerouslySetInnerHTML={{__html: marked(blog.markdown ?? "", {mangle:false})}}/>
</div>
</div>
</main>
);
};