Next.js - Static File Serving
Next.js - Serving Static Files
Section titled “Next.js - Serving Static Files”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.pngcan be accessed at/my-image.png.public/css/style.csscan be accessed at/css/style.css.public/robots.txtcan 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.
Example: Adding a Logo
Section titled “Example: Adding a Logo”-
Create the
publicdirectory in your project root if it doesn’t exist. -
Place an image file inside it, for example,
logo.svg. -
You can now reference this image in your components using a root-relative path (
/). For better optimization and accessibility, it’s recommended to use thenext/imagecomponent.
Let’s update a page (e.g., app/page.tsx) to display the logo:
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.
Start Development Server
Section titled “Start Development Server”Run the development server:
npm run devVerify Output
Section titled “Verify Output”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).