13 Load assets with Next.js

13.1 Introduction

Next.js provides efficient and flexible methods for loading assets such as images, fonts, CSS and JavaScript. These functionalities are crucial for the performance and user experience of web applications.

13.2 Static assets

Static assets such as images, fonts and stylesheets are usually stored in the public directory. They can be referenced via the base URL path. For example, an image in the public/images folder is included as <img src="/images/example.png" alt="Example" />.

13.3 Import of component assets

In Next.js, JavaScript modules and CSS can be imported directly into components. For example:

import React from 'react';
import styles from './MyComponent.module.css';

function MyComponent() {
  return <div className={styles.container}>Hello world</div>;
}

13.4 Optimization of images

Next.js offers a powerful way to optimize images with the <image /> tag from next/image. This tag enables automatic optimizations such as lazy loading, resizing and format conversions.

13.5 Dynamic loading of assets

For efficient resource utilization, Next.js supports dynamic loading of JavaScript modules and components with import(). This feature is useful for code splitting and loading components on demand.

13.6 Environment variables for assets

Environment variables can be used to configure asset paths at runtime. These can be set in the .env file and referenced with process.env.MY_VARIABLE in the code.

Loading assets in Next.js is an essential part of developing modern web applications. By handling resources efficiently, Next.js improves performance and user experience.