implementing image loading functionality in Next.js using TypeScript

I recently started working on building a website using NEXT.js with typescript. I have limited experience with typescript and currently facing an issue related to ImageLoader as cloudflare pages don't support the default image loader. However, I am unable to figure out why my code is not functioning properly.

Here is the snippet of my Loader code:

const normalizeSrc = (src: string) => {
  return src.startsWith("/") ? src.slice(1) : src;
};

const cloudflareLoader = ({
  src,
  width,
  quality,
}: {
  src: string;
  width: number;
  quality: number;
}) => {
  const params = [`width=${width}`];
  if (quality) {
    params.push(`quality=${quality}`);
  }

  const paramsString = params.join(".");
  return `/cdn-cgi/images/${paramsString}/${normalizeSrc(src)}`;
};

And here is how I'm implementing the Image:

<Image
  loader={cloudflareLoader}
  src="/images/image-name.png" // the image is located in the public/images folder
  height={120}
  width={120}
  alt=""
/>

The error message that I'm encountering is:

Type '({ src, width, quality, }: { src: string; width: number; quality: number; }) => string' is not assignable to type 'ImageLoader'.
  Types of parameters '__0' and 'p' are incompatible.
    Type 'ImageLoaderProps' is not assignable to type '{ src: string; width: number; quality: number; }'.
      Types of property 'quality' are incompatible.
        Type 'number | undefined' is not assignable to type 'number'.
          Type 'undefined' is not assignable to type 'number'.

Any suggestions or insights on what steps should I take to resolve this issue?

I found some helpful information at

Answer №1

Utilizing the type definition provided by next/image ensures that you are adhering to established types rather than creating your own, which enhances safety as it aligns with next's expectations.

To achieve this, follow these steps:

import type { ImageLoaderProps } from 'next/image';

export default function imageLoader({ src, width, quality }: ImageLoaderProps) {...}

Your code snippet would then look like this:

import type { ImageLoaderProps } from 'next/image';

const normalizeSrc = (src: string) => {
  return src.startsWith('/') ? src.slice(1) : src;
};

const cloudflareLoader = ({ src, width, quality }: ImageLoaderProps) => {
  const params = [`width=${width}`];
  if (quality) {
    params.push(`quality=${quality}`);
  }

  const paramsString = params.join('.');
  return `/cdn-cgi/images/${paramsString}/${normalizeSrc(src)}`;
};

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

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Error: A stream was expected, but instead you provided an object that is invalid. Acceptable options include an Observable, Promise, Array, or Iterable

I attempted to use map with a service call and encountered an error. After checking this post about 'subscribe is not defined in angular 2', I learned that for subscribing, we need to return from within the operators. Despite adding return statem ...

Session Timeout of 1 minute inactivity on OpenLiteSpeed with Next.js Application

Hello amazing Community. I've come across a perplexing issue while hosting my nextjs application with express using openlitespeed. Everything seems to be working smoothly in production, except for one thing - session authentication. The user is corre ...

Unexpected behavior when trying to catch errors in Node.js await block

After logging, my node process exited unexpectedly E callback: [Function: RP$callback], E { serviceName: '....', E errno: 'EAI_AGAIN', E name: 'RequestError', I had anticipated that the code below would handle ex ...

Error: Attempting to access the 'subscribe' property of an undefined value (Observable)

In my TypeScript/Angular2/SPFx project, I have the following code snippet: // Populate the regulatory documents dropdown this.regulatoryDocumentsService.fetchRegulatoryDocumentsData().subscribe( data => { this.regulatoryDocumentsData = data }, ...

Using the React Icon component as a prop in the Client Component within a NextJS application

Creating a dynamic button: 'use client'; import type { IconType } from 'react-icons'; interface ButtonProps { children: React.ReactNode; Icon: IconType; } export default function Button(props: ButtonProps) { const { children, ...

Error occurred when attempting to fetch data from a nested JSON object in React/Next.JS

Having trouble retrieving data from my API and encountering this error message. I suspect it may be related to the JSON structure. Interestingly, when using a different URL with nested arrays, it works fine. However, my current data is not cooperating. Any ...

Simpler method for organizing API route functions in NextJS

Currently, the majority of our API route handlers follow this structure (api/test.js): export default function handler(req, res) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } } ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Typescript - Stripping multiple characters from the start and end of a string/Retrieving attributes of a JSON list element

My challenge involves a string like the following : "{"element":"634634"}" My goal is to eliminate {"element":" which remains constant, as well as the final character "}. The only variable component is 634634. How can I achieve this? Alternatively, can ...

API data is being received, however, it is not being stored in the state

I am facing an issue while trying to update the state with data in a nested folder structure. -- using next.js view/src/app/page/WhyChoseUS.js 'use client'; import React, { useState, useEffect } from 'react'; import WhyChooseUsChild fro ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

If I exclusively utilize TypeScript with Node, is it possible to transpile it to ES6?

I am developing a new Node-based App where browser-compatibility is not a concern as it will only run on a Node-server. The code-base I am working with is in TypeScript. Within my tsconfig.json, I have set the following options for the compiler: { "inc ...

What is the TypeScript term for assigning multiple parameters an alias?

Imagine having a piece of code structured like this: export async function execute(conf: Record<string, string>, path: string, params: Array<string>) { const cmd = params[1]; const commandOption = params.slice(2) switch(cmd){ ...

Generating dynamically loaded components in Angular 2 with lazy loading

We are integrating an angular2 app into a cms (Sitecore) where content editors need the ability to add, remove, and rearrange components on a page, as well as include new components as needed. This is achieved by having the cms generate script tags to loa ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages │ └───Work │ │ index.vue │ │ [Work].vue Template <templat ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Reloading a Next.js website on an Apache server leads to a redirect back to the homepage

My Next.js website is statically hosted on an Apache server with a control panel. Initially, when I reloaded the page, it showed a 404 error. However, now every time I reload, it automatically goes to the homepage. I attempted to include a .htaccess file i ...

The presence of a method is triggering an Error TS2741 message stating that the property is missing in type

Here is a simplified code snippet that highlights the issue I am facing: class Test { prop1 : boolean prop2 : string method() { } static create(prop1 : boolean, prop2 : string) : Test { let item : Test = { prop1: prop1, prop2: pro ...

Error message encountered: The object contains unknown key(s): 'images' at "experimental" - Error in Next.js version 14.1.0

Currently, I am in the process of deploying my nextJs project on github pages and following a tutorial. I encountered an issue while trying to execute a pipeline in github, receiving an error message. Below is the code snippet from my next.config.mjs fil ...