Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How to import SASS in Next.js ?
Next article icon

How to import image in Next.js ?

Last Updated : 05 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Next.js is a full-stack React-based framework. Unlike a traditional react app, which loads and renders the entire application on the client, Next.js allows the first-page load to be rendered by the server, which is great for SEO and performance.

Some of the key features of Next.js are: 

  • Server-side rendering
  • Image optimization
  • Static Site generation
  • Incremental Site regeneration.

You can learn more about Next.js here. In this article, we will learn to import images in Next.js using the Image component.

Image component in Next.js (next/image): Next.js Image component is an evolved form of <img/> element in HTML. It comes built-in with performance optimization which helps in achieving good Core web vitals. This performance boost is factored in Google’s ranking algorithm, hence improving the ranking of our website.

The Image component supports the following built-in optimizations: 

  1. Improved Performance: It serves different image sizes for each device, which reduces image size for smaller devices and thus improves performance.
  2. Faster Page Loads: Images are not loaded until they enter the viewport, hence enabling the web page to load faster.
  3. Asset Flexibility: It supports various configurations such as resizing the Image component via props.
  4. Visual Stability: It automatically prevents Cumulative Layout Shift, which is a layout error that occurs when elements get shifted after being rendered by DOM. It determines the overall stability of our website’s layout

Properties of Image Component: The image components support the following props: 

  • src (required): This property accepts a path string, an external URL, or a locally imported image.
  • width (required): It represents the image’s rendered or original width in pixels. For locally imported images, this property is optional.
  • height (required): It represents the rendered height or the image’s original height in pixels. For locally imported images, this property is optional.
  • layout: It determines the behavior of the image size when the viewport width changes. It supports the following values: 
    • intrinsic: It is the default behavior, which scales the image down to the width of the container, up to the image size.
    • fixed: It keeps the image fixed to the given width and height.
    • responsive: It scales the image to fit the container’s dimensions.
    • fill: It causes the image to fill the container. It also makes the width and height properties optional because the container will determine them.
    • raw: It allows the image to be rendered without any automatic behavior.

Working with Image component: Run the following command to create a new Next.js project.

npx create-next-app@latest gfg

Project Structure: 

 

For the scope of this article, we will only focus on the public and pages directory. The public directory contains all the static files that need to be served when the Next.js app is built for deployment. 

In this example, we’ll create and add three images with different sources, one will be imported from the public directory, the second image will be served through the static path from the public directory and the other one will be served from an external URL. You can add your image to the public directory (Here we’ve added gfgLogo.png). And for the external URL, we’re using this image, but for the external URL to work, we’ll have to add its domain name to the next.config.js file to protect our application from malicious users.

We’ll first clean up some boilerplate code in the pages/index.js (Home Page) and import the Image component. 

pages/index.js

import Image from "next/image";
  
const HomePage = () => {
    return (
        <>
            {/* This is a local import, so the 
            height and width props are optional */}
            <div>
                <Image src={gfgLogo} 
                    alt="GFG logo imported from public directory" />
            </div>
  
            {/* This image is also served from public 
            directory but using the static path */}
            <div>
                <Image
                    src="
https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png"
                    alt="GFG logo served with static path of public directory"
                    height="100"
                    width="400"
                />
            </div>
  
            {/* This image is being served from an 
            external URL, for this URL to work we 
            will need to add the hostname 
            'media.geeksforgeeks.org' to our 
            next.config.js file */}
            <div>
                <Image
                    src="
https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png"
                    height="100"
                    width="400"
                    alt="GFG logo served from external URL"
                />
            </div>
        </>
    );
};
  
export default HomePage;
                      
                       

/next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images : {
    domains : ['media.geeksforgeeks.org']
  }
}
  
module.exports = nextConfig
                      
                       

Step to run the application: Run your Next app using the following command:

npm run dev

Output: 

 



Next Article
How to import SASS in Next.js ?
author
ksangtiani13
Improve
Article Tags :
  • ReactJS
  • Web Technologies
  • Next.js

Similar Reads

  • How to import SASS in Next.js ?
    Sass is the short form of Syntactically Awesome Style Sheet. It is an upgrade to Cascading Style Sheets (CSS). Sass is a CSS pre-processor. It is fully compatible with every version of CSS. Importing SASS in Next.js allows you to use SCSS for styling your application. This integration enables advanc
    2 min read
  • How to ignore ESLint in Next.js ?
    In this article, we are going to see how to ignore ESLint in Next.Js. Follow the below steps to ignore ESLint in the Next.js application: ESLint: ESLint is a JavaScript linter that is designed to help identify and correct problems in JavaScript code. ESLint is based on JSHint, but ESLint has more fe
    2 min read
  • How to add Image Carousel in Next.js ?
    In this article, we are going to learn how we can add an Image Carousel in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. ApproachTo create image carousel in next.js we are going to use a react-r
    2 min read
  • How to Import SVGs Into Your Next.js Apps?
    Next.js is a powerful React framework that simplifies building and deploying web applications. Incorporating SVGs (Scalable Vector Graphics) into your Next.js projects can enhance your user interface with high-quality, scalable images. In this article, we will see how to Import SVGs Into Your Next.j
    5 min read
  • How To Use An ES6 Import In Node.js?
    To use an ES6 import in Node.js, you need to make some configurations to support ES6 modules. While Node.js was originally built around the CommonJS module system (require() and module.exports), modern JavaScript development prefers using the ES6 module syntax (import and export). Node.js now suppor
    4 min read
  • How to Add a Background Image in Next.js?
    Next.js is a powerful React framework that allows for server-side rendering and the generation of static websites. Adding a background image to your Next.js application can enhance the visual appeal of your web pages. This article will guide you through the process of adding a background image to a
    3 min read
  • How to use imgur to host images in ReactsJS ?
    Imgur is primarily used as an image-sharing service, where users post content through an interface provided by the company, just like Facebook or Instagram. But we can also post images to Imgur by accessing their APIs. So, in this article, we will discuss how to upload images to Imgur in React witho
    2 min read
  • How to add Tag Input in Next.js ?
    In this article, we are going to learn how we can add Tag input in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. Approach: To add our tag input, we are going to use the react-tag-input-component
    2 min read
  • How to Set Port in NextJs?
    Setting a custom port in Next.js is essential when you want to run your development or production server on a port other than the default (3000). While Next.js doesn't directly support port configuration via .env.local for development, you can control the port using alternative methods. This article
    3 min read
  • ImageResponse Next.js
    ImageResponse is a powerful feature that allows you to generate images dynamically on the server side using JSX and CSS. To use an ImageResponse function, you need to import it from "next/og". It uses Vercel's open graph library to generate dynamic images. The ImageResponse constructor, by allowing
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences