0
0
NextJSframework~3 mins

Why Public directory for static files in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple folder can save you hours of debugging broken image links!

The Scenario

Imagine you have images, icons, or fonts that your website needs to show. You try to put them in your project folders and write code to load each file manually with complex paths.

The Problem

Manually managing static files is confusing and error-prone. Paths can break easily, files might not load, and you waste time fixing broken links instead of building features.

The Solution

Next.js provides a public directory where you can simply drop static files. These files are served automatically at the root URL, making access easy and reliable.

Before vs After
Before
const logo = require('../assets/images/logo.png');
<img src={logo} alt="Logo" />
After
<img src="/logo.png" alt="Logo" />
What It Enables

This lets you focus on building your app without worrying about file paths or server setup for static assets.

Real Life Example

When building a company website, you can put your logo, favicon, and background images in the public folder and reference them easily in your pages.

Key Takeaways

Managing static files manually is tricky and breaks easily.

The public directory in Next.js serves files automatically at the root URL.

This simplifies file access and speeds up development.