Next JS

Next JS

What is Next.js?

  • Next.js is a full stack web development framework, built on the top of popular JavaScript library React JS
  • It uses React for building user interfaces
  • Provides additional features that enable you to build production-ready applications
  • These features include routing, optimized rendering, data fetching, bundling, compiling, and more
  • Don't need to install additional packages as Next.js provides everything.

History of Next.js

  • Need : challenges in the mid-2010s regarding Server-Side Rendering, Search Engine Optimization (SEO), and the overall setup of complex React applications
  • Intro. in 2016 : Next.js was created by the team at Vercel to tackle these issues
  • Latest version : Next.js 14

Commands to setup Next.js application

  • npx create-next-app@latest my-next-project
  • npm run dev

Next.js File Structure

notion image
  • Inside the src folder, the app folder is responsible for routing. The layout.tsx file used to define a structure that renders consistently across your application
  • public folder for static files like images, fonts, css
 

🚏 Routing

The App Router, introduced in Next.js 13 and enhanced in version 14, brings significant changes to how you define and structure routes in your Next.js applications. Key concepts include:
  • File-system Based Routing: Your application's routing structure is directly mirrored in the app directory. Route segments are represented by folders, and pages by files.
  • Layouts: Layout files in the app directory allow you to create nested layouts for shared UI elements across different routes. These act as wrappers for other components or pages.
  • Server Components: Pages in Next.js are primarily Server Components by default. This means they render on the server, leading to faster initial page loads and improved SEO.
  • Data Fetching with Server Actions: Server Actions provide a way to define functions that execute on the server in response to form submissions or other logic, handling data mutations.
Example: Creating a Basic App Structure
  1. Project Setup: If you don't have an existing project, initiate one with:
    1. Bash
      npx create-next-app@latest my-app
  1. Basic Routing:
    1. app/ page.js # Root route (/) about/ page.js # /about route profile/ page.js # /profile route
Advanced Concepts
  • Dynamic Routes: Use brackets [] in file names to define dynamic routes:
    • app/blog/[slug]/page.js - Matches routes like /blog/hello-world
  • Catch-all Routes: Optional catch-all routes can handle otherwise unmatched paths:
    • app/blog/[[...slug]]/page.js - Matches /blog/, /blog/some-post, /blog/some/nested/path, etc.
  • Data Fetching: Use fetch inside Server Components (or getServerSideProps in specific cases) to get data on the server for your pages. You can also define Server Actions for data updates and interaction.
  • Linking: Use the Link component from next/link for client-side navigation.
Not Found
In Next.js, If the route does not match then the default 404 page will be displayed, if we want to displayed the customize not-found page, we create the not-found file in root directory
Key Points:
  • File Location: The custom "not found" component must be placed in the root of your app directory (e.g., app/not-found.js).
  • Automatic Behavior: This file in the correct place will automatically handle any unmatched routes, replacing the default 404 page.
Example:
JavaScript
// app/not-found.js import Link from 'next/link'; export default function NotFoundPage() { return ( <div> <h1>Oops! Page Not Found (404)</h1> <p>The page you're looking for doesn't seem to exist.</p> <Link href="/"> <a>Go back home</a> </Link> </div> ); }
 

⚡️File Colocation

What is File Colocation?
  • File colocation refers to the ability to place files directly alongside your page components within the app directory. This means you can store related components, styles, tests, and other files near the component they're associated with.
Example:
app/ blog/ page.js // The main page component for the /blog route index.js // A listing of blog posts rendered at /blog styles.module.css // Styles for the blog components post.test.js // Tests for blog post components
Benefits of File Colocation
  • Improved Organization: Keeps closely related files together, enhancing project maintainability.
  • Simplified Imports: You can use relative imports within a directory, making code more readable.
  • Flexibility: While colocation offers organization, Next.js doesn't enforce a strict structure – you can customize your project layout.
Special Note: Only files directly returned by special files like page.js, route.js, loading.js, etc. are publicly accessible routes. The other files are there for organization but are not individual URLs a user can navigate to.

💡Private Folders in Next.js

  • Purpose: Private folders help organize your Next.js project by clearly separating internal implementation details from your application's routing structure. Think of them as 'behind-the-scenes' folders.
  • How to Create: Simply prefix a folder's name with an underscore (_). For example:
    • app/ _helpers/ (Private Folder) page.js (Public route)
  • Key Behavior:
    • Excluded from Routing: Files inside private folders are not treated as routes by Next.js. You cannot access them directly in the browser by typing their URL.
    • Accessible to Other Files: Components within private folders can still be imported and used within components in public folders.
  • Common Use Cases:
    • Organization: Store utility functions, helper components, libraries not directly tied to specific routes.
    • Future-proofing: Avoid conflicts with future Next.js conventions.
    • Separation of Concerns: Differentiate UI rendering logic from internal project structure.
Example:
app/ page.js _components/ Header.js Footer.js _lib/ formatters.js
  • In this structure, 'page.js' is accessible as a route, while the 'Header', 'Footer', and 'formatters' are internal implementation details.

🏘️Route Groups

Route Groups in Next.js
Purpose:
  • Organization: Group related routes together within your project's file structure, even if you don't want the group name reflected in the URL path.
  • Nested Layouts: Create multiple nested layout components at the same route level, including multiple root layouts.
  • Selective Layouts: Apply a specific layout to a subset of routes within a shared route segment.
How to Create a Route Group:
  1. Prefix: Prefix the folder name with an open parenthesis (.
  1. Example: app/(blog). This creates a route group named 'blog'.
Key Behaviors
  • URL Path Exclusion: The route group's name does not become part of the URL path. For example, routes inside the (blog) group would be accessible like:
    • /blog/hello-world
    • /blog/recent-posts
  • Nested Structure: Route groups can be nested within each other.
Example Use Cases
  • Site Sections: Organize routes by distinct website sections (e.g., /blog, /admin, /shop).
  • Team-Based Structure: Group routes according to different teams working on the project.
  • Applying Layouts:
    • Create a layout specifically for the /blog section without affecting other parts of the site.
    • Have multiple side-by-side layouts with their own content at a particular route level.
Important Notes
  • Route groups help manage project file structure and routing logic.
  • They provide a way to control layout behavior without modifying the URL structure.

Layouts