======================== CODE SNIPPETS ======================== TITLE: Initializing Next.js Project with Jest Example (Quickstart) DESCRIPTION: This command quickly initializes a new Next.js project using the `create-next-app` utility, pre-configured with the `with-jest` example. It sets up a ready-to-use environment for unit and snapshot testing with Jest, streamlining the setup process. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest --example with-jest with-jest-app ``` ---------------------------------------- TITLE: Initializing a Next.js Project with create-next-app (Bash) DESCRIPTION: This command initializes a new Next.js application using `create-next-app`, an official tool that automates project setup. It prompts the user for configuration choices like TypeScript, ESLint, and Tailwind CSS, then installs all necessary dependencies. This is the recommended method for starting new Next.js projects. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest ``` ---------------------------------------- TITLE: Initializing Next.js Project with Cypress Example (Bash) DESCRIPTION: This command quickly sets up a new Next.js project pre-configured with Cypress for testing, leveraging the `with-cypress` example from the Next.js repository. It's ideal for a rapid development start. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/04-cypress.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest --example with-cypress with-cypress-app ``` ---------------------------------------- TITLE: Manually Installing Playwright (Bash) DESCRIPTION: These commands initiate the Playwright setup process for a project, guiding the user through configuration prompts and generating necessary files like `playwright.config.ts`. Users can choose their preferred package manager. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/03-playwright.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm init playwright ``` LANGUAGE: bash CODE: ``` yarn create playwright ``` LANGUAGE: bash CODE: ``` pnpm create playwright ``` ---------------------------------------- TITLE: Generating Jest Configuration File (Manual Setup) DESCRIPTION: This command initiates the Jest setup wizard, which interactively guides the user through creating a basic `jest.config.ts` or `jest.config.js` file. This file will contain the initial configuration for Jest in the project, which can then be further customized. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_2 LANGUAGE: bash CODE: ``` npm init jest@latest ``` LANGUAGE: bash CODE: ``` yarn create jest@latest ``` LANGUAGE: bash CODE: ``` pnpm create jest@latest ``` ---------------------------------------- TITLE: create-next-app Interactive Prompts (Terminal) DESCRIPTION: This snippet displays the interactive prompts presented by `create-next-app` during the automatic installation process. Users are asked to configure project name, TypeScript, ESLint, Tailwind CSS, `src` directory usage, App Router, and import aliases. These choices determine the initial setup of the Next.js application. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_1 LANGUAGE: txt CODE: ``` What is your project named? my-app Would you like to use TypeScript? No / Yes Would you like to use ESLint? No / Yes Would you like to use Tailwind CSS? No / Yes Would you like to use `src/` directory? No / Yes Would you like to use App Router? (recommended) No / Yes Would you like to customize the default import alias (@/*)? No / Yes What import alias would you like configured? @/* ``` ---------------------------------------- TITLE: Installing Jest and React Testing Library Dependencies (Manual Setup) DESCRIPTION: These commands install the necessary development dependencies for setting up Jest with Next.js. This includes Jest itself, `jest-environment-jsdom` for a browser-like DOM environment, and `@testing-library/react` and `@testing-library/jest-dom` for React component testing utilities and custom Jest matchers. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom ``` LANGUAGE: bash CODE: ``` yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom ``` LANGUAGE: bash CODE: ``` pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom ``` ---------------------------------------- TITLE: Running ESLint Lint Command (Bash) DESCRIPTION: This command executes the `lint` script defined in `package.json` using `yarn`. Running this command will either start the linting process or guide you through the initial ESLint installation and configuration if it's not already set up. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/02-eslint.mdx#_snippet_1 LANGUAGE: Bash CODE: ``` yarn lint ``` ---------------------------------------- TITLE: Installing Next.js ESLint Plugin DESCRIPTION: This snippet provides commands to install `@next/eslint-plugin-next` as a development dependency. This plugin provides Next.js-specific ESLint rules and configurations, allowing for direct extension without needing to run `next lint` for basic setup. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/02-eslint.mdx#_snippet_14 LANGUAGE: bash CODE: ``` npm install --save-dev @next/eslint-plugin-next yarn add --dev @next/eslint-plugin-next pnpm add --save-dev @next/eslint-plugin-next bun add --dev @next/eslint-plugin-next ``` ---------------------------------------- TITLE: Running Next.js Development Server for Partytown Setup DESCRIPTION: This command initiates the Next.js development server. When `nextScriptWorkers` is enabled, Next.js will prompt the user to install `@builder.io/partytown` to complete the web worker script offloading setup. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/05-scripts.mdx#_snippet_4 LANGUAGE: Bash CODE: ``` npm run dev ``` ---------------------------------------- TITLE: Configuring Next.js Development Scripts (JSON) DESCRIPTION: This JSON snippet defines standard npm scripts within `package.json` for a Next.js project. It includes `dev` for development mode, `build` for production compilation, `start` for serving the production build, and `lint` for ESLint checks. These scripts streamline common development and deployment tasks. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_3 LANGUAGE: json CODE: ``` { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" } } ``` ---------------------------------------- TITLE: Installing @vercel/otel Package (Terminal) DESCRIPTION: This command installs the `@vercel/otel` package, which provides utilities for OpenTelemetry instrumentation in Next.js applications, making setup quicker and easier. It's the first step to integrate OpenTelemetry into your project. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/10-open-telemetry.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install @vercel/otel ``` ---------------------------------------- TITLE: Ordered File Structure in Next.js Docs (TXT) DESCRIPTION: This example demonstrates how files in the Next.js documentation are ordered using two-digit numerical prefixes. This method ensures that content is presented in a specific learning sequence, as seen in the routing section. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/05-community/01-contribution-guide.mdx#_snippet_2 LANGUAGE: txt CODE: ``` 02-routing ├── 01-defining-routes.mdx ├── 02-pages-and-layouts.mdx ├── 03-linking-and-navigating.mdx └── ... ``` ---------------------------------------- TITLE: Initializing Next.js Project with Vitest Example (Terminal) DESCRIPTION: This command uses `create-next-app` to quickly set up a new Next.js project pre-configured with Vitest by leveraging the `with-vitest` example. It creates a new directory named `with-vitest-app`. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/01-vitest.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest --example with-vitest with-vitest-app ``` ---------------------------------------- TITLE: Markdown Input Example DESCRIPTION: Illustrates a basic Markdown syntax example, showing how bold text and links are written using plain text. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/05-mdx.mdx#_snippet_0 LANGUAGE: md CODE: ``` I **love** using [Next.js](https://nextjs.org/) ``` ---------------------------------------- TITLE: Initializing Next.js Project with Playwright Example (Bash) DESCRIPTION: This command uses `create-next-app` to quickly set up a new Next.js project pre-configured with Playwright for End-to-End testing, leveraging the `with-playwright` example. It creates a new directory `with-playwright-app`. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/03-playwright.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest --example with-playwright with-playwright-app ``` ---------------------------------------- TITLE: Displaying Next.js Start Command Help (Bash) DESCRIPTION: This command is used to display the help message and available options for the `next start` command. It provides a comprehensive list of arguments and flags for configuring the production server. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/08-next-cli.mdx#_snippet_16 LANGUAGE: bash CODE: ``` next start -h ``` ---------------------------------------- TITLE: Installing Core Next.js Dependencies (Bash) DESCRIPTION: This command manually installs the essential packages for a Next.js application: `next`, `react`, and `react-dom`. It's used when setting up a Next.js project without `create-next-app`, requiring subsequent manual configuration of scripts and file structure. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_2 LANGUAGE: bash CODE: ``` npm install next@latest react@latest react-dom@latest ``` ---------------------------------------- TITLE: Next.js Start Command Help Output (Terminal) DESCRIPTION: This snippet shows the detailed help output for `next start`, listing arguments like `[directory]` and options such as `-p, --port`, `-H, --hostname`, and `--keepAliveTimeout`. It explains how to configure the production server, including port and hostname settings. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/08-next-cli.mdx#_snippet_17 LANGUAGE: bash CODE: ``` Usage: next start [directory] [options] Starts Next.js in production mode. The application should be compiled with `next build` first. Arguments: [directory] A directory on which to start the application. If not directory is provided, the current directory will be used. Options: -p, --port Specify a port number on which to start the application. (default: 3000, env: PORT) -H, --hostname Specify a hostname on which to start the application (default: 0.0.0.0). --keepAliveTimeout Specify the maximum amount of milliseconds to wait before closing the inactive connections. -h, --help Displays this message. ``` ---------------------------------------- TITLE: Installing @next/third-parties Library DESCRIPTION: This command installs the `@next/third-parties` package along with the latest version of Next.js. This library provides optimized components for integrating third-party services, and it is currently experimental, so using `@latest` or `@canary` is recommended. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/12-third-party-libraries.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install @next/third-parties@latest next@latest ``` ---------------------------------------- TITLE: Basic Link Component Usage in Next.js (TSX) DESCRIPTION: Illustrates a minimum working example of the Next.js `` component in a TypeScript/JSX file. It includes the necessary import statement and demonstrates how to render a simple link to another page, ensuring the code is runnable out-of-the-box for documentation examples. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/05-community/01-contribution-guide.mdx#_snippet_8 LANGUAGE: tsx CODE: ``` import Link from 'next/link' export default function Page() { return About } ``` ---------------------------------------- TITLE: Defining GET Route Handlers in App Directory DESCRIPTION: This example demonstrates how to define a GET request handler using Route Handlers in the `app` directory. Route Handlers replace API Routes from the `pages` directory, allowing custom request handling with Web Request and Response APIs, shown here in both TypeScript and JavaScript. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_35 LANGUAGE: ts CODE: ``` export async function GET(request: Request) {} ``` LANGUAGE: js CODE: ``` export async function GET(request) {} ``` ---------------------------------------- TITLE: Cloning the Next.js v14 Documentation Repository (Bash) DESCRIPTION: This command clones the `next.js-docs` repository from GitHub to your local machine. It's the first step to get started with contributing or using the documentation project. This command uses SSH for authentication. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` git clone git@github.com:emapeire/next.js-docs.git ``` ---------------------------------------- TITLE: Installing Next.js Canary for Partial Prerendering (Bash) DESCRIPTION: This snippet shows how to install the `next@canary` version, which is a prerequisite for enabling the experimental Partial Prerendering feature in Next.js. Running this command updates the `next` package to its latest experimental release, providing access to cutting-edge features. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/05-next-config-js/partial-prerendering.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install next@canary ``` ---------------------------------------- TITLE: Installing Vitest and React Testing Library Dependencies (Terminal) DESCRIPTION: Installs necessary development dependencies for Vitest and React Testing Library, including `@vitejs/plugin-react` for React support and `jsdom` for a browser-like DOM environment. This command supports npm, yarn, pnpm, and bun. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/01-vitest.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react # or yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react # or pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react # or bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react ``` ---------------------------------------- TITLE: Implementing getStaticPaths and getStaticProps in Next.js (JavaScript) DESCRIPTION: This JavaScript example demonstrates how to use `getStaticPaths` to define a list of paths for static generation and `getStaticProps` to fetch data for each path in a Next.js dynamic route. It shows the setup for pre-rendering pages based on external data, including the `fallback` option for handling paths not generated at build time. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/03-data-fetching/02-get-static-paths.mdx#_snippet_1 LANGUAGE: JavaScript CODE: ``` export async function getStaticPaths() { return { paths: [ { params: { name: 'next.js', }, }, // See the "paths" section below ], fallback: true, // false or "blocking" } } export async function getStaticProps() { const res = await fetch('https://api.github.com/repos/vercel/next.js') const repo = await res.json() return { props: { repo } } } export default function Page({ repo }) { return repo.stargazers_count } ``` ---------------------------------------- TITLE: Building and Starting Next.js Production Server - Bash DESCRIPTION: These commands are used to test On-Demand ISR configuration in a production-like environment. `next build` creates an optimized production build, and `next start` starts the Next.js production server, allowing verification of revalidation behavior. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/03-data-fetching/04-incremental-static-regeneration.mdx#_snippet_3 LANGUAGE: Bash CODE: ``` $ next build $ next start ``` ---------------------------------------- TITLE: Installing Tailwind CSS Packages with npm DESCRIPTION: This snippet demonstrates how to install the necessary Tailwind CSS, PostCSS, and Autoprefixer packages as development dependencies, followed by initializing Tailwind CSS to generate the `tailwind.config.js` and `postcss.config.js` configuration files. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/05-styling/02-tailwind-css.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p ``` ---------------------------------------- TITLE: AMP HOC Transformation Example - After DESCRIPTION: Example of a Next.js page after the `withamp-to-config` codemod, showing the modern `config` export for AMP integration. This replaces the `withAmp` HOC. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/01-codemods.mdx#_snippet_16 LANGUAGE: javascript CODE: ``` // After export default function Home() { return

My AMP Page

} export const config = { amp: true, } ``` ---------------------------------------- TITLE: Updating `package.json` Scripts for Next.js - JSON DESCRIPTION: This JSON snippet provides the necessary updates to the `scripts` section of the `package.json` file. It replaces Create React App commands with Next.js specific commands for development (`dev`), building (`build`), and starting the production server (`start`). SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/05-from-create-react-app.mdx#_snippet_22 LANGUAGE: json CODE: ``` { "scripts": { "dev": "next dev", "build": "next build", "start": "next start" } } ``` ---------------------------------------- TITLE: Installing MDX Packages for Next.js DESCRIPTION: Installs the necessary npm packages (`@next/mdx`, `@mdx-js/loader`, `@mdx-js/react`, `@types/mdx`) required to enable MDX support in a Next.js project. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/05-mdx.mdx#_snippet_2 LANGUAGE: bash CODE: ``` npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx ``` ---------------------------------------- TITLE: Upgrading ESLint Configuration for Next.js (Bash) DESCRIPTION: This command installs or updates the `eslint-config-next` package to its latest version as a development dependency. This is necessary to ensure ESLint is compatible with the upgraded Next.js version. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm install -D eslint-config-next@latest ``` ---------------------------------------- TITLE: Testing Next.js Preview API Route Manually DESCRIPTION: This example shows a complete, simple Next.js API route (`pages/api/preview.js`) for manually testing the preview mode. When accessed, it sets the necessary preview cookies (`__prerender_bypass` and `__next_preview_data`) and sends a confirmation message, allowing developers to verify the setup in their browser's developer tools. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/06-configuring/14-preview-mode.mdx#_snippet_1 LANGUAGE: js CODE: ``` // simple example for testing it manually from your browser. export default function handler(req, res) { res.setPreviewData({}) res.end('Preview mode enabled') } ``` ---------------------------------------- TITLE: Installing Cypress as a Dev Dependency (NPM/Yarn/PNPM) DESCRIPTION: This snippet demonstrates how to manually install Cypress as a development dependency using popular package managers like npm, yarn, or pnpm. It's a prerequisite for integrating Cypress into an existing Next.js project. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/04-cypress.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm install -D cypress # or yarn add -D cypress # or pnpm install -D cypress ``` ---------------------------------------- TITLE: Installing PostCSS and Autoprefixer for Tailwind CSS DESCRIPTION: This snippet provides the command to install `postcss` and `autoprefixer` using npm. These packages are essential dependencies for integrating and properly processing Tailwind CSS within a Next.js project. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/05-from-create-react-app.mdx#_snippet_12 LANGUAGE: bash CODE: ``` npm install postcss autoprefixer ``` ---------------------------------------- TITLE: create-next-app Command Line Options DESCRIPTION: This output provides a comprehensive list of command-line options for `create-next-app`. These options enable non-interactive project setup, allowing users to specify configurations like TypeScript, ESLint, Tailwind CSS, App Router, and package manager preferences directly via arguments. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/06-create-next-app.mdx#_snippet_5 LANGUAGE: txt CODE: ``` Usage: create-next-app [options] Options: -V, --version output the version number --ts, --typescript Initialize as a TypeScript project. (default) --js, --javascript Initialize as a JavaScript project. --tailwind Initialize with Tailwind CSS config. (default) --eslint Initialize with ESLint config. --app Initialize as an App Router project. --src-dir Initialize inside a `src/` directory. --import-alias Specify import alias to use (default "@/*"). --use-npm Explicitly tell the CLI to bootstrap the app using npm --use-pnpm Explicitly tell the CLI to bootstrap the app using pnpm --use-yarn Explicitly tell the CLI to bootstrap the app using Yarn --use-bun Explicitly tell the CLI to bootstrap the app using Bun -e, --example [name]|[github-url] An example to bootstrap the app with. You can use an example name from the official Next.js repo or a public GitHub URL. The URL can use any branch and/or subdirectory --example-path In a rare case, your GitHub URL might contain a branch name with a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar). In this case, you must specify the path to the example separately: --example-path foo/bar --reset-preferences Explicitly tell the CLI to reset any stored preferences -h, --help output usage information ``` ---------------------------------------- TITLE: Configuring Next.js with an Async Function Export in next.config.js DESCRIPTION: Introduced in Next.js 12.1.0, this example shows how to use an `async` function to export the configuration. This enables asynchronous operations within the configuration logic, providing more flexibility for complex setups. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/05-next-config-js/index.mdx#_snippet_3 LANGUAGE: js CODE: ``` // @ts-check module.exports = async (phase, { defaultConfig }) => { /** * @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ } return nextConfig } ``` ---------------------------------------- TITLE: Installing Sharp for Next.js Image Optimization (Terminal) DESCRIPTION: These commands demonstrate how to install the `sharp` package, which is a required dependency for Next.js Image Optimization when using the default loader. `sharp` provides efficient image processing capabilities for optimizing images during runtime. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/05-next-config-js/output.mdx#_snippet_1 LANGUAGE: Bash CODE: ``` npm i sharp ``` LANGUAGE: Bash CODE: ``` yarn add sharp ``` LANGUAGE: Bash CODE: ``` pnpm add sharp ``` LANGUAGE: Bash CODE: ``` bun add sharp ``` ---------------------------------------- TITLE: Using Icons in MDX Documentation DESCRIPTION: Provides an example of how to embed custom icons like `` and `` within MDX documentation. It shows the syntax for including these components and specifies their size, enhancing visual communication in the docs. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/05-community/01-contribution-guide.mdx#_snippet_14 LANGUAGE: mdx CODE: ``` ``` ---------------------------------------- TITLE: Migrating Data Fetching to Async Server Components DESCRIPTION: This example illustrates the new data fetching paradigm in the Next.js `app` directory, utilizing `fetch` within `async` React Server Components. It shows how to achieve caching behaviors similar to `getStaticProps` (force-cache, revalidate) and `getServerSideProps` (no-store) by configuring the `fetch` options, simplifying data retrieval logic. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_20 LANGUAGE: tsx CODE: ``` export default async function Page() {\n // This request should be cached until manually invalidated.\n // Similar to `getStaticProps`.\n // `force-cache` is the default and can be omitted.\n const staticData = await fetch(`https://...`, { cache: 'force-cache' })\n\n // This request should be refetched on every request.\n // Similar to `getServerSideProps`.\n const dynamicData = await fetch(`https://...`, { cache: 'no-store' })\n\n // This request should be cached with a lifetime of 10 seconds.\n // Similar to `getStaticProps` with the `revalidate` option.\n const revalidatedData = await fetch(`https://...`, {\n next: { revalidate: 10 }\n })\n\n return
...
\n} ``` LANGUAGE: jsx CODE: ``` export default async function Page() {\n // This request should be cached until manually invalidated.\n // Similar to `getStaticProps`.\n // `force-cache` is the default and can be omitted.\n const staticData = await fetch(`https://...`, { cache: 'force-cache' })\n\n // This request should be refetched on every request.\n // Similar to `getServerSideProps`.\n const dynamicData = await fetch(`https://...`, { cache: 'no-store' })\n\n // This request should be cached with a lifetime of 10 seconds.\n // Similar to `getStaticProps` with the `revalidate` option.\n const revalidatedData = await fetch(`https://...`, {\n next: { revalidate: 10 }\n })\n\n return
...
\n} ``` ---------------------------------------- TITLE: Data Fetching with fetch() in Next.js App Directory DESCRIPTION: This example illustrates data fetching in the `app` directory using the native `fetch()` API. By default, `fetch()` requests are cached (`cache: 'force-cache'`), mimicking the static generation behavior of `getStaticProps` from the `pages` directory without requiring a dedicated function. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_28 LANGUAGE: JSX CODE: ``` // `app` directory // This function can be named anything async function getProjects() { const res = await fetch(`https://...`) const projects = await res.json() return projects } export default async function Index() { const projects = await getProjects() return projects.map((project) =>
{project.name}
) } ``` ---------------------------------------- TITLE: Creating Next.js App Interactively with npx DESCRIPTION: This command initiates the interactive `create-next-app` process using `npx`, the package runner included with npm. It fetches the latest version of `create-next-app` and guides the user through configuration prompts. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/06-create-next-app.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest ``` ---------------------------------------- TITLE: Implementing getStaticPaths and getStaticProps in Next.js (TypeScript) DESCRIPTION: This TypeScript example demonstrates how to use `getStaticPaths` to define a list of paths for static generation and `getStaticProps` to fetch data for each path in a Next.js dynamic route. It shows the setup for pre-rendering pages based on external data, including type definitions and the `fallback` option for handling paths not generated at build time. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/03-data-fetching/02-get-static-paths.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` import type { InferGetStaticPropsType, GetStaticProps, GetStaticPaths, } from 'next' type Repo = { name: string stargazers_count: number } export const getStaticPaths = (async () => { return { paths: [ { params: { name: 'next.js', }, }, // See the "paths" section below ], fallback: true, // false or "blocking" } }) satisfies GetStaticPaths export const getStaticProps = (async (context) => { const res = await fetch('https://api.github.com/repos/vercel/next.js') const repo = await res.json() return { props: { repo } } }) satisfies GetStaticProps<{ repo: Repo }> export default function Page({ repo, }: InferGetStaticPropsType) { return repo.stargazers_count } ``` ---------------------------------------- TITLE: Interactive create-next-app Prompts DESCRIPTION: This snippet displays the series of questions presented to the user during the interactive `create-next-app` setup. These prompts allow customization of the project's name, use of TypeScript, ESLint, Tailwind CSS, `src/` directory, App Router, and import alias. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/06-create-next-app.mdx#_snippet_4 LANGUAGE: txt CODE: ``` What is your project named? my-app Would you like to use TypeScript? No / Yes Would you like to use ESLint? No / Yes Would you like to use Tailwind CSS? No / Yes Would you like to use `src/` directory? No / Yes Would you like to use App Router? (recommended) No / Yes Would you like to customize the default import alias (@/*)? No / Yes ``` ---------------------------------------- TITLE: Installing @next/bundle-analyzer Plugin DESCRIPTION: This snippet provides commands for installing the `@next/bundle-analyzer` plugin, which is essential for analyzing JavaScript bundle sizes in Next.js applications. It supports npm, yarn, and pnpm package managers. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/06-bundle-analyzer.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm i @next/bundle-analyzer # or yarn add @next/bundle-analyzer # or pnpm add @next/bundle-analyzer ``` ---------------------------------------- TITLE: Configuring Next.js Scripts for Node.js Server Deployment DESCRIPTION: This `package.json` snippet defines essential scripts for developing and deploying a Next.js application on a Node.js server. The `build` script compiles and optimizes the application for production, while the `start` script launches the Next.js production server, supporting all Next.js features. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/10-deploying/index.mdx#_snippet_0 LANGUAGE: JSON CODE: ``` { "scripts": { "dev": "next dev", "build": "next build", "start": "next start" } } ``` ---------------------------------------- TITLE: Implementing TypeScript and JavaScript Code Switcher in MDX DESCRIPTION: Demonstrates the syntax for creating a language switcher in MDX documentation, allowing users to toggle between TypeScript and JavaScript versions of a code example. This involves placing TS and JS code blocks sequentially and linking them with the `switcher` prop to provide flexible code presentation. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/05-community/01-contribution-guide.mdx#_snippet_10 LANGUAGE: mdx CODE: ``` ```tsx filename="app/page.tsx" switcher ``` ```jsx filename="app/page.js" switcher ``` ``` ---------------------------------------- TITLE: Installing OpenTelemetry Core Packages (Bash) DESCRIPTION: Installs the essential OpenTelemetry SDK and exporter packages required for manual configuration in a Next.js project. These packages provide the foundational components for creating, processing, and exporting telemetry data. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/10-open-telemetry.mdx#_snippet_3 LANGUAGE: bash CODE: ``` npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http ``` ---------------------------------------- TITLE: Configuring Global Layout with Custom App (JSX) DESCRIPTION: This JavaScript snippet provides an alternative implementation for the custom `_app` file, serving the same purpose as its TypeScript counterpart. It enables global styling and shared component logic by wrapping all page components in a Next.js application. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_10 LANGUAGE: jsx CODE: ``` export default function App({ Component, pageProps }) { return } ``` ---------------------------------------- TITLE: Running Cypress for the First Time (Bash) DESCRIPTION: This command executes the `cypress:open` script defined in `package.json`, launching the Cypress testing suite. The first run will prompt you to configure E2E and/or Component Testing, creating necessary configuration files and folders. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/04-cypress.mdx#_snippet_3 LANGUAGE: bash CODE: ``` npm run cypress:open ``` ---------------------------------------- TITLE: Installing OpenTelemetry API - Bash DESCRIPTION: Installs the `@opentelemetry/api` package using npm, which is a fundamental dependency for integrating OpenTelemetry's tracing capabilities and creating custom spans within a Next.js project. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/06-optimizing/10-open-telemetry.mdx#_snippet_6 LANGUAGE: bash CODE: ``` npm install @opentelemetry/api ``` ---------------------------------------- TITLE: Creating a Home Page in Next.js App Router (JavaScript) DESCRIPTION: This JavaScript React component defines the root page (`/`) for a Next.js application using the App Router. It exports a simple functional component that renders an `

` tag with initial content. This `page.js` file serves as the entry point for the application's home route. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_7 LANGUAGE: jsx CODE: ``` export default function Page() { return

Hello, Next.js!

} ``` ---------------------------------------- TITLE: Creating a Server Component Page with Data Fetching (JavaScript) DESCRIPTION: This JavaScript snippet demonstrates creating a Server Component (`app/page.js`) that fetches data using the new data fetching APIs. It then imports and forwards the fetched data to the `HomePage` Client Component, illustrating the interaction between Server and Client Components in the `app` directory. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_18 LANGUAGE: JavaScript CODE: ``` // Import your Client Component import HomePage from './home-page' async function getPosts() { const res = await fetch('https://...') const posts = await res.json() return posts } export default async function Page() { // Fetch data directly in a Server Component const recentPosts = await getPosts() // Forward fetched data to your Client Component return } ``` ---------------------------------------- TITLE: Configuring Jest Setup Files - JavaScript DESCRIPTION: This configuration snippet for `jest.config.js` specifies a setup file to run after the test environment is set up. It's used to import custom matchers like those from `@testing-library/jest-dom`, making testing easier by extending Jest's assertion capabilities. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_12 LANGUAGE: JavaScript CODE: ``` setupFilesAfterEnv: ['/jest.setup.js'] ``` ---------------------------------------- TITLE: Installing Next.js Dependency - Bash DESCRIPTION: This snippet demonstrates how to install the latest version of Next.js as a project dependency using npm. This is the essential first step to begin migrating a Vite application to a Next.js environment. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/04-from-vite.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install next@latest ``` ---------------------------------------- TITLE: AMP HOC Transformation Example - Before DESCRIPTION: Example of a Next.js page using the deprecated `withAmp` HOC for AMP integration. This pattern is transformed to use the `config` export for AMP settings. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/01-codemods.mdx#_snippet_15 LANGUAGE: javascript CODE: ``` // Before import { withAmp } from 'next/amp' function Home() { return

My AMP Page

} export default withAmp(Home) ``` ---------------------------------------- TITLE: Enabling Manual Signal Handling in package.json (Pages Router) DESCRIPTION: This `package.json` script configuration sets the `NEXT_MANUAL_SIG_HANDLE` environment variable to `true` for the `start` command. This enables manual handling of `SIGTERM` and `SIGINT` signals in a self-hosted Next.js application, allowing custom cleanup logic to be executed before the server shuts down. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/10-deploying/index.mdx#_snippet_7 LANGUAGE: JSON CODE: ``` { "scripts": { "dev": "next dev", "build": "next build", "start": "NEXT_MANUAL_SIG_HANDLE=true next start" } } ``` ---------------------------------------- TITLE: Deprecated URL Prop Usage Example - After DESCRIPTION: Example of a Next.js page component after the `url-to-withrouter` codemod, showing the use of `withRouter` and `this.props.router` to access router information. This is the recommended approach. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/01-codemods.mdx#_snippet_19 LANGUAGE: javascript CODE: ``` import React from 'react' import { withRouter } from 'next/router' export default withRouter( class extends React.Component { render() { const { pathname } = this.props.router return
Current pathname: {pathname}
} } ) ``` ---------------------------------------- TITLE: Installing Next.js Dependency - Bash DESCRIPTION: This command installs the latest version of Next.js as a project dependency using npm. It's the first step in migrating a Create React App project to Next.js, ensuring the core framework is available for use. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/05-from-create-react-app.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install next@latest ``` ---------------------------------------- TITLE: Adding Cypress Open Command to package.json (JSON) DESCRIPTION: This JSON snippet shows how to add a `cypress:open` script to the `scripts` section of your `package.json` file. This script allows you to easily launch the Cypress testing suite from your terminal. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/04-cypress.mdx#_snippet_2 LANGUAGE: json CODE: ``` { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "cypress:open": "cypress open" } } ``` ---------------------------------------- TITLE: Getting a Cookie Value with NextRequest.cookies.get in TypeScript DESCRIPTION: This method retrieves the value of a cookie given its name. If the cookie is not found, `undefined` is returned. If multiple cookies with the same name exist, the first one encountered is returned. The example shows how to get the value of the 'show-banner' cookie. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/04-functions/next-request.mdx#_snippet_1 LANGUAGE: TypeScript CODE: ``` // Given incoming request /home // { name: 'show-banner', value: 'false', Path: '/home' } request.cookies.get('show-banner') ``` ---------------------------------------- TITLE: Configuring Cypress for E2E Testing (JavaScript) DESCRIPTION: This JavaScript configuration snippet for `cypress.config.js` provides the foundational setup for End-to-End testing. It defines the `e2e` object where specific E2E test configurations, like `setupNodeEvents`, are managed. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/04-cypress.mdx#_snippet_5 LANGUAGE: js CODE: ``` const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) {}, }, }) ``` ---------------------------------------- TITLE: Demonstrating Sequential Data Fetching with Nested Components DESCRIPTION: This example illustrates sequential data fetching in a Next.js server component setup. The Playlists component depends on artistID from the Artist component, causing data fetching to occur in sequence. It also shows how can be used to provide a loading fallback, preventing the entire page from being blocked while data is fetched. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/02-data-fetching/03-patterns.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` // ... async function Playlists({ artistID }: { artistID: string }) { // Wait for the playlists const playlists = await getArtistPlaylists(artistID) return (
    {playlists.map((playlist) => (
  • {playlist.name}
  • ))}
) } export default async function Page({ params: { username }, }: { params: { username: string } }) { // Wait for the artist const artist = await getArtist(username) return ( <>

{artist.name}

Loading...}> ) } ``` LANGUAGE: JavaScript CODE: ``` // ... async function Playlists({ artistID }) { // Wait for the playlists const playlists = await getArtistPlaylists(artistID) return (
    {playlists.map((playlist) => (
  • {playlist.name}
  • ))}
) } export default async function Page({ params: { username } }) { // Wait for the artist const artist = await getArtist(username) return ( <>

{artist.name}

Loading...}> ) } ``` ---------------------------------------- TITLE: Enabling Turbopack in Next.js Development (Bash) DESCRIPTION: This command starts the Next.js development server with Turbopack enabled using the `--turbo` option. Turbopack is a new bundler designed to speed up local iteration times during development. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/08-next-cli.mdx#_snippet_6 LANGUAGE: bash CODE: ``` next dev --turbo ``` ---------------------------------------- TITLE: Starting Next.js Dev Server with Debugging (Bash) DESCRIPTION: This command starts the Next.js development server with the Node.js `--inspect` flag, enabling debugging via Chrome DevTools. It's used directly in the terminal to initiate the debugging process for server-side code. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/06-configuring/13-debugging.mdx#_snippet_1 LANGUAGE: bash CODE: ``` NODE_OPTIONS='--inspect' next dev ``` ---------------------------------------- TITLE: Configuring Jest Setup Files - TypeScript DESCRIPTION: This configuration snippet for `jest.config.ts` specifies a setup file to run after the test environment is set up. It's used to import custom matchers like those from `@testing-library/jest-dom`, making testing easier by extending Jest's assertion capabilities. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_11 LANGUAGE: TypeScript CODE: ``` setupFilesAfterEnv: ['/jest.setup.ts'] ``` ---------------------------------------- TITLE: Defining Bash Code Block with Filename in MDX DESCRIPTION: Shows how to embed a Bash code block within an MDX file, specifying the language and a `filename` prop. The `filename` prop renders a special Terminal icon, guiding users on where to input the command and improving clarity for command-line examples. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/05-community/01-contribution-guide.mdx#_snippet_9 LANGUAGE: mdx CODE: ``` ```bash filename="Terminal" npx create-next-app ``` ``` ---------------------------------------- TITLE: Example of router.prefetch with Login Flow in Next.js JSX DESCRIPTION: This example demonstrates prefetching the '/dashboard' page after a login attempt to enable a faster client-side transition. It uses `useEffect` to prefetch the page on component mount and `router.push` for navigation upon successful API response. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/02-api-reference/02-functions/use-router.mdx#_snippet_12 LANGUAGE: jsx CODE: ``` import { useCallback, useEffect } from 'react' import { useRouter } from 'next/router' export default function Login() { const router = useRouter() const handleSubmit = useCallback((e) => { e.preventDefault() fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ /* Form data */ }), }).then((res) => { // Do a fast client-side transition to the already prefetched dashboard page if (res.ok) router.push('/dashboard') }) }, []) useEffect(() => { // Prefetch the dashboard page router.prefetch('/dashboard') }, [router]) return (
{/* Form fields */}
) } ``` ---------------------------------------- TITLE: Defining Home Page with Pages Router (TSX) DESCRIPTION: This snippet creates the root page (`/`) for a Next.js application using the Pages Router. It exports a default React component that renders a simple `

` tag, serving as the entry point for the application's home route. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_8 LANGUAGE: tsx CODE: ``` export default function Page() { return

Hello, Next.js!

} ``` ---------------------------------------- TITLE: Basic Markdown List Syntax DESCRIPTION: This snippet illustrates the standard Markdown syntax for creating an unordered list. It serves as a basic example of how Markdown content is structured before being transformed into HTML. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/05-mdx.mdx#_snippet_14 LANGUAGE: Markdown CODE: ``` This is a list in markdown: - One - Two - Three ``` ---------------------------------------- TITLE: Starting Next.js Production Server with PORT Environment Variable (Bash) DESCRIPTION: This command starts the Next.js application in production mode by setting the `PORT` environment variable. This method allows specifying the server port (here, 4000) without using a command-line flag, which is useful for environment-specific configurations. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/08-next-cli.mdx#_snippet_19 LANGUAGE: bash CODE: ``` PORT=4000 next start ``` ---------------------------------------- TITLE: Initializing New Next.js Project with TypeScript (Bash) DESCRIPTION: This command initializes a new Next.js project using `create-next-app`. By default, `create-next-app` now includes TypeScript support, automatically setting up the necessary configurations and dependencies for a TypeScript-first development experience. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/07-configuring/01-typescript.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npx create-next-app@latest ``` ---------------------------------------- TITLE: Setting CORS Headers in Next.js Route Handlers (GET) DESCRIPTION: This example shows how to configure Cross-Origin Resource Sharing (CORS) headers for a GET request in a Next.js Route Handler. It sets Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers to enable cross-origin requests. The dynamic = 'force-dynamic' export ensures the handler is not statically optimized. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/01-routing/12-route-handlers.mdx#_snippet_23 LANGUAGE: TypeScript CODE: ``` export const dynamic = 'force-dynamic' // defaults to auto export async function GET(request: Request) { return new Response('Hello, Next.js!', { status: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization' } }) } ``` LANGUAGE: JavaScript CODE: ``` export const dynamic = 'force-dynamic' // defaults to auto export async function GET(request) { return new Response('Hello, Next.js!', { status: 200, headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization' } }) } ``` ---------------------------------------- TITLE: Creating Next.js App Interactively with Yarn DESCRIPTION: This command starts the interactive `create-next-app` process using `yarn`, a popular package manager. It's an alternative to `npx` for users who prefer Yarn for managing their project dependencies. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/06-create-next-app.mdx#_snippet_1 LANGUAGE: bash CODE: ``` yarn create next-app ``` ---------------------------------------- TITLE: Creating a Server Component Page with Data Fetching (TypeScript) DESCRIPTION: This TypeScript snippet demonstrates creating a Server Component (`app/page.tsx`) that fetches data using the new data fetching APIs. It then imports and forwards the fetched data to the `HomePage` Client Component, illustrating the interaction between Server and Client Components in the `app` directory. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_17 LANGUAGE: TypeScript CODE: ``` // Import your Client Component import HomePage from './home-page' async function getPosts() { const res = await fetch('https://...') const posts = await res.json() return posts } export default async function Page() { // Fetch data directly in a Server Component const recentPosts = await getPosts() // Forward fetched data to your Client Component return } ``` ---------------------------------------- TITLE: Configuring npm Scripts for Custom Next.js Server in JSON DESCRIPTION: This JSON snippet shows how to modify the `scripts` section in `package.json` to run a custom Next.js server. It defines `dev` to start the server in development mode, `build` to build the Next.js application, and `start` to run the custom server in production, ensuring the `server.js` file is executed instead of the default Next.js server. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/06-configuring/10-custom-server.mdx#_snippet_1 LANGUAGE: json CODE: ``` { "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js" } } ``` ---------------------------------------- TITLE: Example of router.back in Next.js JSX DESCRIPTION: This example shows how to use `router.back` to navigate back in the browser's history. It's equivalent to clicking the browser's back button and executes `window.history.back()`. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/02-api-reference/02-functions/use-router.mdx#_snippet_15 LANGUAGE: jsx CODE: ``` import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return ( ) } ``` ---------------------------------------- TITLE: Creating a Home Page in Next.js App Router (TypeScript) DESCRIPTION: This TypeScript React component defines the root page (`/`) for a Next.js application using the App Router. It exports a simple functional component that renders an `

` tag with initial content. This `page.tsx` file serves as the entry point for the application's home route. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_6 LANGUAGE: tsx CODE: ``` export default function Page() { return

Hello, Next.js!

} ``` ---------------------------------------- TITLE: Example Home Component - App Router DESCRIPTION: This JSX code defines a simple `Home` component for the Next.js App Router. It renders an `h1` heading and a `Link` component, providing a basic structure for testing rendering and navigation within the App Router context. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_18 LANGUAGE: JSX CODE: ``` import Link from 'next/link' export default function Home() { return (

Home

About
) } ``` ---------------------------------------- TITLE: Getting All Cookies or Specific Cookies with NextRequest.cookies.getAll in TypeScript DESCRIPTION: This method returns an array of cookie values. If a cookie name is provided, it returns all cookies with that specific name. If no name is given, it returns all cookies present on the request. The examples illustrate retrieving all 'experiments' cookies and all cookies on the request. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/04-functions/next-request.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` // Given incoming request /home // [ // { name: 'experiments', value: 'new-pricing-page', Path: '/home' }, // { name: 'experiments', value: 'winter-launch', Path: '/home' }, // ] request.cookies.getAll('experiments') // Alternatively, get all cookies for the request request.cookies.getAll() ``` ---------------------------------------- TITLE: Configuring Global Layout with Custom App (TSX) DESCRIPTION: This TypeScript snippet defines a custom `_app.tsx` file, which is crucial for initializing pages in Next.js. It allows for global CSS, layout, and state management by wrapping all page components with the `App` component and passing `pageProps`. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/01-getting-started/01-installation.mdx#_snippet_9 LANGUAGE: tsx CODE: ``` import type { AppProps } from 'next/app' export default function App({ Component, pageProps }: AppProps) { return } ``` ---------------------------------------- TITLE: Getting All Cookies or by Name in Next.js (JSX) DESCRIPTION: This example shows how to use `cookies().getAll()` to retrieve a list of cookies. If a `name` parameter is provided, it returns all cookies matching that name; otherwise, it returns all available cookies. This is useful in Server Components for iterating and displaying multiple cookie values. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/04-functions/cookies.mdx#_snippet_1 LANGUAGE: JSX CODE: ``` import { cookies } from 'next/headers' export default function Page() { const cookieStore = cookies() return cookieStore.getAll().map((cookie) => (

Name: {cookie.name}

Value: {cookie.value}

)) } ``` ---------------------------------------- TITLE: Fetching Page Data with getStaticProps in Next.js DESCRIPTION: This example demonstrates how to use `getStaticProps` to fetch data at build time for a Next.js page. The `getStaticProps` function calls an external API, retrieves post data, and then passes it as props to the `Blog` component, enabling pre-rendering with dynamic content. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/02-rendering/02-static-site-generation.mdx#_snippet_2 LANGUAGE: JSX CODE: ``` export default function Blog({ posts }) { // Render posts... } // This function gets called at build time export async function getStaticProps() { // Call an external API endpoint to get posts const res = await fetch('https://.../posts') const posts = await res.json() // By returning { props: { posts } }, the Blog component // will receive `posts` as a prop at build time return { props: { posts, }, } } ``` ---------------------------------------- TITLE: Converting Absolute Image Import Paths to Relative - TypeScript (Before) DESCRIPTION: This code shows an example of an absolute import path for an image located in the `/public` directory, typical in a Create React App setup before migration to Next.js. Next.js requires relative paths for such imports. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/05-from-create-react-app.mdx#_snippet_18 LANGUAGE: tsx CODE: ``` // Before import logo from '/logo.png' ``` ---------------------------------------- TITLE: Fetching Data for Dynamic Routes with getStaticProps and getStaticPaths DESCRIPTION: This example combines `getStaticProps` and `getStaticPaths` for a dynamic Next.js page. `getStaticPaths` defines the routes to pre-render, while `getStaticProps` fetches the specific data for each pre-rendered post using the `params.id` from the route, passing it to the `Post` component. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/02-rendering/02-static-site-generation.mdx#_snippet_4 LANGUAGE: JSX CODE: ``` export default function Post({ post }) { // Render post... } export async function getStaticPaths() { // ... } // This also gets called at build time export async function getStaticProps({ params }) { // params contains the post `id`. // If the route is like /posts/1, then params.id is 1 const res = await fetch(`https://.../posts/${params.id}`) const post = await res.json() // Pass post data to the page via props return { props: { post } } } ``` ---------------------------------------- TITLE: Example Home Component - Pages Router DESCRIPTION: This JSX code defines a simple `Home` component for the Next.js Pages Router. It renders an `h1` heading with the text 'Home', serving as a basic component to be tested for rendering and content. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/08-testing/02-jest.mdx#_snippet_16 LANGUAGE: JSX CODE: ``` export default function Home() { return

Home

} ``` ---------------------------------------- TITLE: Generating Static Params for Dynamic Routes in Next.js App Directory DESCRIPTION: This example shows `generateStaticParams` in the `app` directory, which replaces `getStaticPaths` for defining dynamic segments to be pre-rendered. It returns an array of segment objects, simplifying the API for nested routing, and is used alongside `fetch()` for data retrieval. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/01-building-your-application/11-upgrading/02-app-router-migration.mdx#_snippet_30 LANGUAGE: JSX CODE: ``` // `app` directory import PostLayout from '@/components/post-layout' export async function generateStaticParams() { return [{ id: '1' }, { id: '2' }] } async function getPost(params) { const res = await fetch(`https://.../posts/${params.id}`) const post = await res.json() return post } export default async function Post({ params }) { const post = await getPost(params) return } ``` ---------------------------------------- TITLE: Importing and Initializing Next.js Application Instance in JavaScript DESCRIPTION: This JavaScript snippet illustrates the fundamental way to import the Next.js module and initialize a Next.js application instance. The `next()` function, when called, returns an `app` object that can then be used to programmatically handle Next.js requests. It accepts an optional configuration object to customize behavior like development mode, hostname, and port. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/01-building-your-application/06-configuring/10-custom-server.mdx#_snippet_2 LANGUAGE: js CODE: ``` const next = require('next') const app = next({}) ``` ---------------------------------------- TITLE: Starting Next.js Production Server on Custom Port (Bash) DESCRIPTION: This command starts the Next.js application in production mode on a specified port, in this case, port 4000. It overrides the default port (3000) for the production server. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/08-next-cli.mdx#_snippet_18 LANGUAGE: bash CODE: ``` next start -p 4000 ``` ---------------------------------------- TITLE: Preloading Resources with ReactDOM in Next.js (JSX) DESCRIPTION: This JavaScript example demonstrates how to use `ReactDOM` methods (`preload`, `preconnect`, `prefetchDNS`) within a client component in Next.js to insert resource hints into the document's ``. It's a workaround for the Metadata API's lack of direct support for these hints, mirroring the TypeScript example. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/02-app/02-api-reference/04-functions/generate-metadata.mdx#_snippet_53 LANGUAGE: jsx CODE: ``` 'use client' import ReactDOM from 'react-dom' export function PreloadResources() { ReactDOM.preload('...', { as: '...' }) ReactDOM.preconnect('...', { crossOrigin: '...' }) ReactDOM.prefetchDNS('...') return null } ``` ---------------------------------------- TITLE: Creating an AMP-First Page Component in Next.js DESCRIPTION: This example illustrates a complete AMP-only page component in Next.js. By setting 'amp: true' in the config, the page is rendered without client-side JavaScript, is optimized by AMP Optimizer, and serves both user-accessible and search-engine indexable versions. SOURCE: https://github.com/nextjsargentina/next.js-docs/blob/main/src/docs/03-pages/02-api-reference/02-functions/use-amp.mdx#_snippet_1 LANGUAGE: jsx CODE: ``` export const config = { amp: true } function About(props) { return

My AMP About Page!

} export default About ```