Everything you think you know about next/image is wrong!

Everyoneusesnext/image,butveryfewactuallyunderstandwhathappensbehindthescenes.Andthislackofunderstandingoftenleadstoconfusion,myths,andevenperformanceissues.Inthisblog,Ibreakdownexactlyhownext/imageworksunderthehood—withouttheboringdocumentationtone.
Let’sstartwiththisverybasicsnippet,whichIbelieveeveryonereadingthisisfamiliarwith:
1import Image from 'next/image';
2
3export default function Page() {
4 return (
5 <Image
6 src="/shady.png"
7 width={500}
8 height={500}
9 alt="The real slim shady"
10 />
11 );
12}
(youcandirectlypastethissnippetinyourcodebase,justchangetheimageofyourliking.)
ThisisMagic,buthow?
Thisisallthefrontpartwhichyouenjoywritingthecodebecauseitisseamlesstointegrate,butthereisasolidfoundationandlotsofhardworkhasbeenputunderthehoodtomakeitworklikethis.InthisblogI’lltalkingin-depthaboutnext/imageandalsotrytoclearsomeofthemisconceptionssurroundingit.
CoreArchitecture
Thecorearchitectureofnext/imageisprimarilymadeupofthreecomponents.

CoreArchitecturebreakdown
- 1. React Component
- 2. Image API
- 3. Image Optimizer
Nowlet’sbreakdowneverything.
ReactComponent
next/imageisnothingbutareactcomponentanditsprimaryfunctionistogeneratecorrectHTMLimageoutputbasedonthepropertiesprovidedandalsoitconstructsmultipleURLswhichpointstodifferentsizedversionsofthesameimage,youcancalloptimizedvariants.
Basicallyitnext/imagedoesn’tjustoutputoneimgtagwithasinglesrc.InsteaditgeneratesmultipleversionsofthesameimagewithdifferentsizesandconstructstheappropriateHTMLtoservethebestpossibleversionforeachdevice.
ThecomponentgeneratesoptimizedimageURLsfordifferentresolutionsandpopulatetheminthesrcsetandsrcattributesofthefinalHTMLimgelement,sobrowserscanloadtherightimagesizeforeachdeviceautomatically.hereistheexamplecodewhichisoutputofNextImagecomponent.
1<img
2 alt="Example"
3 loading="lazy"
4 width="500"
5 height="500"
6 decoding="async"
7 data-nimg="1"
8 style="color:transparent"
9 srcset="/_next/image?url=%2Fimages%2Fexample.jpg&w=640&q=75 1x,
10 /_next/image?url=%2Fimages%2Fexample.jpg&w=1080&q=75 2x"
11 src="/_next/image?url=%2Fimages%2Fexample.jpg&w=1080&q=75"
12>
Nowlet’stakeacloserlookatthegeneratedURL:
/_next/image?url=/images/example.jpg&w=640&q=75
ThisencodedURLacceptstwoparameterswandqwhichstandsforwidthandqualityrespectively,whicharemorevisibleinthedecodedversion.Nowyoumighthaveobservedthereisnohheightattribute,fornowjustkeepthisinmindI’llconnectthedotahead.
ImageAPI
Thenextimageapiservesasanimageproxy,meaningnextjsstandsbetweenyourappandtheoriginalimagesource—itfetches,optimizes,cachesandservestheimageonyourbehalf.ItisverysimilartoIPX.Itperformthesetasks.
- 1. Accepts an image URL, width and quality.
- 2. Validates parameters
- 3. Determine cache control policies
- 4. Process the image
- 5. Serves the image in a format supported by the user’s browser
Nowatthispoint,thingsarestartedtotakeashapeorstartedmakingsense.Nowlet’sjumptothefinalpieceofthepuzzle.
ImageOptimizer
NextImageutilizesdifferentimageoptimizationlibrariessuchasSharporSquoosh,dependingoncertainconditions.
Sharpisafastandefficientimageoptimizationlibrarylibraryfornode.jsthatmakesuseoftheNativelibvipslibrary.
Squooshisafullynode-basedimageoptimizationsolution.It’sslowerthantheSharp,butitdoesn’trequireanyadditionallibrariestobeinstalledonamachine.Forthisreason,Sharpisrecommendedforproductionuse,whereasSquooshisusedbydefaultinlocalenvironments.
Botharequitesimilar,bothhavingtheirprosandcons.IwouldsuggesttouseSharpinlocalenvironmentsaswell.Howeversharp’simageoptimizingalgorithmscanleadtoslightcolordegradation,morethatsquoosh.Thismayresultinvisuallydifferentbehavioursbetweenproductionandlocalenviornments,Speciallywhentryingtomatchthebackgroundcolorsofimagewiththepage’sbackground.Ifyouhavealsoexperiencedthis,nowyouthereasonwhy.
Results
Nowyouknowwhatistheprimaryarchitecturebehindthenext/image.Nowwecandebunkcommonmisconceptionsandgleanmoreinsightsonhowtoutilizeitmoreeffectively.
next/imagedoesnotcrop.
Acommonmisconceptionamongdevsisthatnext/imagecancroptheirimages.Thisquestionarisesbecauseyoucanpasswidth,heightandfillpropertiestothecomponent,whichmaycreateanimpressionthattheimageisbeingcropped.Butinrealitythisisn’tthecase.Thenextimagecomponentprimarilyrequiresthewidthandheightforassigningtotheimgtagtopreventlayoutshifts.
NowconnectingthedotofthatheightattributethatItalkedaboutaboveintheReactComponent.TheImageAPIdoesnotaccepttheheightparameterbecauseitcurrentlyisn’tpossibletochangetheoriginalimage’saspectratio,whichmeans.Ifyoudon’tusethefillproperty,theimagewillsimplystretchorshrinkincasesofwidth–heightmismatches.
Howeverthereisanexceptionifyou’reusingtailwindcss,itbehavesdifferentlydueitsdefaultglobalcssrule.Thismakeslayoutshiftsissueshardertodetect,hereisthesnippetoftherule.
1img,
2video {
3 max-width: 100%;
4 height: auto;
5}
DisplayedImagewidth≠globalimagewidth
Another potential point of confusion is that the width property passed to next/image doesn't represent the actual width to which the image will be resized when the screen will be subjected to a lower width scenerio. As we noted from the example at the start of the blog, passing width=500 to a component will result in the image being resized to a width of 640px, as evident in the generated URL:
/_next/image?url=/images/example.jpg&w=640&q=75
Ifyouexpectthex2retinaversiontoutilizeanimagewidthof1000pxor1280px,you'reinforasurprise.Theactualwidthusedwillbe1080px.Naturally,naturallyyoumightwonderwherethesenumbersarecomingfrom.

Next.jsresizesimagestotheclosestsizefromanarrayofdeviceSizesandimageSizesthatyoucandefineinnext.config.js.Bydefault,theseare:
1module.exports = {
2 images: {
3 deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
4 imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
5 },
6};
What’scrucialtonotehereisthatusingthedefaultconfigurationcannegativelyimpactperformance,leadingtoareducedscoreinLighthouse’sPageSpeedInsights.Thisbecomesparticularlyevidentwhenyouattempttodisplaylargeimagesonapage.Forinstance,ifyouwanttorenderanimagewithawidthof1250px,theactualloadedimagewidthwillbe1920px.Thediscrepancybetweentherequiredsizeandtheactualloadedsizebecomesevengreaterforx2retinaversions,asthesewillberesizedto3840px.However,youcanremedythisbyaddingmoresizestothedeviceSizesorimageSizesarrays.
Imageoptimizationcanbeusedwithoutthenext/imagecomponent
Ialreadydiscussedabouttheimageapiabove,withthisunderstandingofthecorearchitecture,it’sveryobviousthatyoucanuseImageAPIwithoutnecessarilyusingnext/image.Butisthisreallyagoodoption?Let’sfindoutandseesomescenariosinwhichthiscanbeuseful.
First,youcanrenderoptimizedimagesinsideacanvas.Regardlessofwhetheryou’reloadingimagesontoacanvasfromexternalsourcesorfromlocalstorage,youcanpassthecorrectURLtotheAPIandhaveitworkseamlessly.
First,youcanrenderoptimizedimagesinsideacanvas.Regardlessofwhetheryou’reloadingimagesontoacanvasfromexternalsourcesorfromlocalstorage,youcanpassthecorrectURLtotheAPIandhaveitworkseamlessly.
/_next/image?url=/images/example.jpg&w=640&q=75
Alwaysremember,thewidthparameterischeckedbytheAPIandcanonlybeanumbersourcedfromeitherthedeviceSizesorimageSizesconfiguration.
Useimportforlocalimages
Innext/image,therearetwowaysbywhichyouloadlocalimages:
1import Image from 'next/image';
2import em from './shady.png';
3
4export default function TheRealSlimShady() {
5 return (
6 <>
7 {/* Using absolute path */}
8 <Image src="/shady.png" width={500} height={500} alt="The real slim shay" />
9 {/* Using imported image via relative path */}
10 <Image src={em} alt="Em" />
11 </>
12 );
13}
14
Usinganabsolutepathforlocalimagesisprettycommon—you’llseeitinexamples,tutorials,andevenopen-sourceprojects.Andit’seasytoassumetheonlydifferenceisthatNext.jswon’tauto-assignthewidthandheight.Butnope,thereisarealdifference.Whenyouloadimagesusinganabsolutepathfromthepublicfolder,Next.jsfollowsthecacheheadersoftheserver,whichdefaultstoa30-daycacheinsteadofpublic,max-age=31536000,immutable.Andyeah,that30-daycachecanactuallyhurtyourLighthousescorequiteabit.
Conclusions
Iamsureatthispoint,you’realsoexhaustedlikeIam.Wellthenlet’sdrawtheconclusionandendthisblog.
Imageoptimization(next/image)providessignificantadvantagesandsimplifiesimagemanagement,itcouldbenefitfromadditionalfeatureslikeadvancedcroppingandpreciseresizing,similartothird-partysolutions.
Wellpersonallyinmyopinion,formostusecase,thedeveloperexperienceandefficiencyofNextImagewillbemorethanenough.
Endingthisblogwithlot’soflove.Ifyoulikethisblogpleaseshareitwithyourfriends.YoucanalwayssuggestmesometopicsincommentsorDMme.Iwilltrymybesttomakeanarticleoutofit.
Iamdroppingbelowalltheresourceswhichmadeitpossibleformetowritethisblog.AndIreallyappreciatealltheworkthey’vedone.
ThankYou!