Sling Academy
Home/Next.js/Next.js: How to Access Files in the Public Folder

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

Last updated: January 02, 2024

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.

Next Article: How to Set Placeholder for Image in Next.js

Previous Article: Choosing the Right Framework: Next.js vs Remix (2024)

Series: The First Steps to Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported
  • Fixing Next.js Error: Only Absolute URLs Are Supported