Skip to content

Next.js - Static File Serving

Next.js makes it simple to serve static assets like images, fonts, stylesheets, or verification files directly from the public directory located in your project’s root.

Files inside the public directory are mapped to the root URL (/) of your application.

  • public/my-image.png can be accessed at /my-image.png.
  • public/css/style.css can be accessed at /css/style.css.
  • public/robots.txt can be accessed at /robots.txt.

This mechanism is ideal for assets that don’t need processing or bundling, such as logos, favicons, or SEO-related files like robots.txt and site verification files.

  1. Create the public directory in your project root if it doesn’t exist.

  2. Place an image file inside it, for example, logo.svg.

  3. You can now reference this image in your components using a root-relative path (/). For better optimization and accessibility, it’s recommended to use the next/image component.

Let’s update a page (e.g., app/page.tsx) to display the logo:

app/page.tsx
import Link from 'next/link';
import Image from 'next/image'; // Import the next/image component
export default function HomePage() {
return (
<main style={{ padding: '20px' }}>
<h1>Welcome to Our Site!</h1>
<p>Powered by Next.js</p>
{/* Using next/image for optimization */}
<Image
src="/logo.svg" // Path relative to the public directory
alt="Our Company Logo"
width={150} // Required width
height={50} // Required height
priority // Optional: Load image sooner if it's above the fold
/>
<br />
<Link href="/about">About Us</Link>
</main>
);
}

Why use next/image?

  • Automatic Optimization: Serves images in modern formats (like WebP) and resizes them for different devices.
  • Prevent Layout Shift: Automatically reserves space for the image while it loads.
  • Faster Loading: Optimizes images for performance.

While you can use a standard <img> tag (<img src="/logo.svg" alt="...">), the next/image component provides significant advantages.

Run the development server:

npm run dev

Open http://localhost:3000 in your browser. You should see your home page content along with the logo image (logo.svg) served directly from the public directory.

The public directory is also the correct place for files like robots.txt (to instruct web crawlers) or favicon.ico (the small icon shown in browser tabs).