--- title: "Next.js" section: "Network Services" sectionSlug: "network-services-pentesting" sourcePath: "src/network-services-pentesting/pentesting-web/nextjs.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/pentesting-web/nextjs.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0" --- # Next.js ## General Architecture of a Next.js Application ### Typical File Structure A Next.js project commonly follows a file and directory structure that supports routing, request handlers, and static assets. The exact layout depends on whether it uses the App Router, Pages Router, or both. The following example uses the App Router:[[12]](#references) ```lua my-nextjs-app/ ├── node_modules/ ├── public/ │ ├── images/ │ │ └── logo.png │ └── favicon.ico ├── app/ │ ├── api/ │ │ └── hello/ │ │ └── route.ts │ ├── layout.tsx │ ├── page.tsx │ ├── about/ │ │ └── page.tsx │ ├── dashboard/ │ │ ├── layout.tsx │ │ └── page.tsx │ ├── components/ │ │ ├── Header.tsx │ │ └── Footer.tsx │ ├── styles/ │ │ ├── globals.css │ │ └── Home.module.css │ └── utils/ │ └── api.ts ├── .env.local ├── next.config.js ├── tsconfig.json ├── package.json ├── README.md └── yarn.lock / package-lock.json ``` ### Core Directories and Files - **public/:** Hosts static assets such as images, fonts, and other files. Files here are accessible at the root path (`/`). - **app/:** Central directory for your application’s pages, layouts, components, and API routes. Embraces the **App Router** paradigm, enabling advanced routing features and server-client component segregation. - **app/layout.tsx:** Defines the root layout for your application, wrapping around all pages and providing consistent UI elements like headers, footers, and navigation bars. - **app/page.tsx:** Serves as the entry point for the root route `/`, rendering the home page. - **app/[route]/page.tsx:** Handles static and dynamic routes. Each folder within `app/` represents a route segment, and `page.tsx` within those folders corresponds to the route's component. - **app/api/:** Common location for App Router Route Handlers. These are the App Router equivalent of Pages Router API Routes; their deployment runtime depends on the hosting configuration.[[12]](#references) - **app/components/:** Houses reusable React components that can be utilized across different pages and layouts. - **app/styles/:** Contains global CSS files and CSS Modules for component-scoped styling. - **app/utils/:** Includes utility functions, helper modules, and other non-UI logic that can be shared across the application. - **.env.local:** Stores local environment variables. The default template ignores `.env*` files, but verify repository ignore rules rather than assuming the file cannot be committed.[[14]](#references) - **next.config.js:** Customizes Next.js behavior, including webpack configurations, environment variables, and security settings. - **tsconfig.json:** Configures TypeScript settings for the project, enabling type checking and other TypeScript features. - **package.json:** Manages project dependencies, scripts, and metadata. - **README.md:** Provides documentation and information about the project, including setup instructions, usage guidelines, and other relevant details. - **yarn.lock / package-lock.json:** Locks the project’s dependencies to specific versions, ensuring consistent installations across different environments. ## Client-Side in Next.js ### File-Based Routing in the `app` Directory The `app` directory is the cornerstone of routing in the latest Next.js versions. It leverages the filesystem to define routes, making route management intuitive and scalable.
Handling the Root Path / **File Structure:** ```text my-nextjs-app/ ├── app/ │ ├── layout.tsx │ └── page.tsx ├── public/ ├── next.config.js └── ... ``` **Key Files:** - **`app/page.tsx`**: Handles requests to the root path `/`. - **`app/layout.tsx`**: Defines the layout for the application, wrapping around all pages. **Implementation:** ```tsx // app/page.tsx export default function HomePage() { return (

Welcome to the Home Page!

This is the root route.

); } ``` **Explanation:** - **Route Definition:** The `page.tsx` file directly under the `app` directory corresponds to the `/` route. - **Rendering:** This component renders the content for the home page. - **Layout Integration:** The `HomePage` component is wrapped by the `layout.tsx`, which can include headers, footers, and other common elements.
Handling Other Static Paths **Example: `/about` Route** **File Structure:** ```text my-nextjs-app/ ├── app/ │ ├── about/ │ │ └── page.tsx │ ├── layout.tsx │ └── page.tsx ├── public/ ├── next.config.js └── ... ``` **Implementation:** ```tsx // app/about/page.tsx export default function AboutPage() { return (

About Us

Learn more about our mission and values.

) } ``` **Explanation:** - **Route Definition:** The `page.tsx` file inside the `about` folder corresponds to the `/about` route. - **Rendering:** This component renders the content for the about page.
Dynamic Routes Dynamic routes allow handling paths with variable segments, enabling applications to display content based on parameters like IDs, slugs, etc. **Example: `/posts/[id]` Route** **File Structure:** ```text my-nextjs-app/ ├── app/ │ ├── posts/ │ │ └── [id]/ │ │ └── page.tsx │ ├── layout.tsx │ └── page.tsx ├── public/ ├── next.config.js └── ... ``` **Implementation:** ```tsx // app/posts/[id]/page.tsx import { useRouter } from 'next/navigation'; interface PostProps { params: { id: string }; } export default function PostPage({ params }: PostProps) { const { id } = params; // Fetch post data based on 'id' return (

Post #{id}

This is the content of post {id}.

); } ``` **Explanation:** - **Dynamic Segment:** `[id]` denotes a dynamic segment in the route, capturing the `id` parameter from the URL. - **Accessing Parameters:** The `params` object contains the dynamic parameters, accessible within the component. - **Route Matching:** Any path matching `/posts/*`, such as `/posts/1`, `/posts/abc`, etc., will be handled by this component.
Nested Routes Next.js supports nested routing, allowing for hierarchical route structures that mirror the directory layout. **Example: `/dashboard/settings/profile` Route** **File Structure:** ```text my-nextjs-app/ ├── app/ │ ├── dashboard/ │ │ ├── settings/ │ │ │ └── profile/ │ │ │ └── page.tsx │ │ └── page.tsx │ ├── layout.tsx │ └── page.tsx ├── public/ ├── next.config.js └── ... ``` **Implementation:** ```tsx // app/dashboard/settings/profile/page.tsx export default function ProfileSettingsPage() { return (

Profile Settings

Manage your profile information here.

); } ``` **Explanation:** - **Deep Nesting:** The `page.tsx` file inside `dashboard/settings/profile/` corresponds to the `/dashboard/settings/profile` route. - **Hierarchy Reflection:** The directory structure reflects the URL path, enhancing maintainability and clarity.
Catch-All Routes Catch-all routes handle multiple nested segments or unknown paths, providing flexibility in route handling. **Example: `/*` Route** **File Structure:** ```text my-nextjs-app/ ├── app/ │ ├── [...slug]/ │ │ └── page.tsx │ ├── layout.tsx │ └── page.tsx ├── public/ ├── next.config.js └── ... ``` **Implementation:** ```tsx // app/[...slug]/page.tsx interface CatchAllProps { params: { slug: string[] } } export default function CatchAllPage({ params }: CatchAllProps) { const { slug } = params const fullPath = `/${slug.join("/")}` return (

Catch-All Route

You have navigated to: {fullPath}

) } ``` **Explanation:** - **Catch-All Segment:** `[...slug]` captures all remaining path segments as an array. - **Usage:** Useful for handling dynamic routing scenarios like user-generated paths, nested categories, etc. - **Route Matching:** Paths like `/anything/here`, `/foo/bar/baz`, etc., are handled by this component.
### Potential Client-Side Vulnerabilities While Next.js provides a secure foundation, improper coding practices can introduce vulnerabilities. Key client-side vulnerabilities include:
Cross-Site Scripting (XSS) XSS attacks occur when malicious scripts are injected into trusted websites. Attackers can execute scripts in users' browsers, stealing data or performing actions on behalf of the user. **Example of Vulnerable Code:** ```jsx // Dangerous: Injecting user input directly into HTML function Comment({ userInput }) { return
} ``` **Why It's Vulnerable:** Using `dangerouslySetInnerHTML` with untrusted input allows attackers to inject malicious scripts.
Client-Side Template Injection Occurs when user inputs are improperly handled in templates, allowing attackers to inject and execute templates or expressions. **Example of Vulnerable Code:** ```jsx import React from "react" import ejs from "ejs" function RenderTemplate({ template, data }) { const html = ejs.render(template, data) return
} ``` **Why It's Vulnerable:** If `template` or `data` includes malicious content, it can lead to execution of unintended code.
Client Path Traversal Client-side path traversal (CSPT) occurs when attacker-controlled input is interpolated into a client-generated request path. Dot segments can redirect an otherwise legitimate, credentialed request to a different application endpoint. When that endpoint changes state, CSPT can provide a CSRF-like primitive; unlike server-side filesystem traversal, the manipulated path is an HTTP route. **Example of Vulnerable Code:** A Next.js application allows users to upload and download files. The download feature is implemented on the client side, where users can specify the file path to download. ```jsx // pages/download.js import { useState } from "react" export default function DownloadPage() { const [filePath, setFilePath] = useState("") const handleDownload = () => { fetch(`/api/files/${filePath}`) .then((response) => response.blob()) .then((blob) => { const url = window.URL.createObjectURL(blob) const a = document.createElement("a") a.href = url a.download = filePath a.click() }) } return (

Download File

setFilePath(e.target.value)} placeholder="Enter file path" />
) } ``` #### Attack Scenario 1. **Attacker's Objective**: Perform a CSRF attack to delete a critical file (e.g., `admin/config.json`) by manipulating the `filePath`. 2. **Exploiting CSPT**: - **Malicious Input**: The attacker crafts a URL with a manipulated `filePath` such as `../deleteFile/config.json`. - **Resulting API Call**: The client-side code makes a request to `/api/files/../deleteFile/config.json`. - **Server's Handling**: If the server does not validate the `filePath`, it processes the request, potentially deleting or exposing sensitive files. 3. **Executing CSRF**: - **Crafted Link**: The attacker sends the victim a link or embeds a malicious script that triggers the download request with the manipulated `filePath`. - **Outcome**: The victim unknowingly executes the action, leading to unauthorized file access or deletion. #### Why It's Vulnerable - **Lack of Input Validation**: The client-side allows arbitrary `filePath` inputs, enabling path traversal. - **Trusting Client Inputs**: The server-side API trusts and processes the `filePath` without sanitization. - **Potential API Actions**: If the API endpoint performs state-changing actions (e.g., delete, modify files), it can be exploited via CSPT.
### Recon: static export route discovery via _buildManifest When `nextExport`/`autoExport` are true (static export), Next.js exposes the `buildId` in the HTML and serves a build manifest at `/_next/static//_buildManifest.js`. The `sortedPages` array and route→chunk mapping there enumerate every prerendered page without brute force.[[5]](#references) - Grab the buildId from the root response (often printed at the bottom) or from `