Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on GitHub: https://github.com/GabrielPedroza/e-commerce/blob/main/components/Product.tsx

<Image src={urlFor(image && image[0]!)} />

import imageUrlBuilder from "@sanity/image-url"
import { SanityImageSource } from "@sanity/image-url/lib/types/types"

export const client = sanityClient({
    projectId: "gz95qrem",
    dataset: "production",
    apiVersion: "2022-04-27",
    useCdn: true,
    token: process.env.NEXT_PUBLIC_SANITY_TOKEN, // for security purposes
})

const builder = imageUrlBuilder(client)

export const urlFor = (source: SanityImageSource) => {
    return builder.image(source)
} 
Type 'ImageUrlBuilder' is not assignable to type 'string | StaticImport'.
  Property 'src' is missing in type 'ImageUrlBuilder' but required in type 'StaticImageData'.ts(2322)
image.d.ts(19, 5): 'src' is declared here.
image.d.ts(29, 5): The expected type comes from property 'src' which is declared here on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "ref" | ... 4 more ... | "loading"> & { ...; }'

Server Error
Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {}
Call Stack
Image
node_modules/next/dist/client/image.js (160:18)
renderWithHooks
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5448:16)
renderIndeterminateComponent
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5521:15)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5736:7)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)
renderHostElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5433:3)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5742:5)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)

I have tried using a string or using ts-ignore to remove the error, but this approach doesn't work for me as I'm utilizing Sanity. As a temporary workaround, I have resorted to using the regular img tag with a ts-ignore to make it function. I have sought help in the official Next discord server and searched through documentation, but unfortunately, I haven't found a solution yet.

Answer №1

I encountered a similar issue...

The workaround I found was to include the following line before calling the src Image:

src={urlFor(image).url()};

Additionally, in my schema files, I updated the type of "image" to "SanityImageSource"

Best regards!

Answer №2

Discovered a clever fix:

const source = generateUrl(image && image[0]).url()

<div style="position: relative;">
    <Image loader={() => source} src={source} layout='fill' />
</div>
`` Wrap the Image component in a div tag and ensure it has `position: relative;` so that layout='fill' can function correctly for creating responsive images

Answer №3

My current setup involves using Next13 and sanity.io for pulling images, with deployment on Vercel. Special thanks to @javiRelax for the helpful hint that made it all come together. This is how I've implemented it:

     {Images.map((array, index) => {         
        return(           
          <Image
          src={urlFor(array.imgUrl).url()}
          alt={array.alt}
          key={index}
          width="100"
          height="100"
          unoptimized={true} 
          />
        );
      })}
              

After encountering some issues, I found that adding

unoptimized={true}

was necessary for the functionality to work as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simplifying parameter types for error handling in app.use callback with Express.js and TypeScript

With some familiarity with TypeScript but a newcomer to Express.js, I aim to develop a generic error handler for my Express.js app built in TypeScript. The code snippet below is functional in JavaScript: // catch 404 and forward to error handler app.use((r ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

Is it possible to utilize a global variable in place of a React.Context for transmitting constant props in this scenario?

I am considering the drawbacks of using a globally shared variable instead of a Context in my specific scenario: This variable will only be set once during the initial rendering It will not change throughout the runtime The variable is needed in multiple ...

Personalized Shade Selection for Papyrus

Is there a method to specifically alter the color of the box-shadow for the mui Paper component? I have a black background, making the shadow not visible. I've tried createMuiTheme({ overrides: { MuiPaper: { root: { boxShadow: & ...

an image loader for nextjs that reveals a vibrant color before transitioning into the full image显示颜

Is there a way to display a color (black) while an image is loading and then smoothly transition to the image once it's loaded? import Image from 'next/image' const customLoader = ({ src, width, quality }) => { return `https://example. ...

"Encountering a 500 Internal Server Error with NextJS next-auth while attempting to log in on Netlify platform

I am facing an issue when attempting to log in with next-auth. I receive a 500 error from /api/auth/providers and the message "Internal Server Error" is the only thing displayed on the screen. This process works perfectly fine locally, but not in the produ ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

I am unable to loop through and display the buttons

I have a button object within my component that I want to iterate through and display all the buttons {0: {…}, 1: {…}, isActive: true} 0: {key: ':R2m:', text: 'Trading', isActive: true} 1: {key: ':R2mH1:', text: 'Ba ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

What is the reason behind the avoidance of using sequential numbers for storing images?

I've noticed that platforms like Instagram and Facebook use long strings to name their images (e.g. instagram/p/BB-cCvtje4k). Is there any downside to naming pictures as thisuser/1, thisuser/2, and so on? Is it considered poor practice in server-side ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

What is the rationale behind TypeScript's decision to implement two checks for its optional chaining and null-coalescing operators during compilation?

What is the reason behind the way the TypeScript compiler translates its optional chaining and null-coalescing operators, found here, from: // x?.y x === null || x === void 0 ? void 0 : x.y; // x ?? y x !== null && x !== void 0 ? x : y as opposed ...

What causes material-ui styling to flicker while moving between pages in Next.js?

Visit this link for more information Experience a unique button styling transition when moving from one page to another. Check out the code snippet here: Explore the code on GitHub ...

Tips for initializing constructor arguments using JSON during object instantiation in TypeScript

Let's consider a scenario where we have the following class: export class PersonInformation { constructor( public firstName: string = "", public lastName: string = "", public middleName: string = "", ) { } } Now, we&a ...

Using next.js with GraphQL resulted in the following error: "Invariant Violation: Unable to locate the "client" in the context or passed in as an option..."

I've searched extensively online, but I can't find a solution to my problem. Here is the error message I'm encountering: Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an ...

Having trouble getting Firestore/Firebase to work with Next.js?

Hey everyone, I could really use some help here. I've been working on integrating Firebase into my Next.js app for the API. Everything works well when I build and run locally, but once I deploy to Vercel for production, I encounter a 500 - Internal S ...

What is the best way to create a case-insensitive sorting key in ag-grid?

While working with grids, I've noticed that the sorting is case-sensitive. Is there a way to change this behavior? Here's a snippet of my code: columnDefs = [ { headerName: 'Id', field: 'id', sort: 'asc', sortabl ...

What is the most efficient method for line wrapping in the react className attribute while utilizing Tailwind CSS with minimal impact on performance?

Is there a more efficient way to structure the className attribute when utilizing tailwind css? Which of the examples provided would have the least impact on performance? If I were to use an array for the classes and then join them together as shown in e ...