next js image contentful

Next.js Image with Contentful

If you are building a website using Next.js and require a CMS to manage your content, Contentful can be a good option. In this case, you may want to use Next.js Image component to optimize images for the web. Here's how to use Next.js Image with Contentful.

Step 1: Install Dependencies

You need to install three packages: next, react, and react-dom.


npm install next react react-dom

Step 2: Set Up Contentful

You need to create a Contentful account and set up a space for your content. You also need to create a Content Model for the content you want to manage. Here's an example of a Content Model for a blog post:


{
  "name": "Blog Post",
  "description": "",
  "displayField": "title",
  "fields": [
    {
      "name": "Title",
      "id": "title",
      "type": "Symbol",
      "required": true
    },
    {
      "name": "Body",
      "id": "body",
      "type": "RichText",
      "required": true
    },
    {
      "name": "Image",
      "id": "image",
      "type": "Link",
      "linkType": "Asset"
    }
  ]
}

Step 3: Query Contentful API

You can query the Contentful API using the contentful package. Here's an example of how to query a blog post with its image:


import { createClient } from 'contentful';

const client = createClient({
  space: '',
  accessToken: ''
});

export async function getBlogPost(slug) {
  const entries = await client.getEntries({
    content_type: 'blogPost',
    'fields.slug': slug,
    include: 1
  });

  if (entries.items.length > 0) {
    const post = entries.items[0].fields;
    const image = post.image.fields;

    return {
      title: post.title,
      body: post.body,
      imageUrl: 'https:' + image.file.url,
      imageAlt: image.title
    };
  } else {
    return null;
  }
}

Step 4: Use Next.js Image Component

Finally, you can use the Next.js Image component to display the optimized image. Here's an example of how to use it:


import Image from 'next/image';

export default function BlogPost({ title, body, imageUrl, imageAlt }) {
  return (
    <div>
      <h1>{title}</h1>
      <Image src={imageUrl} alt={imageAlt} width={600} height={400} />
      <div dangerouslySetInnerHTML={{ __html: body }} />
    </div>
  );
}

Note that you need to pass the width and height props to the Image component to specify the size of the image on the page.

That's it! You can now use Next.js Image with Contentful to optimize your images for the web.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe