Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk8 min

How to Optimize Images in Next.js with next/image and Custom Loaders

A practical guide to responsive next/image layouts, custom loader setup, remote images, format and cache behavior, and image loading priorities.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Next.js’s built-in image optimizer unless you have a specific reason to delegate transformations to an external service. In either case, give each image its real layout dimensions, set an accurate sizes value for responsive layouts, and reserve preloading for a known above-the-fold LCP image. A custom loader only builds the image URL; the provider still has to perform and serve the requested transformations.

Image behavior and configuration can change between Next.js versions, so check the Image component and configuration references for the version installed in your project.

As an Amazon Associate I earn from qualifying purchases.

Start with layout: dimensions, sizes, and fill

For a fixed-size image, provide its intrinsic width and height. These values describe the image’s aspect ratio and let the browser reserve space while it loads; they do not dictate its final CSS-rendered size. Next.js explains that the attributes help infer the aspect ratio and avoid layout shift (Next.js Image Component documentation).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import Image from 'next/image'

export default function ArticleImage() {
  return (
    <Image
      src="/images/feature.jpg"
      alt="A person working at a desk beside a window"
      width={1200}
      height={800}
      sizes="(max-width: 700px) 100vw, 700px"
      style={{ width: '100%', height: 'auto' }}
    />
  )
}

Write sizes to describe the image’s expected rendered width at the breakpoints in your actual CSS. The example says the image takes the full viewport width up to 700 pixels, then occupies a maximum 700 pixels. Change those conditions and values to match your layout; they are not universal defaults. The browser uses sizes to choose a suitable candidate from the responsive srcset. Without it, a responsive image can be treated as viewport-wide, causing a larger download than its rendered layout requires. See the Pages Router Image reference for the responsive-image behavior.

#1 Best Overall
Lavsoul 4K Webcam with Microphone for PC & Streaming Computer Camera
  • ULTRA HD 4K CLARITY: Stand out in every video call with breathtaking 4K video at 30fps or smooth 1080p at 60fps. Powered by a premium 1/2.5" CMOS sensor and a wide f/1.78 aperture, this webcam captures every detail with vibrant color and stunning low-light performance-so you always look your best
  • FAST AUTOFOCUS & SMART LIGHT CORRECTION: No more blurry moments with this webcam for PC. Advanced Phase Detection Auto Focus (PDAF) locks onto your face instantly and keeps you sharp-even when you move. Built-in light correction adapts to your environment, balancing brightness and contrast for a flawless image in dim rooms or bright spaces
  • DUAL NOISE-CANCELING MICS: Speak with confidence using this webcam with microphones. Dual microphones with intelligent noise-canceling tech isolate your voice and reduce background noise-suitable for webinars, live streams, team meetings, and virtual interviews
  • WIDE-ANGLE LENS & FLEXIBLE MOUNTING OPTIONS: Capture more of your world with an 80 field of view and full 360 swivel rotation. Whether this streaming webcam is mounted on a laptop, monitor, or tripod, it allows you to find the right angle for any setup
  • BUILT-IN PRIVACY COVER & PLUG-AND-PLAY SIMPLICITY: Protect your privacy with a secure sliding lens cover that blocks the camera when not in use. Setup is a breeze-just plug into any USB-A port and start streaming, chatting, or recording instantly. The USB webcam is compatible with Zoom, Microsoft Teams, Skype, OBS Studio, and all major platforms across Windows, macOS, and Linux

Using fill for a responsive box

With fill, the image occupies its positioned parent rather than taking its dimensions from width and height props. Establish the parent’s positioning and dimensions, then choose whether the image should crop or fit inside the box.

<div className="hero">
  <Image
    src="/images/hero.jpg"
    alt="A city skyline at sunset"
    fill
    sizes="(max-width: 768px) 100vw, 50vw"
    style={{ objectFit: 'cover' }}
  />
</div>
.hero {
  position: relative;
  min-height: 18rem;
}

Here, cover fills the box and can crop the image; use contain when the complete image must remain visible, accepting that unused space may remain. The sample sizes is illustrative: align its breakpoint and width fractions with the real CSS layout.

How do I use a custom loader with next/image?

A loader is a URL-building function. Next.js passes it the source, the requested width, and optionally quality; the function returns a URL in the syntax expected by your image optimization service. The function does not itself resize an image or configure the provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure a loader for one Image

import Image from 'next/image'

function imageLoader({ src, width, quality }) {
  return makeProviderUrl({
    src,
    width,
    quality: quality ?? 75,
  })
}

export default function ProductImage() {
  return (
    <Image
      loader={imageLoader}
      src="https://images.example.com/products/item.jpg"
      alt="Blue ceramic mug"
      width={900}
      height={900}
      sizes="(max-width: 600px) 100vw, 300px"
    />
  )
}

makeProviderUrl above is deliberately provider-specific pseudocode, not a complete integration: replace it with the provider’s documented URL construction. The quality fallback of 75 follows the official loader example; confirm accepted quality values and width behavior with your provider.

Rank #2
10.1 Inch Mini Netbook, Quad-Core Processor Laptop Computer, 2GB Memory 64GB Storage Android 12 Portable Notebook Built-in Webcam, WiFi & Bluetooth Keyboard & Mouse for Home Schooling & Office Work
  • 【Efficient Quad-Core Performance】 Powered by a 1.8GHz Quad-Core processor, this mini laptop ensures smooth multitasking. With 2GB RAM and 64GB ROM (expandable to 1TB), it handles daily work and online tasks with ease.
  • 【10.1" HD IPS Display & GMS Support】 Featuring a 1280x800 HD IPS screen, this cheap laptop delivers vibrant visuals. Pre-installed with Android OS and GMS, you get direct access to the Google Play Store for apps.
  • 【Ultra-Portable & Lightweight Design】 Weighing only 1.76 lbs, this Blue computer is designed for mobility. Its compact form makes it an ideal companion for students and professionals for home schooling or trips.
  • 【Versatile Connectivity Options】 Stay productive with dual USB 2.0 ports, a headphone jack, and a TF card slot. This computer for kids and adults features built-in Wi-Fi and Bluetooth for stable connections.
  • 【Complete All-in-One Bundle】 This kid laptop kit includes the laptop, carrying bag, mouse, mouse pad, and power adapter. It is the perfect ready-to-use set for online classes, remote work, and entertainment.

Configure a loader for the project

For app-wide behavior, set loader: 'custom' and loaderFile in next.config.js. The loader file path is relative to the project root and the file exports a default function.

// next.config.js
module.exports = {
  images: {
    loader: 'custom',
    loaderFile: './src/lib/image-loader.js',
  },
}
// src/lib/image-loader.js
export default function imageLoader({ src, width, quality }) {
  return makeProviderUrl({ src, width, quality: quality ?? 75 })
}

Use the module syntax appropriate to your project’s configuration setup. The supported options and file handling are documented in the Image component reference and image configuration reference.

Validate the provider integration

Before deploying, verify that the returned URL correctly encodes the source and requests a transformation the provider supports. Check allowed source hosts, width and quality constraints, format negotiation, and the provider’s cache and invalidation behavior. A custom loader controls URL generation; it does not prove that the external service is reachable, configured, compatible, or affordable for your traffic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Built-in optimization or an external image service?

The default loader uses Next.js’s Image Optimization API. A custom loader is the documented path when you want an external image optimization service or image CDN to generate transformed image URLs. The right choice depends on your deployment and source-image requirements, as well as provider-specific behavior; Next.js does not determine a third-party service’s price, transformations, or cache policy.

Rank #3
Sale
Logitech C920x HD Pro Webcam, Full HD 1080p/30fps - Black w/Blue Yeti USB Microphone - Blackout
  • Webcam comes with a 3-month XSplit VCam license and no privacy shutter. XSplit VCam lets you remove, replace and blur your background without a Green Screen.
  • Full HD 1080p video calling and recording at 30 fps - You’ll make a strong impression when it counts with crisp, clearly detailed and vibrantly colored video.
  • Stereo audio with dual mics - Capture natural sound on calls and recorded videos.
  • Custom three-capsule array: This professional USB mic produces clear, powerful, broadcast-quality sound for YouTube videos, Twitch game streaming, podcasting, Zoom meetings, music recording and more
  • Blue VOICE software: Elevate your streamings and recordings with clear broadcast vocal sound and entertain your audience with enhanced effects, advanced modulation and HD audio samples
Decision area Built-in Next.js optimizer Custom loader and external service
Transformation control Uses the Next.js image optimization API and its configuration. URL parameters and transformations depend on the provider.
Hosting fit Uses the Next.js deployment’s image optimization setup. Depends on the chosen service and how it is hosted or reached.
Remote-source access Remote URLs must satisfy configured remotePatterns; source authentication headers are not forwarded. Depends on the provider’s source-access model and your URL construction.
Widths and quality Use the widths and quality settings supported by the installed Next.js version and configuration. Must match the provider’s accepted parameters and limits.
Format negotiation Configured formats are negotiated using the request’s Accept header. Depends on provider behavior and the URLs your loader generates.
Cache and invalidation Uses the built-in optimizer’s cache behavior; it has no cache invalidation mechanism. Cache duration and invalidation depend on the service.
Operational responsibility Runs through the Next.js image optimization path. Requires an available, correctly configured external service.

Use the default when its deployment, source access, formats, and cache behavior meet your needs. Consider a custom loader when an external service is already part of your delivery architecture or its transformations are required. The Next.js loader documentation describes the external cloud-provider loader approach.

How do I use a remote image with next/image?

When the built-in optimizer fetches a remote image, allow only the sources your application expects. Configure remotePatterns with the intended protocol, hostname, path, and search-string policy. Avoid broad patterns: they can authorize URLs beyond the source set you meant to permit.

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.example.com',
        port: '',
        pathname: '/products/**',
        search: '',
      },
    ],
  },
}

Use the pattern syntax supported by your installed Next.js version. The example permits HTTPS images under the specified path and no query string; adjust it only if your source URLs require different paths or parameters. The default optimizer does not forward authentication headers when it fetches a source. For authenticated images, Next.js advises considering unoptimized rather than expecting those headers to reach the source.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SVG and other special cases

SVG images are generally served unoptimized. If you enable SVG optimization, follow Next.js’s documented content-disposition and content-security-policy protections rather than treating SVG as an ordinary raster image. Consult the Image component documentation for the configuration details applicable to your version.

Rank #4
Webcam Cover for Logitech C920 C930e c922x Lens Privacy Shutter Slider
  • Compatible with Logitech C920x HD Pro Webcam, Full HD 1080p/30fps Video Calling. Compatible with Logitech C920 Hd Pro Webcam. Compatible with Logitech HD Pro Webcam C920 Widescreen Video Calling and Recording Webcam.
  • Compatible with Logitech C930e Webcam. Compatible with Logitech C922 Pro Stream Webcam 1080P Camera for HD Video Streaming. Compatible with Logitech Privacy Cover for C920 and C930e.
  • This webcam cover conveniently blocks your camera cover to protect your privacy.
  • This also compatible with other popular webcams. This is also known as webcam lid, webcam cap, webcam protector, web camera privacy cover.
  • ienza is a registered trademark and a registered Amazon brand. Use of the ienza trademark without the prior written consent of ienza, LLC. may constitute trademark infringement and unfair competition in violation of federal and state laws. ienza products are developed as cost-effective alternatives to OEM parts. They are not necessarily endorsed by the OEMs
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Formats, caching, and replacement behavior

The built-in optimizer chooses among configured output formats based on the incoming request’s Accept header. WebP is the documented default format; AVIF can also be configured, with encoding and cache tradeoffs described by Next.js. If a proxy or CDN sits in front of Next.js, it must forward Accept for format negotiation to work as intended.

minimumCacheTTL sets a lower bound, while upstream cache-control information can extend the effective max age. Next.js documents no cache invalidation mechanism for optimized images. If an image must be replaced in place, plan for that cache behavior: prefer a changed source URL when appropriate, or clear the image cache where your deployment permits it. These are built-in optimizer details; an external provider’s formats, cache lifetime, and invalidation controls are separate questions.

When should I preload an image?

Preload only when you know which above-the-fold image is likely to be the page’s Largest Contentful Paint (LCP) image. The Pages Router reference notes that loading="eager" or fetchPriority="high" may be preferable in most cases. Avoid preloading several competing candidates, especially when the likely LCP image changes with viewport size or other loading and fetch-priority controls are already in use. Choose the setting that fits the rendered page and verify the API against your Next.js version (Pages Router Image reference).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common image issues

  • The image request is rejected for a remote source: Check that protocol, hostname, pathname, and search policy match the source URL in remotePatterns. Tighten or adjust the pattern rather than allowing arbitrary hosts.
  • An authenticated source fails through the built-in optimizer: The optimizer does not forward request headers to the source. Consider unoptimized for that image, or choose a source-delivery approach that does not depend on forwarded authentication headers.
  • The browser downloads an image that is too large: Check the rendered CSS width and the image’s sizes value together. If sizes is missing or describes a wider layout than the real one, the browser may choose an unnecessarily large candidate.
  • The page shifts when the image loads: Provide accurate intrinsic width and height for fixed-size images, or establish a correctly sized parent for fill. Confirm that CSS does not undermine the reserved aspect ratio.
  • A custom URL returns the wrong size, format, or quality: Inspect the generated URL and compare its parameters with the provider’s accepted syntax and limits. The loader only constructs the request; transformation behavior belongs to the provider.
  • A replaced source still appears unchanged: The built-in optimizer has no cache invalidation mechanism. Use a changed source URL when suitable, or clear the image cache if the deployment permits it.
  • Format negotiation does not produce the expected format: Check the configured formats and whether an intervening proxy or CDN forwards the request’s Accept header.
  • SVG optimization is unsafe or unexpected: SVGs are generally served unoptimized. If enabling optimization, apply the documented content disposition and content security policy settings for your Next.js version.

Or skip the browser setup

If the job is to capture a page as an image or PDF rather than render your own site’s image assets, ScreenshotNeo is a separate screenshot API and MCP server—not a replacement for next/image. A single GET request can return a screenshot in PNG, JPEG, or WebP, or a PDF. For example, using cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options and response details. ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo’s free plan.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.