Basic Routes and Index Files
Basic Routes and Index Files
Section titled “Basic Routes and Index Files”Introduction
Section titled “Introduction”Understanding how basic routes and index files work is fundamental to mastering Next.js routing. This topic covers how to create simple pages and how index files serve as the default route for a directory.
Why do we need this?
Section titled “Why do we need this?”Every web application needs a homepage and other static pages. Knowing how to create these basic routes efficiently allows you to build the foundation of your application’s navigation structure.
Problem Statement
Section titled “Problem Statement”Without understanding index files, developers might create redundant routes or confusion about how to access the main page of a section (e.g., /blog vs /blog/index).
Real World Story
Section titled “Real World Story”You’re building a news website and need sections for different categories like politics, sports, and technology. Each section should have a landing page that shows recent articles in that category. By using index files, you can create /politics, /sports, and /technology as landing pages without creating redundant files like /politics/index.
Real World Analogy
Section titled “Real World Analogy”Think of index files like the main table in a room:
- When you enter a room (route section), you naturally look at the main table first
- The main table (index file) gives you an overview of what’s in that section
- Side tables (other files in the directory) provide more specific information
- Just as you wouldn’t label every table in a room as “Table 1”, “Table 2”, etc., you don’t need to name every section’s main page with a redundant filename
Visual Explanation
Section titled “Visual Explanation”pages/├── index.js → / (Homepage)├── about.js → /about (About page)├── blog/│ ├── index.js → /blog (Blog landing page)│ ├── first-post.js → /blog/first-post (Specific post)│ └── guide.md → /blog/guide (Static file)└── api/ └── hello.js → /api/hello (API endpoint)Internal Working
Section titled “Internal Working”When a request comes to the Next.js server:
- The URL path is matched against files in the
pages/directory - For a path like
/blog:- Next.js looks for
pages/blog/index.js - If found, it uses that component as the route handler
- If not found, it looks for
pages/blog.js(treated as a page)
- Next.js looks for
- For a path like
/:- Next.js looks for
pages/index.js
- Next.js looks for
- For a path like
/about:- Next.js looks for
pages/about.js
- Next.js looks for
Technical Explanation
Section titled “Technical Explanation”Route Resolution Priority
Section titled “Route Resolution Priority”Next.js follows this order when resolving a path:
- Check for
pages/<path>/index.js(directory index) - Check for
pages/<path>.js(page file) - Check for dynamic routes that match the path
- Check for catch-all routes
- If nothing matches, return 404
Special Case: Root Route
Section titled “Special Case: Root Route”- The root route
/can only be mapped topages/index.js - There is no
pages/.jsfile (invalid filename)
Index Files in Nested Directories
Section titled “Index Files in Nested Directories”pages/dashboard/index.js→/dashboardpages/settings/account/index.js→/settings/account- If both
pages/settings/account.jsandpages/settings/account/index.jsexist, theindex.jstakes precedence for/settings/account
Static Files in pages/
Section titled “Static Files in pages/”Note: Files in pages/ that are not .js, .jsx, .ts, or .tsx are not treated as pages (unless using the app router with certain extensions). However, static files like .md or .txt in pages/ will be served as static assets only if they’re in the public/ directory or handled via custom server logic.
Mermaid Diagram 1: Route Resolution Flow
Section titled “Mermaid Diagram 1: Route Resolution Flow”flowchart TD A[Request URL: /blog] --> B{Does pages/blog/index.js exist?} B -->|Yes| C[Use pages/blog/index.js] B -->|No| D{Does pages/blog.js exist?} D -->|Yes| E[Use pages/blog.js] D -->|No| F[Check dynamic routes] F -->|Match| G[Use matching dynamic route] F -->|No match| H[Return 404]Mermaid Diagram 2: Index File vs Page File
Section titled “Mermaid Diagram 2: Index File vs Page File”flowchart LR A[pages/blog/index.js] --> B[Route: /blog] C[pages/blog.js] --> D[Route: /blog] style B stroke:#f66,stroke-width:2px style D stroke:#66f,stroke-width:2px classDef index fill:#f9f,stroke:#333; classDef page fill:#bbf,stroke:#333; class B index class D pageExplanation
Section titled “Explanation”Imagine you’re organizing a library. Instead of having a complex catalog system, you simply arrange books on shelves where the shelf location tells you exactly what book you’ll find. The main shelf in each section shows you what’s available in that section - that’s your index file.
Real-world Analogy
Section titled “Real-world Analogy”Like a shopping mall directory:
- Main directory shows: “Food Court”, “Clothing”, “Electronics”
- Each section has its own directory showing specific stores
- You don’t need a separate map for every single store - the hierarchy guides you
Technical Explanation
Section titled “Technical Explanation”Next.js uses the file system as its router. When you request a URL, it maps that path to the file system:
/→pages/index.js/about→pages/about.js/blog/→pages/blog/index.js(note the trailing slash is optional)/blog/post→pages/blog/post.js
Diagram 1: Basic Route Mapping
Section titled “Diagram 1: Basic Route Mapping”flowchart TD A[User visits /] --> B[Loads pages/index.js] C[User visits /about] --> D[Loads pages/about.js] E[User visits /blog] --> F[Loads pages/blog/index.js] G[User visits /blog/post] --> H[Loads pages/blog/post.js]Diagram 2: Index File Precedence
Section titled “Diagram 2: Index File Precedence”flowchart TD A[Request: /blog] --> B{Is pages/blog/index.js present?} B -->|Yes| C[Use pages/blog/index.js] B -->|No| D{Is pages/blog.js present?} D -->|Yes| E[Use pages/blog.js] D -->|No| F[Check dynamic routes]Diagram 3: Nested Directory Structure
Section titled “Diagram 3: Nested Directory Structure”flowchart LR A[pages/] --> B[index.js] --> C[/] A --> D[about.js] --> E[/about] A --> F[blog/] --> G[index.js] --> H[/blog] F --> I[first-post.js] --> J[/blog/first-post] A --> K[api/] --> L[hello.js] --> M[/api/hello]Diagram 4: Data Flow in Basic Routes
Section titled “Diagram 4: Data Flow in Basic Routes”sequenceDiagram participant Browser as Browser participant NextJS as Next.js participant Server as Server Browser->>NextJS: GET /about NextJS->>NextJS: Route to pages/about.js NextJS->>Server: Fetch component code Server-->>NextJS: Return component NextJS->>Browser: Send HTML + JS Browser->>Browser: Render React component Browser->>User: Display About pageBasic Example
Section titled “Basic Example”Creating a simple homepage and about page:
export default function Home() { return ( <div> <h1>Welcome to My Site</h1> <p>This is the homepage.</p> <a href="/about">Learn About Us</a> </div> );}
// pages/about.jsexport default function About() { return ( <div> <h1>About Us</h1> <p>We build amazing websites.</p> <a href="/">Back to Home</a> </div> );}Intermediate Example
Section titled “Intermediate Example”Creating a blog section with index file:
import Link from 'next/link';
export default function Blog() { return ( <div> <h1>Blog</h1> <p>Latest posts:</p> <ul> <li> <Link href="/blog/first-post"> <a>My First Post</a> </Link> </li> <li> <Link href="/blog/second-post"> <a>My Second Post</a> </Link> </li> </ul> </div> );}
// pages/blog/first-post.jsexport default function FirstPost() { return ( <div> <h1>My First Post</h1> <p>This is the content of my first blog post.</p> <Link href="/blog"> <a>← Back to Blog</a> </Link> </div> );}Advanced Example
Section titled “Advanced Example”Creating nested sections with index files:
export default function Dashboard() { return ( <div> <h1>Dashboard Overview</h1> <p>Welcome to your dashboard.</p> </div> );}
// pages/dashboard/analytics/index.jsexport default function Analytics() { return ( <div> <h1>Analytics</h1> <p>View your data and metrics here.</p> </div> );}
// pages/dashboard/settings/index.jsexport default function Settings() { return ( <div> <h1>Settings</h1> <p>Configure your preferences.</p> </div> );}Production Example
Section titled “Production Example”In production, basic routes are optimized:
- Static routes (
/,/about,/contact) can be pre-rendered at build time if they don’t require data fetching - The HTML is served directly from CDN (on Vercel) for fastest performance
- Client-side navigation between basic routes is instantaneous
- Search engines can easily crawl and index these predictable URLs
Folder Structure
Section titled “Folder Structure”pages/├── index.js # Homepage (/)├── about.js # About page (/about)├── contact.js # Contact page (/contact)├── blog/│ ├── index.js # Blog landing page (/blog)│ ├── [slug].js # Individual blog post (/blog/:slug)│ └── feed.xml # RSS feed (static file)├── docs/│ ├── index.js # Documentation homepage (/docs/)│ ├── getting-started.js # Getting started guide (/docs/getting-started)│ └── advanced/│ └── index.js # Advanced topics landing page (/docs/advanced/)├── api/│ ├── index.js # API root (/api/)│ ├── users/│ │ └── index.js # Users collection endpoint (/api/users/)│ └── posts/│ └── [id].js # Individual post endpoint (/api/posts/:id)└── [username].js # User profile pages (dynamic route, /:username)Best Practices
Section titled “Best Practices”- Use index.js for section landing pages: Makes
/sectionaccessible - Keep homepage simple:
pages/index.jsshould be lightweight for fastest load - Leverage index files for nested sections:
/section/subsectionviapages/section/subsection/index.js - Avoid redundant naming: Don’t create both
pages/blog.jsandpages/blog/index.jsunless you have a specific reason (and understand precedence) - Use descriptive names: Even for index files, the directory name provides context
- Consider using
.mdor other static files inpublic/: For actual static content rather than putting inpages/ - Test route accessibility: Ensure all important sections are reachable via intuitive URLs
- Document your route structure: Especially for larger teams
- Use consistent casing: Stick to kebab-case or snake_case for URL predictability
- Remember the root route: Only
pages/index.jscan serve/
Common Mistakes
Section titled “Common Mistakes”- Forgetting to create index.js for sections: Results in
/sectionreturning 404 - Confusing
pages/section.jswithpages/section/index.js: Leads to unexpected behavior - Placing components in pages/: They become accessible as routes (e.g.,
pages/components/Button.js→/components/Button) - Using uppercase in filenames: Can cause issues on case-sensitive file systems
- Forgetting to restart dev server: After adding new pages or folders
- Assuming all files in pages/ are routes: Only
.js,.jsx,.ts,.tsxfiles are considered for routing (by default) - Overlooking that index.js takes precedence: Leads to confusion when both
section.jsandsection/index.jsexist - Not considering trailing slashes: Next.js handles them, but be consistent for SEO
- Trying to access non-existent index files: Results in 404, not fallback to parent
- Misunderstanding that index.js only works for directories: It doesn’t work for files (e.g.,
pages/blog/index.jsis for/blog, not/blog/index)
Performance Notes
Section titled “Performance Notes”- Basic routes are fast: Especially when statically optimized
- HTML size: Keep the initial HTML small for fastest first paint
- CSS delivery: Consider inlining critical CSS for above-the-fold content
- JavaScript: Minimize render-blocking JavaScript in the initial load
- Images: Optimize and use
next/imagefor automatic optimization - Caching: Static routes can be cached aggressively by CDNs
- Client-side navigation: Instantaneous between basic routes
- Preloading: Use
next/linkprefetching for likely next navigations
Security Notes
Section titled “Security Notes”- Input validation: Even basic routes should validate any query parameters
- CSRF protection: Not typically needed for GET-only basic routes, but important for forms
- XSS prevention: Sanitize any user-generated content before rendering
- Information disclosure: Don’t expose sensitive information in basic routes (use authentication/authorization)
- Rate limiting: Generally not needed for public basic routes unless they perform expensive operations
- Secure headers: Implement via
_headersfile or middleware for security headers (CSP, HSTS, etc.)
SEO Considerations
Section titled “SEO Considerations”- Descriptive URLs: Use meaningful names for your pages and sections
- Consistent trailing slashes: Choose one style and stick to it (Next.js can enforce via
next.config.js) - Canonical URLs: Ensure each piece of content has one preferred URL
- Title and meta description: Use
<Head>to set unique, descriptive titles and descriptions - Heading structure: Use proper h1-h6 hierarchy for content
- Image alt text: Provide descriptive alt attributes for all images
- Internal linking: Use
next/linkfor crawlable internal links - Sitemap: Generate a sitemap based on your routes for search engines
- Robots.txt: Control what search engines can crawl via
public/robots.txt - Pagination: Use proper
rel="next"andrel="prev"for paginated content (if applicable)
Interview Questions
Section titled “Interview Questions”- How does Next.js determine the route for
pages/about.js? - What is the difference between accessing
/blogand/blog/indexin a Next.js application? - What happens if you create both
pages/blog.jsandpages/blog/index.js? - How do you create a homepage in Next.js?
- What files does Next.js consider when resolving a route?
- How does Next.js handle the root route
/? - What is the purpose of index files in Next.js routing?
- How would you create a section landing page for
/products? - How do static routes differ from dynamic routes in terms of performance?
- How does Next.js optimize basic routes for production?
-
Which file creates the route
/? a)pages/root.jsb)pages/index.jsc)pages/home.jsd)pages/main.jsAnswer
-
If you have both
pages/blog.jsandpages/blog/index.js, which one serves/blog? a)pages/blog.js(takes precedence) b)pages/blog/index.js(takes precedence) c) Both serve the route (undefined behavior) d) Neither; you must choose oneAnswer
-
What is the route for
pages/admin/dashboard/index.js? a)/adminb)/admin/dashboardc)/admin/dashboard/indexd)/admin/dashboard/index.jsAnswer
-
Which of the following is NOT a valid way to create an about page route? a)
pages/about.jsb)pages/about/index.jsc)pages/about/contact.js(this would be/about/contact) d)pages/aboutus.js(this would be/aboutus)Answer
-
How does Next.js handle a request for
/blogwhenpages/blog/index.jsexists? a) Looks forpages/blog.jsfirst b) Usespages/blog/index.jsdirectly c) Returns a 404 d) Redirects to/blog/indexAnswer
-
Which file would create the route
/docs/getting-started? a)pages/docs/getting-started.jsb)pages/docs/index.js+pages/docs/getting-started/index.jsc)pages/docs/getting-started/index.jsd)pages/docs/getting-started/.[index].jsAnswer
-
What happens if you request
/productsand onlyproducts/[id].jsexists? a) Shows the product page with id=“products” b) Returns 404 (no matching route) c) Shows a list of all products d) Redirects to/products/indexAnswer
-
Which file creates the route
/api/users? a)pages/api/users.jsb)pages/api/users/index.jsc) Both a and b (with b taking precedence) d) Neither; you needpages/api/users/[id].jsAnswer
-
How does Next.js treat files in the
pages/directory that are not.js,.jsx,.ts, or.tsx? a) They are automatically routed based on filename b) They are ignored for routing purposes c) They cause a build error d) They are treated as static files and served at their pathAnswer
-
What is the file for the root route (
/)? a)pages/root.jsb)pages/index.jsc)pages/home.jsd) There is no specific file; it’s configured innext.config.jsAnswer
Practice Exercise
Section titled “Practice Exercise”- Create a new Next.js project called
basic-routing-exercise - Create the following pages:
- Homepage (
/) - About page (
/about) - Services page (
/services) - Contact page (
/contact)
- Homepage (
- Create a
blog/section with:- Blog landing page (
/blog) - Individual blog post (
/blog/[slug])
- Blog landing page (
- Create an
api/section with:- API root (
/api/) - Users endpoint (
/api/users/)
- API root (
- Link between pages using
next/link - Test all routes in the development server
- Verify that accessing
/blogshows the blog landing page (not 404) - Verify that accessing
/api/usersshows the API endpoint response
Mini Project
Section titled “Mini Project”Build a simple documentation website:
- Create a homepage (
/) with site title and navigation - Create a
docs/section for documentation:- Documentation homepage (
/docs/) - Getting started guide (
/docs/getting-started) - API reference (
/docs/api/) - Tutorials (
/docs/tutorials/)
- Documentation homepage (
- Create a
blog/section:- Blog homepage (
/blog/) - Individual blog posts (
/blog/[slug])
- Blog homepage (
- Create an
api/section for dynamic content:- Get all articles (
/api/articles) - Get article by ID (
/api/articles/[id])
- Get all articles (
- Implement navigation between all sections
- Add meta tags for SEO on important pages
- Ensure all routes are accessible and return appropriate content
- Test the development server to verify everything works
- Consider adding a search page (
/search) that uses query parameters - Add a 404 page for handling invalid routes
Summary
Section titled “Summary”In this topic, you learned how to create basic routes and use index files in Next.js. You understand how the file-system routing maps files to URLs, how index files serve as section landing pages, and how to structure your pages directory for intuitive and maintainable routing.
Cheat Sheet
Section titled “Cheat Sheet”# Basic Route Examplespages/index.js → / (Homepage)pages/about.js → /aboutpages/contact.js → /contact
# Index Files (Section Landing Pages)pages/blog/index.js → /blogpages/products/index.js → /productspages/docs/index.js → /docs
# Nested Index Filespages/admin/index.js → /adminpages/admin/dashboard/index.js → /admin/dashboardpages/settings/account/index.js → /settings/account
# API Routes with Index Filespages/api/index.js → /api/pages/api/users/index.js → /api/users/pages/api/posts/[id].js → /api/posts/:id
# Route Resolution Priority1. pages/<path>/index.js (if <path> is a directory)2. pages/<path>.js (if <path> is a file)3. Dynamic routes4. Catch-all routes5. 404
# Special Casepages/index.js → / (only way to get root route)Related Topics
Section titled “Related Topics”- Dynamic Routes and Parameter Handling
- Catch-all and Optional Catch-all Routes
- API Routes and Middleware
- Route Groups (App Router)
- Internationalized Routing (i18n)
- Redirects and Rewrites