I have an issue with displaying an image for a blog post in my Next.js app. The blog page uses Contentful's model for the blog posts.
I have defined in my types.d.ts file the following:
import { Document } from '@contentful/rich-text-types';
export type BlogItem = {
fields: {
title: string;
slug: string;
date: Date;
content: Document;
image:{}. //left like this on purpose for now
author:string;
}
}
export type BlogItems = ReadonlyArray<BlogItem>;
export type BlogQueryResult = {
items: BlogItems;
}
In my blog/page.tsx the blog posts are fetched this way:
const getBlogEntries = async (): Promise<BlogQueryResult> => {
const entries = await client.getEntries({ content_type: "blog" });
return entries as unknown as BlogQueryResult; //unknown added because of a ts error
};
and then displayed in the return part with the following data:
export default async function Blog() {
const blogEntries = await getBlogEntries();
return(
...
{blogEntries.items.map((singlePost) => {
const { slug, title, date, image, author } = singlePost.fields;
console.log("Image field:")
console.log(singlePost.fields.image);
...
The above console log gives me this:
Image field:
{
metadata: { tags: [] },
sys: {
space: { sys: [Object] },
id: '6XUEKZLsv0hyfDCTEh2TJ7',
type: 'Asset',
createdAt: '2024-01-19T12:20:22.967Z',
updatedAt: '2024-01-19T12:20:22.967Z',
environment: { sys: [Object] },
revision: 1,
locale: 'en-US'
},
fields: {
title: 'Entrance to the Fushimi Inari Shrine',
description: '',
file: {
url: '//images.ctfassets.net/cjo7cuugyxv4/6XUEKZLsv0hyfDCTEh2TJ7/e8aa2b53361a2db3881bfaefb0f80688/Entr ance_to_the_Fushimi_Inari_Shrine',
details: [Object],
fileName: 'Entrance_to_the_Fushimi_Inari_Shrine',
contentType: 'image/jpeg'
}
}
}
Sorry for all the code posted and my way of describing things. I've tried changing the image field in the types file but everything results in "cannot read properties of undefined" error and browsing for solutions online I haven't been able to solve it. I also added the domain "images.ctfassets.net" in the next.config.js.
Any help is greatly appreciated, thanks in advance.
I tried changing the image field in a lot of ways and actually matching the format of the console log of the image field, where i was expecting to retrieve the image url from Contentful.
I have a hunch you're not adding
https:${image}.If you access your link directly in the response object, you'll see the image isn't available, however if you go to: https://images.ctfassets.net/cjo7cuugyxv4/6XUEKZLsv0hyfDCTEh2TJ7/e8aa2b53361a2db3881bfaefb0f80688/Entrance_to_the_Fushimi_Inari_Shrine
It is.