generateImageMetadata Next.js (original) (raw)

Last Updated : 15 Jul, 2024

Next.js is a powerful React framework that helps developers build fast, user-friendly web applications. One of the advanced features it offers is**generateImageMetadata**, which helps in generating and optimizing metadata for images in your Next.js applications. This feature is important for improving SEO and ensuring your images load quickly and efficiently.

Syntax

The generateImageMetadata function is typically used within the Next.js configuration or in a custom server setup.

import { generateImageMetadata } from 'next/image-metadata';

const metadata = generateImageMetadata(imagePath, options);

Parameters

Options Object

Returns

The generateImageMetadata function returns an object containing the following properties:

Uses of generateImageMetadata

Steps to Create the Project

Step 1. Create Next.js Project

Use Create Next App to establish a new Next.js project named my-image-project.

npx create-next-app my-image-project

Note : Select **Page Router instead of App Router ( by defualt )

Step 2. Navigate to the Project Directory

cd my-image-project

Project Structure

Screenshot-2024-06-20-221229

project struture used page router

Dependencies

dependencies :
{
"react": "^18",
"react-dom": "^18",
"next": "14.2.4"
}

**Example: Illustration to design a generateImageMetadata App with Next.

// utils/generateImageMetadata.js export const generateImageMetadata = () => { return [ { id: 1, alt: "Small example image", size: "small", width: 100, height: 100 }, { id: 2, alt: "Medium example image", size: "medium", width: 200, height: 200 }, { id: 3, alt: "Large example image", size: "large", width: 300, height: 300 } ]; };

JavaScript

// components/ImageWithVariations.js import React from 'react';

const ImageWithVariations = ({ metadata }) => { return (

{metadata.map((data) => ( {data.alt} ))}
); };

export default ImageWithVariations;

JavaScript

// pages/index.js import React from 'react'; import { generateImageMetadata } from '../utils/generateImageMetadata'; import ImageWithVariations from '../components/ImageWithVariations';

const HomePage = () => { const metadata = generateImageMetadata();

return (

Image Variations

); };

export default HomePage;

`

**Step to Run Application: Run the application using the following command from the root directory of the project

npm run dev

**Output: Your project will be shown in the URL http://localhost:3000/

Screenshot-2024-07-08-100858

image varies size due to different metadata