Next.js

Fonts and Images

by Tomas Trescak t.trescak@westernsydney.edu.au

Next.js

/

Fonts and Images

  • Image and font optimisation crucial for performance and UX.
  • Improves page load times, visual stability, and user engagement.
  • Next.js provides built-in tools for streamlined optimization.

Next.js

/

Static Files

    export default async function Home() {
  return (
    <main>
      <img src="/cat.png" alt="My Cat" />
    </main>
  );
}
  
/src/app/page.tsx
  • Static files (images, fonts) stored in the public folder.
  • Accessible from the base URL (/)
    /my-next-app
├── /app
├── /public
│   ├── /cat.png
│   ├── /wolfie.png
│   ├── /font.woff2
├── /components
  

Next.js

/

Local Images

    import Image from 'next/image'
import catPic from './cat.png' // cat.png in public folder

export default async function Home() {
  return (
    <main>
      <Image src={catPic} alt="My Cat" width={500} height={300} />
    </main>
  );
}
  
/src/app/page.tsx

Next.js

/

Remote Images

    <Image
  src="https://s3.amazonaws.com/my-bucket/cat.png"
  alt="My Cat"
  width={500}
  height={300}
/>

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        pathname: '/my-bucket/**',
      },
    ],
  },
}
  
/src/app/page.tsx
  • Images hosted on external servers
  • Requires width, height, and configuration in next.config.js

Next.js

/

Fonts

    import { Roboto } from 'next/font/google'

const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
})

// In your component:
<html lang="en" className={roboto.className}>
  <body>
    {/* ... */}
  </body>
</html>
  
/src/app/layout.tsx
  • next/font module for font optimization
  • Automatic self-hosting of fonts (Google Fonts and local fonts)

Next.js

/

Local Fonts

    import localFont from 'next/font/local'

const myFont = localFont({
  src: './my-font.woff2', // Font file in public folder
})

// In your component:
<html lang="en" className={myFont.className}>
  <body>
    {/* ... */}
  </body>
</html>
  
/src/app/layout.tsx
  • For self-hosting custom font files
  • Font files placed in the public folder

Next.js

/

Conclusion

  • Image and font optimisation is crucial for web performance.
  • Next.js provides powerful tools: <Image> and next/font .
  • Remember public folder, next.config.js , and className