4
0

More than 3 years have passed since last update.

Next.jsとContentfulを連携する方法

Last updated at Posted at 2021-04-03

Next.jsとヘッドレスCMSのContentfulを連携する方法になります。

パッケージcontentfulをインストール

まずは、contentfulをインストールします。

npm install contentful
yarn add contentful

Contentfulのapiキーの設定をする

contentful.ts
const contentful = require('contentful')

const config = {
  space: process.env.CTF_SPACE_ID,
  accessToken: process.env.CTF_CDA_ACCESS_TOKEN
}

export const createClient = () => {
  return contentful.createClient(config)
}
env.local
CTF_SPACE_ID=YOUR ID
CTF_CDA_ACCESS_TOKEN=YOUR ACCESS TOKEN

contenfulの設定をします。space idやaccess tokenはContenfulのダッシュボードから確認することができます。

ES6 importでも使用できます。

contentful.ts
import * as contentful from 'contentful'
const config = {
  space: process.env.CTF_SPACE_ID,
  accessToken: process.env.CTF_CDA_ACCESS_TOKEN
}

export const createClient = () => {
  return contentful.createClient(config)
}

Contentfulからデータを取得する

Contentfulからデータを取得します。

posts.tsx

import React from 'react'
import { GetStaticProps } from 'next'
import { createClient } from '../library/contentful' // 上記で作成したcontentful.ts

const Posts = ({ posts }) => {
  return (
    <div>
      {posts &&
        posts.items.map((post) => (
          <div>
            <p>{post.fields.title}</p>
            <p>{post.fields.content}</p>
          </div>
        ))}
    </div>
  )
}

export default Posts

export const getStaticProps: GetStaticProps = async () => {
  const response = await getAllPosts()

  // responseが無ければ404にリダイレクトする
  if (!response) {
    return {
      notFound: true
    }
  }
  return {
    props: { posts: response }
  }
}

const getAllPosts = async () => {
  const client = createClient()
  try {
    const response = await client
      .getEntries({
        content_type: 'work',
        order: '-sys.createdAt'
      })
      .catch((error) => {
        return error
      })
    return response
  } catch(error) {
    throw new Error(error.message)
  }
}


上記の例では、Content Modeleがworkの物全て(記事一覧)を取得しています。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0