Private folders
This page explains how to use private folders in Next.js to exclude specific directories from routing.
What are private folders?
While standard folders in Next.js automatically become route segments, sometimes you need directories that store utilities or components without creating corresponding routes. Private folders allow you to organize your code without affecting the URL structure.
Creating private folders
To create a private folder, prefix the folder name with an underscore (_
). All files and subfolders within this directory become inaccessible through URL routes.
Here’s an example component in a private folder:
Directoryapp/
Directory_utils/
- helpers.ts
- page.tsx
- page.tsx
/
export default function PrivateRoute() { return <h1>You cannot view this in the browser</h1>;}
Attempting to access this component at localhost:3000/_lib
results in a 404 error because Next.js excludes the private folder from routing.
Use cases
Private folders help you:
- Separate UI logic from routing logic
- Organize internal files consistently
- Group related files in your code editor
- Avoid conflicts with Next.js file naming conventions
URL encoding for underscores
If you need an actual underscore in your URL path, use the URL-encoded value %5F
. For example:
Directoryapp/
Directory%5Futils/
- helpers.ts
- page.tsx
/
- page.tsx
/
This prevents the folder from being treated as private. You can now access the component at localhost:3000/_utils
.
Alternative approaches
Private folders are optional. You do not have to use them. Alternatively, you can organize your Next.js project using:
- File colocation
- Directory structure outside the app folder