Capítulo 373 de 456

public

Core Idea

The public folder at the project root serves static files directly from the base URL (/), e.g. images, robots.txt, favicon.ico.

Key Concepts

  • public/: files referenced starting from /; public/avatars/me.png is served at /avatars/me.png.
  • Caching: Next.js applies Cache-Control: public, max-age=0 by default since it can't safely assume these assets are immutable.
  • Naming collisions: a static file in public/ sharing a name with a file in pages/ causes a build error.

Code Examples

import Image from 'next/image'

export function Avatar({ id, alt }) {
  return <Image src={`/avatars/${id}.png`} alt={alt} width="64" height="64" />
}
  • O que demonstra: referencing a public/ asset via absolute path.

Reference Tables

None.

Anti-patterns

  • Naming a public/ file the same as a pages/ route: throws a build error (conflicting public file/page).
  • Assuming aggressive caching: default headers are max-age=0; configure headers() in next.config.js per-asset if you need longer caching.

Key Takeaways

  1. Use public/ for robots.txt, favicon.ico, verification files, and any static asset needing a stable public URL.
  2. Default caching is minimal; override via next.config.js headers if needed.
  3. Avoid filename collisions between public/ and pages/.

Connects To

  • src Directory: public/ must always stay at the project root even when using src/.
  • Image (Legacy) / Image: commonly loads assets from public/.