next-images vs next-optimized-images
Handling Static Assets in Legacy Next.js Projects
next-imagesnext-optimized-images

Handling Static Assets in Legacy Next.js Projects

next-images and next-optimized-images are legacy webpack plugins designed to enable the importing of image files (like .jpg, .png, .svg) directly within JavaScript modules in Next.js applications. Before Next.js introduced its built-in Image component and native asset support, these packages were essential for treating images as module dependencies, allowing developers to import them as URLs or optimized data strings. While they solved critical workflow gaps in earlier versions of Next.js, both packages are now largely obsolete due to significant architectural changes in the framework itself.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
next-images094510.9 kB183 years agoMIT
next-optimized-images02,233-1316 years agoMIT

Handling Images in Legacy Next.js: next-images vs next-optimized-images

In the early days of Next.js (prior to version 10), the framework did not have built-in support for importing image files directly in JavaScript, nor did it offer an optimized image component. Developers relied on community plugins to bridge this gap. The two most prominent solutions were next-images and next-optimized-images. While both solved the problem of "how do I import a PNG in my React component?", they took very different approaches to performance and build configuration.

Today, both packages are considered deprecated for new projects. Next.js now includes native asset support and the highly advanced next/image component. However, understanding the differences between these legacy tools is crucial for maintaining older codebases or migrating them to modern standards.

📦 Core Philosophy: Simple Imports vs. Build-Time Optimization

The fundamental difference lies in what happens to your image during the build process.

next-images acts as a straightforward loader. Its primary goal is to make images importable so you get a URL string back. It focuses on compatibility and speed of configuration rather than altering the image file itself.

// next-images usage
// next.config.js
const withImages = require('next-images');
module.exports = withImages({
  // Minimal config, mostly just enables the loader
});

// component.js
import logo from '../assets/logo.png';

// Result: logo is a string like '/_next/static/media/logo.hash.png'
export default function Header() {
  return <img src={logo} alt="Logo" />;
}

next-optimized-images goes much further. It doesn't just load the file; it processes it. It uses tools like imagemin to compress images, resize them, and even convert them into different formats (like WebP) or inline small images as Base64 strings to reduce HTTP requests.

// next-optimized-images usage
// next.config.js
const withOptimizedImages = require('next-optimized-images');
module.exports = withOptimizedImages({
  optimizeImages: true,
  inlineImageLimit: 8192, // Inline images smaller than 8kb as Base64
  imagesName: '[name]-[hash].[ext]',
});

// component.js
import logo from '../assets/logo.png';

// Result: logo could be a URL OR a Base64 string depending on size
export default function Header() {
  return <img src={logo} alt="Logo" />;
}

⚙️ Configuration Complexity and Build Performance

One of the biggest trade-offs between these two packages is the impact on your build pipeline.

next-images is lightweight. It adds a standard webpack file loader to your configuration. It does not introduce heavy CPU tasks during the build. This means your development server starts quickly, and hot-reloading feels snappy.

// next-images config is minimal
const withImages = require('next-images');
module.exports = withImages();
// That's it. No complex options needed for basic usage.

next-optimized-images is heavy. Because it runs optimization algorithms on every image it touches, it can significantly slow down your build times, especially in large projects with hundreds of assets. It also requires installing peer dependencies (like imagemin, imagemin-mozjpeg, etc.) to actually function, adding friction to the setup process.

// next-optimized-images requires extensive config and peer deps
const withOptimizedImages = require('next-optimized-images');

module.exports = withOptimizedImages({
  // You must install separate packages for each optimization type
  optimizeImagesInDev: true, // Slows down dev mode significantly
  inlineImageLimit: 8192,
  handleImages: ['jpeg', 'png', 'webp', 'gif', 'svg'],
});

// Required peer dependencies to install separately:
// npm install --save-dev imagemin imagemin-mozjpeg imagemin-pngquant

🖼️ Handling Different Image Types

How these packages treat specific file types reveals their intended use cases.

next-images treats all supported files uniformly. Whether it is an SVG, a PNG, or a JPG, the result is always a public URL path. It does not attempt to inline small icons or convert formats.

// next-images: All result in URLs
import icon from './icon.svg';      // -> '/_next/static/.../icon.svg'
import photo from './photo.jpg';    // -> '/_next/static/.../photo.jpg'

// Developer must manually decide if an SVG should be a component or image

next-optimized-images offers smart handling based on file size and type. It can automatically inline small SVGs or PNGs as Base64 data URIs, removing the need for an extra network request. It can also generate multiple versions of an image if configured to do so.

// next-optimized-images: Smart inlining
import tinyIcon from './icon.svg'; 
// If < 8kb, tinyIcon might be "data:image/svg+xml;base64,PHN..."

import largePhoto from './hero.jpg';
// If > 8kb, largePhoto is a URL to an optimized JPG

🛑 Current Status and Migration Path

It is critical to understand that neither package is recommended for new projects.

Next.js introduced native support for static assets in version 10 and the next/image component shortly after. The native solution provides automatic image optimization, resizing, lazy loading, and layout shift prevention out of the box, without needing external webpack plugins.

If you are currently using either of these packages, you should plan a migration:

  1. Remove the plugin: Delete next-images or next-optimized-images from your next.config.js and package.json.
  2. Move assets: Place your images in the public/ directory.
  3. Update imports: Change your imports to use standard paths and switch to the Image component.
// ❌ Legacy Way (using next-optimized-images)
import hero from '../assets/hero.jpg';
<img src={hero} alt="Hero" />

// ✅ Modern Way (Native Next.js)
import Image from 'next/image';
// File lives in public/images/hero.jpg
<Image src="/images/hero.jpg" alt="Hero" width={800} height={600} />

📊 Summary Comparison

Featurenext-imagesnext-optimized-images
Primary GoalEnable simple importsOptimize and process images
Output TypeURL string onlyURL string or Base64 (inline)
Build SpeedFast (standard loader)Slow (heavy processing)
Config ComplexityLow (zero-config mostly)High (requires peer deps)
Image OptimizationNoneYes (compression, resizing)
StatusDeprecated / LegacyDeprecated / Legacy

💡 The Bottom Line

If you are maintaining an old Next.js application that hasn't been upgraded in years, your choice depends on your needs:

  • Use next-images if you just need things to work without slowing down your build. It is the "safe" legacy choice.
  • Use next-optimized-images if you absolutely cannot upgrade Next.js but need better performance scores due to image sizes. Be prepared for slower builds and complex dependency management.

However, for any greenfield project or modern codebase, do not install either. The built-in capabilities of Next.js today surpass what these plugins offered, with better developer experience and runtime performance.

How to Choose: next-images vs next-optimized-images

  • next-images:

    Choose next-images only if you are maintaining a legacy Next.js project (version 9 or older) that strictly requires simple URL imports for images and cannot be upgraded. Do not use this for any new development, as it lacks modern optimization features like automatic resizing, format conversion (WebP/AVIF), and lazy loading, which are now standard in the framework.

  • next-optimized-images:

    Choose next-optimized-images only if you are stuck on an older Next.js version but require build-time image optimization (compression, resizing) that next-images does not provide. Be aware that this package introduces significant build complexity and slower compilation times. For any modern project, avoid this entirely in favor of the native next/image component.

README for next-images

Next.js + Images

npm npm npm

Import images in Next.js (jpg, jpeg, png, svg, fig, ico, webp, jp2 and avif images by default).

Features

  • Load images from local computer
  • Load images from remote (CDN for example) by setting assetPrefix
  • Inline small images to Base64 for reducing http requests
  • Adds a content hash to the file name so images can get cached

If you also want image minimalization and optimization have a look at next-optimized-images

Installation

npm install --save next-images

or

yarn add next-images

Usage

Create a next.config.js in your project

// next.config.js
const withImages = require('next-images')
module.exports = withImages()

Optionally you can add your custom Next.js configuration as parameter

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  webpack(config, options) {
    return config
  }
})

And in your components or pages simply import your images:

export default () => <div>
  <img src={require('./my-image.jpg')} />
</div>

or

import img from './my-image.jpg'

export default () => <div>
  <img src={img} />
</div>

Options

assetPrefix

You can serve remote images by setting assetPrefix option.

Dynamic (runtime) asset prefixes are also supported, you can enable this feature by setting dynamicAssetPrefix to true.

Example usage:

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  assetPrefix: 'https://example.com',
  dynamicAssetPrefix: true,
  webpack(config, options) {
    return config
  }
})

InlineImageLimit

Inlines images with sizes below inlineImageLimit to Base64. Default value is 8192.

Example usage:

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  inlineImageLimit: 16384,
  webpack(config, options) {
    return config
  }
})

Exclude

Folders that you want to exclude from the loader. Useful for svg-react-loader for example.

Example usage:

// next.config.js
const path = require('path');
const withImages = require('next-images')
module.exports = withImages({
  exclude: path.resolve(__dirname, 'src/assets/svg'),
  webpack(config, options) {
    return config
  }
})

File Extensions

You have the power to specifiy the file extensions you'd like to pass to this loader configuration. This is helpful for adding image types that behave similarly, but are not included by default. It's also helpful in the same way that exclude is helpful, because you can exclude all SVGs (not just one from a specific folder).

TypeScript Users: If you exclude a file suffix, please note our shipped types declaration file will be incorrect. You'll want to use declaration merging or override dependencies for the same file suffixes as needed.

Please note: If you have issues with a file suffix not included in our default list (["jpg", "jpeg", "png", "svg", "gif", "ico", "webp", "jp2", "avif"]), we won't be able to guarantee bug support.

Example usage:

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  fileExtensions: ["jpg", "jpeg", "png", "gif"],
  webpack(config, options) {
    return config
  }
})

Name

You can change the structure of the generated file names by passing the name option:

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  name: "[name].[hash:base64:8].[ext]",
  webpack(config, options) {
    return config
  }
})

The default value is "[name]-[hash].[ext]". Documentation for available tokens like [name], [hash], etc can be found in webpack/loader-utils

ES Modules

By default, file-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

ES Modules are disabled by default. You can enable them by using esModule config option:

const withImages = require('next-images')
module.exports = withImages({
  esModule: true,
  webpack(config, options) {
    return config
  }
})

By enabling ES modules you should change your require statements and get default property out of them:

<img src={require("./img.png").default}>

import statement should be as before.

import img from "./img.png";

Typescript

Typescript doesn't know how interpret imported images. next-images package contains definitions for image modules, you need to add reference to next-images types into a type definition file, e.g. additional.d.ts, and then reference this from tsconfig.json.

// additional.d.ts
/// <reference types="next-images" />
// tsconfig.json
{
  ...
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "additional.d.ts"],
  ...
}

See the Next.js docs for more information.

With next/image

Base4/Data URL encoding is not supported when using the next/image component for image optimization. To deactivate inline images you can set the inlineImageLimit to false:

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
  inlineImageLimit: false
})

Bonus

Try out some of these awesome NextJS dashboard templates developed by Creative Team and support this project indirectly :)

https://www.creative-tim.com/product/nextjs-argon-dashboard-pro/?ref=next-images

https://www.creative-tim.com/product/nextjs-material-kit-pro/?ref=next-images

https://www.creative-tim.com/product/nextjs-material-kit/?ref=next-images