File colocation
This page explains how file colocation works in Next.js and how to safely organize files within route segments.
Route accessibility
Although Next.js uses a file system-based router where each folder represents a route segment that maps to a URL path, a route becomes publicly accessible only when you add a page.js
or page.tsx
file to it and it contains a default exported React component.
Consider a dashboard route with a line chart component:
export default function LineChart() { return <h1>Line chart</h1>;}
Accessing /dashboard
in the browser will return a 404 “page not found” error because there is no page.tsx
file in the route segment.
Even with a page.tsx
file present, components must be default exported. If you define a component without exporting it, it won’t be accessible:
function LineChart() { return <h1>Line chart</h1>;}
This removes the 404 error but results in a browser error: “The default export is not a React component.”
Route requirements
The correct implementation requires a default exported component in page.tsx
:
export default function Dashboard() { return <h1>Dashboard</h1>;}
The /dashboard
route will now display “Dashboard”, while the bar chart component remains inaccessible through the URL.
Key takeaway
Files can be safely colocated inside route segments in the app directory without becoming publicly accessible routes themselves.
File organization options
While you can keep files in the app directory, it’s not mandatory. Some developers prefer storing files outside the app directory—perhaps in the src
folder with a separate components
folder for UI components. Libraries like ShadcN use this approach, which works equally well.