Next.js: How to Access Files in the Public Folder

Updated: January 2, 2024 By: Guest Contributor Post a comment

Introduction

Handling static files efficiently is vital in web applications, and Next.js simplifies this with its public directory. This guide covers how to access and utilize files kept in the public folder using Next.js 13 or newer syntaxes.

Understanding the Public Directory

In Next.js, the public directory is a special folder at the root of your project. Any static assets placed here can be accessed directly via the browser using a path relative to your site’s base URL.

// Directory Structure

- public/
  - images/
    - logo.png
- pages/
  - index.js
...

To access the logo.png in a component, you simply use the path /images/logo.png:

<Image src="/images/logo.png" alt="Company Logo" />

Access Static Files in Next.js

Use the built-in Image component for optimized image loading:

import Image from 'next/image';

function Logo() {
  return (
    <Image
      src="/images/logo.png"
      alt="Logo"
      width={150}
      height={150}
    />
  );
}

For non-image assets like documents or downloads, reference the file path directly in the href attribute of an anchor tag:

<a href="/files/my-file.pdf" download>Download My File</a>

Using Static Files in CSS

Static assets can also be used in CSS files or JS style objects:

// In a CSS file
.background-image {
  background-image: url('/images/background.jpg');
}

// In a JSX styled object
const backgroundStyle = {
  backgroundImage: 'url(/images/background.jpg)',
};

<div style={backgroundStyle} />

Advanced Usage

When working with localized paths or i18n, you may need dynamic path generation for assets:

import { useRouter } from 'next/router';

function LocalizedImage() {
  const { locale } = useRouter();
  const imagePath = `/images/logo-${locale}.png`;

  return <Image src={imagePath} alt="Localized Logo" width={150} height={150} />;
}

To handle assets for various screen resolutions, you can use the srcSet attribute:

<img
  src="/images/logo.png"
  srcSet="/images/logo-2x.png 2x, /images/logo-3x.png 3x"
  alt="Responsive Logo"
/>

Serving Files from the API

If you need more control over file distribution, consider serving files through an API endpoint:

export default function handler(req, res) {
  const filePath = path.resolve('.', 'public', 'files', 'my-file.pdf');
  res.sendFile(filePath);
}

Security Considerations

Don’t forget that all files in the public directory are accessible to anyone. Ensure sensitive data is stored securely elsewhere and not in the public folder.

Conclusion

This tutorial provided insights into leveraging the public directory in Next.js 13+. We discussed various methods for loading and serving static assets, ensuring an effective way to manage files in a Next.js application.