こんにちは、なおです。
Next.js13.4が安定版でリリースされましたね。
https://nextjs.org/blog/next-13
そんなわけで業務でもNext.jsは使用しているのでキャッチアップを進めていこうと思います。
ただローカル環境で動かしてもそこまで面白くないので今回は
microCMSと連携したブログを構築していきたいと思います。
まずはここから新規登録をしてAPIキーを取得
環境構築
ではやっていきます。
command npx create-next-app@latest Ok to proceed? (y) y ✔ What is your project named? … micro-cms ✔ Would you like to use TypeScript? … Yes ✔ Would you like to use ESLint? … Yes ✔ Would you like to use Tailwind CSS? … Yes ✔ Would you like to use `src/` directory? … No ✔ Would you like to use App Router? (recommended) … Yes ✔ Would you like to customize the default import alias? … Nocd micro-cms
npm run dev
これで以下の画面が表示されればOKです。
次にsdkをインストールします。
command
npm install microcms-js-sdk
プロジェクトのルートディレクトリに.env.localを作成し
APIキーとSERVICE_DOMAINを記述します。
.env.local
MICROCMS_SERVICE_DOMAIN=
MICROCMS_API_KEY=
次にルートディレクトリにlibsディレクトリを作成してその中に
microcms.tsを作成します。
microcms.ts
// libs/microcms.ts
import { createClient } from "microcms-js-sdk";
import type {
MicroCMSQueries,
MicroCMSImage,
MicroCMSDate,
} from "microcms-js-sdk";
//ブログの型定義
export type Blog = {
id: string;
title: string;
body: string;
eyecatch?: MicroCMSImage;
} & MicroCMSDate;
if (!process.env.MICROCMS_SERVICE_DOMAIN) {
throw new Error("MICROCMS_SERVICE_DOMAIN is required");
}
if (!process.env.MICROCMS_API_KEY) {
throw new Error("MICROCMS_API_KEY is required");
}
// API取得用のクライアントを作成
export const client = createClient({
serviceDomain: process.env.MICROCMS_SERVICE_DOMAIN,
apiKey: process.env.MICROCMS_API_KEY,
});
// ブログ一覧を取得
export const getList = async (queries?: MicroCMSQueries) => {
const listData = await client.getList<Blog>({
endpoint: "blog",
queries,
});
return listData;
};
// ブログの詳細を取得
export const getDetail = async (
contentId: string,
queries?: MicroCMSQueries
) => {
const detailData = await client.getListDetail<Blog>({
endpoint: "blog",
contentId,
queries,
});
return detailData;
};
以下の記述に関してはデータの取得が目視しやすいよう明示的に遅延効果を追加しています。
await new Promise((resolve) => setTimeout(resolve, 3000));
ページの作成
まずは記事一覧ページから作成します。
appディレクトリ以下にblogディレクトリを作成してその中に
page.tsxを作成します。
page.tsx
import Link from "next/link";
import { getList } from "../../libs/microcms";
export default async function StaticPage() {
const { contents } = await getList();
if (!contents || contents.length === 0) {
return <h1>No contents</h1>;
}
return (
<div>
<ul>
{contents.map((post) => {
return (
<li key={post.id}>
<Link href={`/blog/${post.id}`}>{post.title}</Link>
<p>{post.body}</p>
</li>
);
})}
</ul>
</div>
);
}
記事詳細ページ
import { notFound } from "next/navigation";
import parse from "html-react-parser";
import { getDetail, getList } from "../../../libs/microcms";
export async function generateStaticParams() {
const { contents } = await getList();
const paths = contents.map((post) => {
return {
postId: post.id,
};
});
return [...paths];
}
export default async function StaticDetailPage({
params: { postId },
}: {
params: { postId: string };
}) {
const post = await getDetail(postId);
if (!post) {
notFound();
}
return (
<div>
<h1>{post.title}</h1>
<div>{parse(post.body)}</div>
</div>
);
}
[/st-pre]
npm run buildにて一度ビルドしてから動作を確認します。
npm run build
npm run start
Vercelにデプロイ
自分のリポジトリに今作ったcmsアプリをpushしておきます。
その後Vercelにログインをしてリポジトリをクローンします。
次にSettings->Environment Variables->以下の値を設定すれば完成です。
MICROCMS_SERVICE_DOMAIN
MICROCMS_API_KEY