Next.js and imgix image optimisation without knowing its size

I need to render images on my statically built Next.js website and I would like to do it according to today's best practices.

I have seen that Next.js includes next/Image which takes care of most optimisation out of the box. Given I won't have images saved in multiple sizes, I was looking at imgix to do this for me.

How I envisioned this setup is, I dump all images in an S3 bucket (I only know the filename) which will be used by imgix. Given the filename and a width requirement, I would then leave it to next/Image to resize and render the images via its imgix loader.

Where I get confused is, the Next.js docs mention both the width and height should be known prior. How would I know the height if I only provide the width to imgix and let it do its resize magic?

I am sure I am missing something obvious here, but a pointer would be highly appreciated.


A little disclaimer, I work at imgix.

Hopefully I can clarify by outlining the responsibilities of some things you mentioned:

  • Next.js is responsible for text/html/dom manipulation/more (i.e. placing img tags with the appropriate attributes in markup/html/etc.)

  • imgix is responsible for all the image processing (i.e. pretty much as you described, s3 => request a specific size => done)

  • devs/designers are responsible for page layout (e.g. css, overall html structure)

The linked section in the Next.js docs does a good job explaining layout shift and how to avoid it (it may or may not be an issue for you).

The height (and width) of your images are determined by your page’s layout. For example, you’ve designed an image gallery that displays uniformly sized images (i.e. each image is bounded above by the top of the row, below by the bottom of the row, and left/right by the columns).

How would I know the height if I only provide the width to imgix and let it do its resize magic?

One way of knowing what the dimensions of your images are/should be is for your designer to tell you what they should be. Many of us aren't that lucky so if you are the designer, once you’re satisfied with your layout you can inspect the width/height of the rendered images and then use that information to provide width/height attributes to the Next.js component.

They also specify a third option which involves using "layout="fill" which causes the image to expand to fill its parent element." If you do go with this third option remember "When using layout='fill', the parent element must have position: relative."

Again, this is all within the context of avoiding layout shift. If you specify the width of images to imgix the height will be calculated according to the aspect ratio of the original image. You can also specify aspect ratio along with other parameters to get the desired effect.