new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · API reference · all subjects

components/image

62 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Image component import and basic usage

The Next.js Image component extends the HTML `<img>` element for automatic image optimization. Import it from 'next/image' and use it with required props `src`, `width`, `height`, and `alt`.

Image component props - complete reference

Image component props: src (String, Required), alt (String, Required), width (Integer px, -), height (Integer px, -), fill (Boolean, -), loader (Function, -), sizes (String, -), quality (Integer 1-100, -), preload (Boolean, -), placeholder (String, -), style (Object, -), onLoadingComplete (Function, Deprecated), onLoad (Function, -), onError (Function, -), loading (String, -), blurDataURL (String, -), unoptimized (Boolean, -), overrideSrc (String, -), decoding (String, -).

src prop - internal path, external URL, or static import

The src prop can be: an internal path string (e.g. '/profile.png'), an absolute external URL configured with remotePatterns (e.g. 'https://example.com/profile.png'), or a static import (e.g. import profile from './profile.png'). For security, the Image Optimization API using the default loader will not forward headers when fetching the src image. If src requires authentication, use the unoptimized property.

alt prop - required for accessibility

The alt property describes the image for screen readers and search engines, serving as fallback text if images are disabled or fail to load. It should contain text that could replace the image without changing the page meaning. For purely decorative images or those not intended for the user, alt should be an empty string (alt="").

width and height props - intrinsic size and aspect ratio

The width and height properties represent the intrinsic image size in pixels and are used to infer the correct aspect ratio for browsers to reserve space and avoid layout shift. They do not determine rendered size (controlled by CSS). Both must be set unless: the image is statically imported, or the image has the fill property. If dimensions are unknown, use the fill property.

fill prop - expand image to parent element

The fill boolean prop causes the image to expand to the size of the parent element. The parent element must assign position: 'relative', 'fixed', or 'absolute'. By default, the <img> element uses position: 'absolute'. If no styles are applied, the image stretches to fit the container. Use objectFit to control cropping and scaling: 'contain' scales down and preserves aspect ratio, 'cover' fills container and crops.

loader prop - custom image URL generation

The loader prop is a custom function that generates the image URL. It receives parameters: src, width, and quality, and returns a URL string. Using props like loader that accept functions requires using Client Components (in app router) to serialize the provided function. Alternatively, configure loaderFile in next.config.js to configure every instance without passing a prop.

loader example - custom function

```jsx 'use client' import Image from 'next/image' const imageLoader = ({ src, width, quality }) => { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } export default function Page() { return ( <Image loader={imageLoader} src="me.png" alt="Picture of the author" width={500} height={500} /> ) } ``` This example shows a custom loader function that constructs an image URL with width and quality query parameters.

sizes prop - define image sizes at different breakpoints

The sizes prop defines image sizes at different breakpoints, used by the browser to choose the most appropriate size from the generated srcset. Use it when: the image is using the fill prop, or CSS is used to make the image responsive. Without sizes, the browser assumes the image is 100vw wide, potentially downloading unnecessarily large images. With sizes, Next.js generates a full srcset (e.g. 640w, 750w); without it, a limited srcset (e.g. 1x, 2x) suitable for fixed-size images.

quality prop - optimize image quality

The quality prop is an integer between 1 and 100 that sets the quality of the optimized image. Default is 75. Higher values increase file size and visual fidelity; lower values reduce file size but may affect sharpness. If qualities config is set in next.config.js, the value must match one of the allowed entries. High quality values on already low-quality images will increase file size without improving appearance.

preload prop - preload image behavior

The preload boolean prop indicates if the image should be preloaded. Default is false. When true, preloads the image by inserting a <link> in the <head>. Use preload when: the image is the Largest Contentful Paint (LCP) element, is above the fold (typically hero image), or you want to begin loading before it's discovered in <body>. Do not use when: you have multiple images that could be LCP depending on viewport, when using the loading prop, or when using fetchPriority. In most cases, use loading="eager" or fetchPriority="high" instead.

priority prop - deprecated in favor of preload

Starting with Next.js 16, the priority property is deprecated in favor of the preload property to make the behavior clear.

loading prop - control when image loads

The loading prop controls when the image should start loading. Values are: 'lazy' (defer loading until image reaches calculated distance from viewport, default), 'eager' (load immediately regardless of position). Use 'eager' only when you want to ensure the image is loaded immediately.

placeholder prop - display placeholder while loading

The placeholder prop specifies a placeholder while the image is loading to improve perceived loading performance. Values are: 'empty' (no placeholder, default), 'blur' (use blurred version of image, must be used with blurDataURL prop), 'data:image/...' (uses Data URL as placeholder). Examples include blur placeholder, shimmer effect with data URL placeholder, and color effect with blurDataURL.

blurDataURL prop - placeholder image before load

The blurDataURL prop is a Data URL used as a placeholder image before the image successfully loads. The image is automatically enlarged and blurred, so a very small image (10px or less) is recommended. For static imports of jpg, png, webp, or avif files, blurDataURL is added automatically unless the image is animated. For dynamic or remote images, provide blurDataURL manually. Tools: online tools like png-pixel.com, or libraries like Plaiceholder. Keep it small and simple to avoid performance impact.

style prop - CSS styles for image element

The style prop allows passing CSS styles to the underlying image element. When using style prop to set custom width, also set height: 'auto' to preserve the image's aspect ratio.

onLoad prop - callback when image loads

The onLoad prop is a callback function invoked once the image is completely loaded and the placeholder has been removed. It receives one argument: the event with a target property referencing the underlying <img> element. Using props like onLoad that accept functions requires using Client Components (in app router) to serialize the provided function.

onError prop - callback when image fails to load

The onError prop is a callback function invoked if the image fails to load. Using props like onError that accept functions requires using Client Components (in app router) to serialize the provided function.

unoptimized prop - disable image optimization

The unoptimized boolean prop indicates if the image should be optimized. Useful for images that don't benefit from optimization such as small images (less than 1KB), vector images (SVG), or animated images (GIF). When true, the source image is served as-is from src without changing quality, size, or format. When false (default), the source image is optimized. Can be set globally in next.config.js: images: { unoptimized: true }.

overrideSrc prop - override src attribute

When providing the src prop to Image, both srcset and src attributes are generated automatically for the resulting <img>. The overrideSrc prop allows overriding the src attribute value without changing the srcset. Useful when upgrading from <img> to <Image> to maintain the same src attribute for SEO purposes like image ranking or avoiding recrawl.

decoding prop - image decode timing hint

The decoding prop hints to the browser whether it should wait for the image to be decoded before presenting other content updates. Values are: 'async' (asynchronously decode, allow other content to render first, default), 'sync' (synchronously decode for atomic presentation with other content), 'auto' (no preference, browser chooses).

onLoadingComplete prop - deprecated callback

The onLoadingComplete prop is deprecated in Next.js 14. Use onLoad instead. It was a callback function invoked once the image is completely loaded and the placeholder has been removed, called with one argument: a reference to the underlying <img> element.

srcSet prop - cannot be passed directly

The srcSet prop cannot be passed to the Image component. Use deviceSizes instead to configure device width breakpoints.

localPatterns config - allow images from specific local paths

The localPatterns configuration in next.config.js allows images from specific local paths to be optimized and blocks all others. It takes an array of objects with pathname (glob pattern) and search (query string) properties. Attempting to optimize any other path responds with 400 Bad Request. Omitting the search property allows all search parameters, which could allow malicious optimization. Use specific values like search: '?v=2' for exact match.

remotePatterns config - allow images from external paths

The remotePatterns configuration in next.config.js allows images from specific external paths and blocks all others. Accepts array of URL objects or glob pattern objects. Glob pattern objects have properties: protocol (string), hostname (string with wildcards), port (string), pathname (string with wildcards), search (string). Wildcard patterns: '*' matches single path segment or subdomain, '**' matches any number at end or beginning. When omitting protocol, port, pathname, or search, wildcard '**' is implied (not recommended for security). Query strings can be restricted using search property. Redirects from allowed remotePatterns follow without validating again; configure maximumRedirects to reduce.

path config - change Image Optimization API path

The path configuration in next.config.js changes or prefixes the default path for the Image Optimization API. Default value is '/_next/image'. Can be customized to a different path like '/my-prefix/_next/image'.

deviceSizes config - device width breakpoints

The deviceSizes configuration in next.config.js specifies a list of device width breakpoints used when the next/image component uses the sizes prop to ensure the correct image is served for the user's device. Default: [640, 750, 828, 1080, 1200, 1920, 2048, 3840].

imageSizes config - image widths for srcset

The imageSizes configuration in next.config.js specifies a list of image widths concatenated with deviceSizes to form the full array of sizes used to generate image srcset. Default: [32, 48, 64, 96, 128, 256, 384]. Only used for images providing a sizes prop, indicating image is less than full screen width. All imageSizes should be smaller than smallest deviceSize.

qualities config - allowed image quality values

The qualities configuration in next.config.js specifies a list of allowed image quality values. Default: [75]. Required starting with Next.js 16 because unrestricted access could allow malicious actors to optimize unintended qualities. If quality prop doesn't match a value in array, the closest allowed value is used. If REST API is visited directly with unmatched quality, server returns 400 Bad Request.

formats config - allowed image formats

The formats configuration in next.config.js specifies a list of image formats to be used. Default: ['image/webp']. Next.js detects browser's supported formats via Accept header to determine best output format. If Accept header matches multiple configured formats, first match in array is used, so array order matters. If no match or source image is animated, uses original format. Can enable AVIF with ['image/avif'] or both with ['image/avif', 'image/webp']. AVIF takes 50% longer to encode but compresses 20% smaller than WebP. When using multiple formats, Next.js caches each separately, increasing storage. If using Proxy/CDN in front, must configure to forward Accept header.

minimumCacheTTL config - cache expiration for optimized images

The minimumCacheTTL configuration in next.config.js sets the Time to Live (TTL) in seconds for cached optimized images. Default: 14400 (4 hours). For static imports, use automatically hashed file contents with Cache-Control: immutable for forever caching. Can increase TTL to reduce revalidations and potentially lower cost. Image expiration is defined by either minimumCacheTTL or upstream image Cache-Control header, whichever is larger. Configure headers to set Cache-Control on upstream image. No cache invalidation mechanism exists; keep minimumCacheTTL low or manually delete cached files in <distDir>/cache/images.

disableStaticImages config - disable static image imports

The disableStaticImages configuration in next.config.js disables static image imports. Default allows importing static files like 'import icon from "./icon.png"' and passing to src property. Can disable if it conflicts with other plugins expecting import to behave differently. Set in next.config.js: images: { disableStaticImages: true }.

maximumRedirects config - HTTP redirect limits

The maximumRedirects configuration in next.config.js sets how many HTTP redirects to follow when fetching remote images. Default: 3. Can set to 0 to disable following redirects. These redirects don't need to satisfy remotePatterns for convenience.

maximumDiskCacheSize config - disk cache size limit

The maximumDiskCacheSize configuration in next.config.js sets the maximum disk cache size in bytes for optimized images. Can configure value like 500_000_000 for 500 MB, or set to 0 to disable disk cache entirely. Default: on startup, checks available disk space and uses 50%. When cache exceeds configured size, least recently used images are deleted until under limit. Alternatively, implement custom cache handler using cacheHandler which ignores this configuration.

maximumResponseBody config - source image size limit

The maximumResponseBody configuration in next.config.js sets the maximum size of source images the loader will fetch. Default: 50_000_000 (50 MB). Can reduce to smaller value like 5_000_000 (5 MB) on memory constrained servers if source images are known to be small.

dangerouslyAllowLocalIP config - allow local IP optimization

The dangerouslyAllowLocalIP configuration in next.config.js allows optimizing images from local IP addresses on the same network when self-hosting Next.js on private network. Default: false (not recommended for most users as could allow malicious access to internal network content). Set to true if self-hosting in VPC with split-horizon DNS and receiving status 400 Bad Request. Only enable after understanding SSRF risk.

dangerouslyAllowSVG config - serve SVG images

The dangerouslyAllowSVG configuration in next.config.js allows serving SVG images. Default: false. By default, Next.js doesn't optimize SVG for reasons: SVG is vector format (resizable losslessly), has similar features as HTML/CSS (security vulnerabilities without proper CSP headers). When enabling, recommend using unoptimized prop when src is known SVG (happens automatically when src ends with '.svg'). Strongly recommend also setting contentDispositionType: 'attachment' and contentSecurityPolicy to prevent embedded scripts from executing.

contentDispositionType config - Content-Disposition header

The contentDispositionType configuration in next.config.js configures the Content-Disposition header value. Can be set to 'inline' or 'attachment'. Default (by loader): 'attachment' forces browser to download image when visiting directly, adding protection since API can serve arbitrary remote images.

contentSecurityPolicy config - CSP header for images

The contentSecurityPolicy configuration in next.config.js configures the Content-Security-Policy header for images. Important when using dangerouslyAllowSVG to prevent scripts embedded in image from executing. Example: "default-src 'self'; script-src 'none'; sandbox;".

domains config - deprecated hostname allowlist

The domains configuration is deprecated since Next.js 14 in favor of strict remotePatterns to protect applications from malicious users. Similar to remotePatterns, domains provides list of allowed hostnames for external images, but doesn't support wildcard pattern matching and cannot restrict protocol, port, or pathname. Most remote image servers are shared between multiple tenants, so remotePatterns is safer.

getImageProps function - extract image props

The getImageProps function can be imported from 'next/image' to get the props that would be passed to the underlying <img> element, allowing passing them to another component, style, canvas, etc. Returns object with props property. Avoids calling React useState() for better performance, but cannot be used with placeholder prop since placeholder will never be removed.

getImageProps example - extract and use image props

```jsx import { getImageProps } from 'next/image' const { props } = getImageProps({ src: 'https://example.com/image.jpg', alt: 'A scenic mountain view', width: 1200, height: 800, }) function ImageWithCaption() { return ( <figure> <img {...props} /> <figcaption>A scenic mountain view</figcaption> </figure> ) } ``` This example shows extracting image props and using them with a custom figure element.

next/image version history and changelog

Version history for next/image component and related configuration: v16.1.7: maximumDiskCacheSize configuration added. v16.1.2: maximumResponseBody configuration added. v16.0.0: qualities default configuration changed to [75], preload prop added, priority prop deprecated, dangerouslyAllowLocalIP config added, maximumRedirects config added. v15.3.0: remotePatterns added support for array of URL objects. v15.0.0: contentDispositionType configuration default changed to attachment. v14.2.23: qualities configuration added. v14.2.15: decoding prop added and localPatterns configuration added. v14.2.14: remotePatterns.search prop added. v14.2.0: overrideSrc prop added. v14.1.0: getImageProps() is stable. v14.0.0: onLoadingComplete prop and domains config deprecated. v13.4.14: placeholder prop support for data:/image... v13.2.0: contentDispositionType configuration added. v13.0.6: ref prop added. v13.0.0: next/image import was renamed to next/legacy/image. next/future/image import was renamed to next/image. span wrapper removed. layout, objectFit, objectPosition, lazyBoundary, lazyRoot props removed. alt is required. onLoadingComplete receives reference to img element. Built-in loader config removed. v12.3.0: remotePatterns and unoptimized configuration is stable. v12.2.0: Experimental remotePatterns and experimental unoptimized configuration added. layout="raw" removed. v12.1.1: style prop added. Experimental support for layout="raw" added. v12.1.0: dangerouslyAllowSVG and contentSecurityPolicy configuration added. v12.0.9: lazyRoot prop added. v12.0.0: formats configuration added. AVIF support added. Wrapper div changed to span. v11.1.0: onLoadingComplete and lazyBoundary props added. v11.0.0: src prop support for static import. placeholder prop added. blurDataURL prop added. v10.0.5: loader prop added. v10.0.1: layout prop added. v10.0.0: next/image introduced.

AWS CloudFront image loader example

export default function cloudfrontLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('format', 'auto') url.searchParams.set('width', width.toString()) url.searchParams.set('quality', (quality || 75).toString()) return url.href }

Custom image loader function signature

A custom image loader function receives an object with properties: src (the image source), width (the requested width), and quality (the quality setting, with a default of 75 if not provided). The function must return a string representing the complete optimized image URL.

Custom image loader must be a Client Component

Customizing the image loader file, which accepts a function, requires using Client Components to serialize the provided function. The loader file should include the 'use client' directive.

Custom loader via loader prop on Image component

Alternatively to configuring a custom loader in next.config.js, you can pass the loader function directly to each instance of next/image using the loader prop.

Akamai image loader example

export default function akamaiLoader({ src, width, quality }) { return `https://example.com/${src}?imwidth=${width}` }

Cloudinary image loader example

export default function cloudinaryLoader({ src, width, quality }) { const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`] return `https://example.com/${params.join(',')}${src}` }

Cloudflare image loader example

export default function cloudflareLoader({ src, width, quality }) { const params = [`width=${width}`, `quality=${quality || 75}`, 'format=auto'] return `https://example.com/cdn-cgi/image/${params.join(',')}/${src}` }

Contentful image loader example

export default function contentfulLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('fm', 'webp') url.searchParams.set('w', width.toString()) url.searchParams.set('q', (quality || 75).toString()) return url.href }

Fastly image loader example

export default function fastlyLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('auto', 'webp') url.searchParams.set('width', width.toString()) url.searchParams.set('quality', (quality || 75).toString()) return url.href }

Gumlet image loader example

export default function gumletLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('format', 'auto') url.searchParams.set('w', width.toString()) url.searchParams.set('q', (quality || 75).toString()) return url.href }

ImageEngine image loader example

export default function imageengineLoader({ src, width, quality }) { const compression = 100 - (quality || 50) const params = [`w_${width}`, `cmpr_${compression}`] return `https://example.com${src}?imgeng=/${params.join('/')` }

Imgix image loader example

export default function imgixLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) const params = url.searchParams params.set('auto', params.getAll('auto').join(',') || 'format') params.set('fit', params.get('fit') || 'max') params.set('w', params.get('w') || width.toString()) params.set('q', (quality || 50).toString()) return url.href }

PixelBin image loader example

export default function pixelBinLoader({ src, width, quality }) { const name = '<your-cloud-name>' const opt = `t.resize(w:${width})~t.compress(q:${quality || 75})` return `https://cdn.pixelbin.io/v2/${name}/${opt}/${src}?f_auto=true` }

Sanity image loader example

export default function sanityLoader({ src, width, quality }) { const prj = 'zp7mbokg' const dataset = 'production' const url = new URL(`https://cdn.sanity.io/images/${prj}/${dataset}${src}`) url.searchParams.set('auto', 'format') url.searchParams.set('fit', 'max') url.searchParams.set('w', width.toString()) if (quality) { url.searchParams.set('q', quality.toString()) } return url.href }

Sirv image loader example

export default function sirvLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) const params = url.searchParams params.set('format', params.getAll('format').join(',') || 'optimal') params.set('w', params.get('w') || width.toString()) params.set('q', (quality || 85).toString()) return url.href }

Supabase image loader example

export default function supabaseLoader({ src, width, quality }) { const url = new URL(`https://example.com${src}`) url.searchParams.set('width', width.toString()) url.searchParams.set('quality', (quality || 75).toString()) return url.href }

Thumbor image loader example

export default function thumborLoader({ src, width, quality }) { const params = [`${width}x0`, `filters:quality(${quality || 75})`] return `https://example.com${params.join('/')}${src}` }

Give your agent this brain