Serving Static Assets

Learn about serving static files and image optimization in Next.js.

When using the term static asset, we refer to all of those nondynamic files, such as images, fonts, icons, compiled CSS, and JS files.

The easiest way to serve those assets is by using the default /public folder provided by Next.js. In fact, every file inside this folder will be considered and served as a static asset. A new file called index.txt is created and put inside the /public folder:

Click the “Run” button below to execute the code. Once it has finished execution, you can view the output using the link provided.

export PORT=5000
ln -s /app/node_modules/ /usercode/app 
cd /usercode/app
npm run dev
Serving index.txt as a static file

We’ll see the text “Hello, world!” displayed in the browser.

Reducing Cumulative Layout Shift through image optimization

Serving static assets is relatively easy. However, a specific type of file can critically affect our website performance (and SEO): the image file.

Most of the time, serving non-optimized images will worsen our user experience because they may take some time to load, and once they do, they’ll move part of the layout after the rendering, which can cause many problems in terms of UX. When this occurs, we’re talking about Cumulative Layout Shift (CLS)Cumulative Layout Shift (or CLS) is a measure of how much a web page unexpectedly shifts during its life.. Here’s a simple representation of how CLS works:

Press + to interact
Representation of how CLS works
Representation of how CLS works

In the first browser tab, the image has not been loaded yet, so the two text areas look quite close to each other. After the image ...