### Quickstart: Create Next.js App with Jest Example
Source: https://nextjs.org/docs/app/guides/testing/jest.md
Use `create-next-app` with the `with-jest` example to quickly scaffold a Next.js project pre-configured with Jest.
```bash
pnpm create next-app --example with-jest with-jest-app
```
```bash
npx create-next-app@latest --example with-jest with-jest-app
```
```bash
yarn create next-app --example with-jest with-jest-app
```
```bash
bun create next-app --example with-jest with-jest-app
```
--------------------------------
### Quickstart: Create Next.js App with Vitest Example
Source: https://nextjs.org/docs/app/guides/testing/vitest.md
Use `create-next-app` with the `with-vitest` example to quickly scaffold a new Next.js project pre-configured for Vitest.
```bash
pnpm create next-app --example with-vitest with-vitest-app
```
```bash
npx create-next-app@latest --example with-vitest with-vitest-app
```
```bash
yarn create next-app --example with-vitest with-vitest-app
```
```bash
bun create next-app --example with-vitest with-vitest-app
```
--------------------------------
### Example Deploy Script for Next.js Testing Adapter (Bash)
Source: https://nextjs.org/docs/app/api-reference/adapters/testing-adapters.md
This script demonstrates how to install an adapter, build a Next.js app, persist metadata, and start/deploy the application, ensuring the deployment URL is output to stdout as required by the contract.
```bash
#!/usr/bin/env bash
set -euo pipefail
# Install the adapter, build the app, and deploy or start it.
node -e "
const pkg=JSON.parse(require('fs').readFileSync('package.json','utf8'));
pkg.dependencies=pkg.dependencies||{};
pkg.dependencies['adapter']='file:${ADAPTER_DIR}';
require('fs').writeFileSync('package.json',JSON.stringify(pkg,null,2));
" >&2
# Set the adapter path so that the app uses it.
export NEXT_ADAPTER_PATH="${ADAPTER_DIR}/dist/index.js"
# Build the app
pnpm build
# Write any metadata needed later to files in the working directory.
BUILD_ID="$(cat .next/BUILD_ID)"
DEPLOYMENT_ID="my-adapter-local"
# If your adapter generates an immutable asset token, set it here.
# Otherwise use "undefined" to indicate there is none.
IMMUTABLE_ASSET_TOKEN="undefined"
{
echo "BUILD_ID: $BUILD_ID"
echo "DEPLOYMENT_ID: $DEPLOYMENT_ID"
echo "IMMUTABLE_ASSET_TOKEN: $IMMUTABLE_ASSET_TOKEN"
} >> .adapter-build.log
# Start or deploy the app. Capture the URL at this point or make the script output the URL to stdout.
provider-cli-to-deploy
# Example URL output:
# echo "http://127.0.0.1:3000"
```
--------------------------------
### Create Next.js App with Official Example
Source: https://nextjs.org/docs/app/api-reference/cli/create-next-app.md
Use the `--example` flag to initialize a new Next.js project based on an official example from the Next.js repository. Replace `[example-name]` with the desired example and `[your-project-name]` with your project's name.
```bash
pnpm create next-app --example [example-name] [your-project-name]
```
```bash
npx create-next-app@latest --example [example-name] [your-project-name]
```
```bash
yarn create next-app --example [example-name] [your-project-name]
```
```bash
bun create next-app --example [example-name] [your-project-name]
```
--------------------------------
### Install @next/bundle-analyzer Plugin
Source: https://nextjs.org/docs/app/guides/package-bundling.md
Install the `@next/bundle-analyzer` plugin using your preferred package manager.
```bash
pnpm add @next/bundle-analyzer
```
```bash
npm install @next/bundle-analyzer
```
```bash
yarn add @next/bundle-analyzer
```
```bash
bun add @next/bundle-analyzer
```
--------------------------------
### Install Jest and React Testing Library Dependencies
Source: https://nextjs.org/docs/app/guides/testing/jest.md
Install Jest, `jest-environment-jsdom`, and React Testing Library packages as development dependencies for manual setup.
```bash
pnpm add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```
```bash
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```
```bash
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```
```bash
bun add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
```
--------------------------------
### Generate Basic Jest Configuration File
Source: https://nextjs.org/docs/app/guides/testing/jest.md
Run this command to generate a basic Jest configuration file, which will guide you through setup prompts.
```bash
pnpm create jest@latest
```
```bash
npm init jest@latest
```
```bash
yarn create jest@latest
```
```bash
bun create jest@latest
```
--------------------------------
### Initialize Next.js app with Cypress example
Source: https://nextjs.org/docs/app/guides/testing/cypress.md
Use `create-next-app` with the `with-cypress` example to quickly set up a new Next.js project pre-configured for Cypress testing.
```bash
pnpm create next-app --example with-cypress with-cypress-app
```
```bash
npx create-next-app@latest --example with-cypress with-cypress-app
```
```bash
yarn create next-app --example with-cypress with-cypress-app
```
```bash
bun create next-app --example with-cypress with-cypress-app
```
--------------------------------
### Install web-push CLI Globally
Source: https://nextjs.org/docs/app/guides/progressive-web-apps.md
Install the `web-push` command-line interface globally using your preferred package manager to generate VAPID keys.
```bash
pnpm add -g web-push
```
```bash
npm install -g web-push
```
```bash
yarn global add web-push
```
```bash
bun add -g web-push
```
--------------------------------
### Run Next.js Development Server with Webpack
Source: https://nextjs.org/docs/app/guides/migrating/from-create-react-app.md
Starts the Next.js development server, explicitly using Webpack as the bundler, which is similar to Create React App's default setup.
```bash
next dev --webpack
```
--------------------------------
### Basic Markdown Syntax Example
Source: https://nextjs.org/docs/app/guides/mdx.md
Illustrates a simple Markdown example with bold text and a hyperlink.
```md
I **love** using [Next.js](https://nextjs.org/)
```
--------------------------------
### Create Next.js App with Playwright Example
Source: https://nextjs.org/docs/app/guides/testing/playwright.md
Use `create-next-app` with the `with-playwright` example to quickly set up a Next.js project pre-configured for Playwright E2E testing.
```bash
pnpm create next-app --example with-playwright with-playwright-app
```
```bash
npx create-next-app@latest --example with-playwright with-playwright-app
```
```bash
yarn create next-app --example with-playwright with-playwright-app
```
```bash
bun create next-app --example with-playwright with-playwright-app
```
--------------------------------
### Install OpenTelemetry Packages
Source: https://nextjs.org/docs/app/guides/open-telemetry.md
Install the core OpenTelemetry SDK and exporter packages required for manual configuration using your preferred package manager.
```bash
pnpm add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
yarn add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
bun add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
--------------------------------
### Install Next.js ESLint Plugin
Source: https://nextjs.org/docs/app/api-reference/config/eslint.md
Install `@next/eslint-plugin-next` as a development dependency using your preferred package manager.
```bash
pnpm add -D @next/eslint-plugin-next
```
```bash
npm i -D @next/eslint-plugin-next
```
```bash
yarn add --dev @next/eslint-plugin-next
```
```bash
bun add -d @next/eslint-plugin-next
```
--------------------------------
### Install @next/env with Bun
Source: https://nextjs.org/docs/app/guides/environment-variables.md
Install the `@next/env` package using Bun to load environment variables outside the Next.js runtime.
```bash
bun add @next/env
```
--------------------------------
### Install OpenTelemetry Core Packages
Source: https://nextjs.org/docs/pages/guides/open-telemetry.md
Install the necessary OpenTelemetry SDK and exporter packages using your preferred package manager to enable manual configuration.
```bash
pnpm add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
yarn add @opentelemetry/sdk-node @opentelemetry/resources @oplemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
```bash
bun add @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http
```
--------------------------------
### Install ESLint and Next.js Configuration
Source: https://nextjs.org/docs/app/api-reference/config/eslint.md
Install ESLint and the `eslint-config-next` package as development dependencies using your preferred package manager.
```bash
pnpm add -D eslint eslint-config-next
```
```bash
npm i -D eslint eslint-config-next
```
```bash
yarn add --dev eslint eslint-config-next
```
```bash
bun add -d eslint eslint-config-next
```
--------------------------------
### Example tsconfig for Relaxed Build Checks
Source: https://nextjs.org/docs/app/api-reference/config/typescript.md
An example `tsconfig.build.json` that extends the main `tsconfig.json` but relaxes specific `compilerOptions` like `useUnknownInCatchVariables` for build purposes.
```json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"useUnknownInCatchVariables": false
}
}
```
--------------------------------
### Install Vitest and Dependencies with bun
Source: https://nextjs.org/docs/app/guides/testing/vitest.md
Install required development dependencies for Vitest, React Testing Library, and JSDOM using bun, with an option for TypeScript-specific packages.
```bash
# Using TypeScript
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom vite-tsconfig-paths
```
```bash
# Using JavaScript
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
```
--------------------------------
### GET /api
Source: https://nextjs.org/docs/app/guides/backend-for-frontend.md
This endpoint handles GET requests to the `/api` route. It serves as a basic example of a public HTTP endpoint in a Next.js application.
```APIDOC
## GET /api
### Description
This endpoint handles GET requests to the `/api` route. It serves as a basic example of a public HTTP endpoint in a Next.js application.
### Method
GET
### Endpoint
/api
```
--------------------------------
### Create Next.js App with Public GitHub Example
Source: https://nextjs.org/docs/app/api-reference/cli/create-next-app.md
Initialize a new Next.js project from any public GitHub repository using the `--example` flag with the repository's URL. Replace `https://github.com/.../` with the actual URL and `[your-project-name]` with your project's name.
```bash
pnpm create next-app --example "https://github.com/.../" [your-project-name]
```
```bash
npx create-next-app@latest --example "https://github.com/.../" [your-project-name]
```
```bash
yarn create next-app --example "https://github.com/.../" [your-project-name]
```
```bash
bun create next-app --example "https://github.com/.../" [your-project-name]
```
--------------------------------
### Implement CacheHandler get() Method
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheHandlers.md
Example implementation of the `get` method to retrieve a cache entry, including expiration checks and handling `undefined` for missing or expired entries.
```javascript
const cacheHandler = {
async get(cacheKey, softTags) {
const entry = cache.get(cacheKey)
if (!entry) return undefined
// Check if expired
const now = Date.now()
if (now > entry.timestamp + entry.revalidate * 1000) {
return undefined
}
return entry
},
}
```
--------------------------------
### Initialize Playwright Manually
Source: https://nextjs.org/docs/app/guides/testing/playwright.md
Run this command to manually install and configure Playwright in an existing project. It will guide you through setting up the `playwright.config.ts` file.
```bash
pnpm create playwright
```
```bash
npm init playwright
```
```bash
yarn create playwright
```
```bash
bun create playwright
```
--------------------------------
### Create and Run a New Next.js Application
Source: https://nextjs.org/docs/app/getting-started/installation.md
Use these commands to quickly set up a new Next.js project, navigate into its directory, and start the development server. The `--yes` flag automatically accepts default configurations including TypeScript, Tailwind CSS, ESLint, and the App Router.
```bash
pnpm create next-app@latest my-app --yes
cd my-app
pnpm dev
```
```bash
npx create-next-app@latest my-app --yes
cd my-app
npm run dev
```
```bash
yarn create next-app@latest my-app --yes
cd my-app
yarn dev
```
```bash
bun create next-app@latest my-app --yes
cd my-app
bun dev
```
--------------------------------
### Generate Static JSON with Route Handlers
Source: https://nextjs.org/docs/app/guides/static-exports.md
Use a GET Route Handler to generate a static JSON file during `next build`. This example shows how to return a simple JSON response.
```ts
export async function GET() {
return Response.json({ name: 'Lee' })
}
```
```js
export async function GET() {
return Response.json({ name: 'Lee' })
}
```
--------------------------------
### Initialize Next.js Project with API Endpoint Example
Source: https://nextjs.org/docs/app/guides/backend-for-frontend.md
Use `create-next-app` with the `--api` flag to scaffold a new Next.js project that includes an example `route.ts` file, demonstrating how to create an API endpoint.
```bash
pnpm create next-app --api
```
```bash
npx create-next-app@latest --api
```
```bash
yarn create next-app --api
```
```bash
bun create next-app --api
```
--------------------------------
### Example Route Handler with Force Cache
Source: https://nextjs.org/docs/app/api-reference/functions/revalidatePath.md
This snippet demonstrates a GET route handler that fetches data with `cache: 'force-cache'`. `revalidatePath('/api/data')` would invalidate the cache for this specific handler.
```typescript
export async function GET() {
const data = await fetch('https://api.vercel.app/blog', {
cache: 'force-cache',
})
return Response.json(await data.json())
}
```
--------------------------------
### Client-side Instrumentation Setup (TypeScript/JavaScript)
Source: https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client.md
Use this file to set up client-side performance monitoring, analytics initialization, and error tracking before the Next.js application becomes interactive. Place the file in the root or `src` folder.
```ts
// Set up performance monitoring
performance.mark('app-init')
// Initialize analytics
console.log('Analytics initialized')
// Set up error tracking
window.addEventListener('error', (event) => {
// Send to your error tracking service
reportError(event.error)
})
```
```js
// Set up performance monitoring
performance.mark('app-init')
// Initialize analytics
console.log('Analytics initialized')
// Set up error tracking
window.addEventListener('error', (event) => {
// Send to your error tracking service
reportError(event.error)
})
```
--------------------------------
### Fetch Data in not-found.js Server Component (TS/JS)
Source: https://nextjs.org/docs/app/api-reference/file-conventions/not-found.md
Mark `not-found.js` as `async` to fetch data on the server. This example uses `headers()` to get the domain and then `getSiteData()` to retrieve site-specific information.
```tsx
import Link from 'next/link'
import { headers } from 'next/headers'
export default async function NotFound() {
const headersList = await headers()
const domain = headersList.get('host')
const data = await getSiteData(domain)
return (
Not Found: {data.name}
Could not find requested resource
View all posts
)
}
```
```jsx
import Link from 'next/link'
import { headers } from 'next/headers'
export default async function NotFound() {
const headersList = await headers()
const domain = headersList.get('host')
const data = await getSiteData(domain)
return (
Not Found: {data.name}
Could not find requested resource
View all posts
)
}
```
--------------------------------
### Deferring Data Fetching in Root Layout (Next.js)
Source: https://nextjs.org/docs/app/guides/single-page-applications.md
Call a server-side function to get a Promise in the root layout without awaiting it. This allows Next.js to start data fetching early on the server and stream the response.
```tsx
import { UserProvider } from './user-provider'
import { getUser } from './user' // some server-side function
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
let userPromise = getUser() // do NOT await
return (
{children}
)
}
```
```jsx
import { UserProvider } from './user-provider'
import { getUser } from './user' // some server-side function
export default function RootLayout({ children }) {
let userPromise = getUser() // do NOT await
return (
{children}
)
}
```
--------------------------------
### Start Standalone Server with Custom Port and Hostname
Source: https://nextjs.org/docs/pages/api-reference/config/next-config-js/output.md
Set `PORT` and `HOSTNAME` environment variables before running `server.js` to specify the server's listening address and port.
```bash
PORT=8080 HOSTNAME=0.0.0.0 node server.js
```
--------------------------------
### Basic Usage of create-next-app with Package Managers
Source: https://nextjs.org/docs/app/api-reference/cli/create-next-app.md
Initialize a new Next.js project using the `create-next-app` CLI with your preferred package manager. Replace `[project-name]` with your desired directory name and `[options]` for specific configurations.
```bash
pnpm create next-app [project-name] [options]
```
```bash
npx create-next-app@latest [project-name] [options]
```
```bash
yarn create next-app [project-name] [options]
```
```bash
bun create next-app [project-name] [options]
```
--------------------------------
### Run next experimental-analyze with various package managers
Source: https://nextjs.org/docs/app/api-reference/cli/next.md
Execute the `next experimental-analyze` command using different package managers to analyze your application's bundle output. By default, this starts a local server for interactive exploration.
```bash
pnpm next experimental-analyze
```
```bash
npx next experimental-analyze
```
```bash
yarn next experimental-analyze
```
```bash
bunx next experimental-analyze
```
--------------------------------
### Implement a Custom Cache Handler (cache-handler.js)
Source: https://nextjs.org/docs/pages/guides/self-hosting.md
Create a `cache-handler.js` file to define a custom cache handler class with `get`, `set`, `revalidateTag`, and `resetRequestCache` methods. This example uses an in-memory `Map` but can be extended for durable storage like Redis or AWS S3.
```jsx
const cache = new Map()
module.exports = class CacheHandler {
constructor(options) {
this.options = options
}
async get(key) {
// This could be stored anywhere, like durable storage
return cache.get(key)
}
async set(key, data, ctx) {
// This could be stored anywhere, like durable storage
cache.set(key, {
value: data,
lastModified: Date.now(),
tags: ctx.tags
})
}
async revalidateTag(tags) {
// tags is either a string or an array of strings
tags = [tags].flat()
// Iterate over all entries in the cache
for (let [key, value] of cache) {
// If the value's tags include the specified tag, delete this entry
if (value.tags.some((tag) => tags.includes(tag))) {
cache.delete(key)
}
}
}
// If you want to have temporary in memory cache for a single request that is reset
// before the next request you can leverage this method
resetRequestCache() {}
}
```
--------------------------------
### Creating a Basic 'Hello World' API Route
Source: https://nextjs.org/docs/pages/building-your-application/routing/api-routes.md
This example demonstrates how to create a basic API route that responds with a JSON message. Files in `pages/api` are treated as API endpoints.
```typescript
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
```
```javascript
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
```
--------------------------------
### Define Web App Manifest in Next.js (TypeScript/JavaScript)
Source: https://nextjs.org/docs/app/guides/progressive-web-apps.md
This snippet defines the web app manifest for a Next.js PWA, specifying its name, display properties, start URL, theme colors, and icons. This file enables home screen installation and a native app-like experience.
```tsx
import type { MetadataRoute } from 'next'
export default function manifest(): MetadataRoute.Manifest {
return {
name: 'Next.js PWA',
short_name: 'NextPWA',
description: 'A Progressive Web App built with Next.js',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#000000',
icons: [
{
src: '/icon-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: '/icon-512x512.png',
sizes: '512x512',
type: 'image/png',
},
],
}
}
```
```jsx
export default function manifest() {
return {
name: 'Next.js PWA',
short_name: 'NextPWA',
description: 'A Progressive Web App built with Next.js',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#000000',
icons: [
{
src: '/icon-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: '/icon-512x512.png',
sizes: '512x512',
type: 'image/png',
},
],
}
}
```
--------------------------------
### Implementing a Basic Next.js Adapter (JavaScript)
Source: https://nextjs.org/docs/app/api-reference/adapters/creating-an-adapter.md
This example shows a minimal adapter with `modifyConfig` to adjust Next.js configuration and `onBuildComplete` to process build artifacts and routing information.
```js
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'my-custom-adapter',
async modifyConfig(config, { phase }) {
// Modify the Next.js config based on the build phase
if (phase === 'phase-production-build') {
return {
...config,
// Add your modifications
}
}
return config
},
async onBuildComplete({
routing,
outputs,
projectDir,
repoRoot,
distDir,
config,
nextVersion,
buildId,
}) {
// Process the build output
console.log('Build completed with', outputs.pages.length, 'pages')
console.log('Build ID:', buildId)
console.log('Dynamic routes:', routing.dynamicRoutes.length)
// Access emitted output entries
for (const page of outputs.pages) {
console.log('Page:', page.pathname, 'at', page.filePath)
}
for (const apiRoute of outputs.pagesApi) {
console.log('API Route:', apiRoute.pathname, 'at', apiRoute.filePath)
}
for (const appPage of outputs.appPages) {
console.log('App Page:', appPage.pathname, 'at', appPage.filePath)
}
for (const prerender of outputs.prerenders) {
console.log('Prerendered:', prerender.pathname)
}
},
}
module.exports = adapter
```
--------------------------------
### Install Tailwind CSS v3 and Initialize Configuration
Source: https://nextjs.org/docs/app/guides/tailwind-v3-css.md
Install Tailwind CSS v3 and its peer dependencies using your preferred package manager, then generate `tailwind.config.js` and `postcss.config.js` files.
```bash
pnpm add -D tailwindcss@^3 postcss autoprefixer
npx tailwindcss init -p
```
```bash
npm install -D tailwindcss@^3 postcss autoprefixer
npx tailwindcss init -p
```
```bash
yarn add -D tailwindcss@^3 postcss autoprefixer
npx tailwindcss init -p
```
```bash
bun add -D tailwindcss@^3 postcss autoprefixer
bunx tailwindcss init -p
```
--------------------------------
### Run Development Server with Webpack
Source: https://nextjs.org/docs/app/guides/local-development.md
Starts the Next.js development server, explicitly opting into Webpack instead of the default Turbopack bundler.
```bash
pnpm dev --webpack
```
```bash
npm run dev -- --webpack
```
```bash
yarn dev --webpack
```
```bash
bun run dev --webpack
```
--------------------------------
### GET
Source: https://nextjs.org/docs/app/api-reference/file-conventions/route.md
Handles HTTP GET requests for a given route, typically used for retrieving data.
```APIDOC
## GET [ROUTE_PATH]
### Description
Handles HTTP GET requests for the route defined by the `route.js` file's location. This method is typically used to retrieve data from the server.
### Method
GET
### Endpoint
The route path defined by the `route.js` file's location in the `app` directory. This can include dynamic segments (e.g., `/users/[id]`).
### Parameters
#### Path Parameters
- **[dynamic_route_segment]** (string or string[]) - Required (if defined in route) - Corresponds to dynamic segments in the route path (e.g., `id` in `/users/[id]`, `team` in `/dashboard/[team]`, `slug` in `/blog/[...slug]`). These values are accessible within the handler via `context.params`.
#### Query Parameters
- **[param_name]** (string) - Optional - Query parameters appended to the URL (e.g., `?sort=asc`). These are accessible within the handler via `request.nextUrl.searchParams`.
#### Request Body
(Not applicable for GET requests)
### Request Example
(Not applicable for GET requests)
### Response
#### Success Response (200)
Returns a `Response` object. The content and structure of the response body are entirely defined by the Route Handler implementation.
#### Response Example
```json
{
"message": "Hello World"
}
```
```
--------------------------------
### Basic Next.js CLI Usage with Package Managers
Source: https://nextjs.org/docs/app/api-reference/cli/next.md
Demonstrates the basic syntax for running Next.js CLI commands using pnpm, npm, yarn, and bun. When using `npm run`, remember to use `--` before CLI flags so npm forwards them to `next`.
```bash
pnpm next [command] [options]
```
```bash
npx next [command] [options]
```
```bash
yarn next [command] [options]
```
```bash
bunx next [command] [options]
```
--------------------------------
### Install Cypress as a Development Dependency
Source: https://nextjs.org/docs/app/guides/testing/cypress.md
Installs Cypress as a development dependency in your project using various package managers.
```bash
pnpm add -D cypress
```
```bash
npm install -D cypress
```
```bash
yarn add -D cypress
```
```bash
bun add -D cypress
```
--------------------------------
### Verify Static Prerendering with next build (Terminal)
Source: https://nextjs.org/docs/app/guides/public-static-pages.md
Run `next build` to confirm that the `/products` route, containing only static components, is marked as prerendered static content.
```bash
Route (app) Revalidate Expire
┌ ○ /products 15m 1y
└ ○ /_not-found
○ (Static) prerendered as static content
```
--------------------------------
### Install Next.js Dependency
Source: https://nextjs.org/docs/app/guides/migrating/from-vite.md
Installs the latest version of Next.js as a project dependency using various package managers.
```bash
pnpm add next@latest
```
```bash
npm install next@latest
```
```bash
yarn add next@latest
```
```bash
bun add next@latest
```
--------------------------------
### Run Next.js Development Server (bun)
Source: https://nextjs.org/docs/app/guides/migrating/from-create-react-app.md
Start the Next.js development server using bun to run your application locally.
```bash
bun dev
```
--------------------------------
### Install @next/third-parties library
Source: https://nextjs.org/docs/app/guides/third-party-libraries.md
Install the experimental `@next/third-parties` library along with Next.js to optimize third-party integrations. Use the `latest` or `canary` flags due to active development.
```bash
pnpm add @next/third-parties@latest next@latest
```
```bash
npm install @next/third-parties@latest next@latest
```
```bash
yarn add @next/third-parties@latest next@latest
```
```bash
bun add @next/third-parties@latest next@latest
```
--------------------------------
### Install eslint-config-prettier
Source: https://nextjs.org/docs/app/api-reference/config/eslint.md
Install `eslint-config-prettier` as a development dependency to resolve conflicts between ESLint's formatting rules and Prettier.
```bash
pnpm add -D eslint-config-prettier
```
```bash
npm i -D eslint-config-prettier
```
```bash
yarn add --dev eslint-config-prettier
```
```bash
bun add -d eslint-config-prettier
```
--------------------------------
### Install Sass in Next.js
Source: https://nextjs.org/docs/pages/guides/sass.md
Install the Sass package as a development dependency in your Next.js project using various package managers.
```bash
pnpm add -D sass
```
```bash
npm install --save-dev sass
```
```bash
yarn add -D sass
```
```bash
bun add -D sass
```
--------------------------------
### Start Next.js Standalone Server
Source: https://nextjs.org/docs/app/api-reference/config/next-config-js/output.md
Run the generated `server.js` file from the `standalone` directory to start the minimal Next.js server, optionally defining `PORT` or `HOSTNAME` environment variables.
```bash
node .next/standalone/server.js
```
```bash
PORT=8080 HOSTNAME=0.0.0.0 node server.js
```
--------------------------------
### Install @vercel/otel and OpenTelemetry dependencies
Source: https://nextjs.org/docs/app/guides/open-telemetry.md
Installs the `@vercel/otel` package and required OpenTelemetry SDKs using various package managers.
```bash
pnpm add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
```bash
npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
```bash
yarn add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
```bash
bun add @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation
```
--------------------------------
### Next.js Info Command Output Example
Source: https://nextjs.org/docs/app/api-reference/cli/next.md
This snippet displays the typical output from the `next info` command, which provides essential system, binary, and package version details for debugging Next.js applications.
```bash
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 23.6.0
Available memory (MB): 65536
Available CPU cores: 10
Binaries:
Node: 20.12.0
npm: 10.5.0
Yarn: 1.22.19
pnpm: 9.6.0
Relevant Packages:
next: 15.0.0-canary.115 // Latest available version is detected (15.0.0-canary.115).
eslint-config-next: 14.2.5
react: 19.0.0-rc
react-dom: 19.0.0
typescript: 5.5.4
Next.js Config:
output: N/A
```
--------------------------------
### Install @next/env with Yarn
Source: https://nextjs.org/docs/app/guides/environment-variables.md
Install the `@next/env` package using Yarn to load environment variables outside the Next.js runtime.
```bash
yarn add @next/env
```
--------------------------------
### Next.js Upgrade Codemod Examples
Source: https://nextjs.org/docs/app/guides/upgrading/codemods.md
Examples demonstrating how to use the `upgrade` codemod with different revision types (patch, minor, major), specific versions, or release channels like `canary`.
```bash
# Upgrade to the latest patch (e.g. 16.0.7 -> 16.0.8)
npx @next/codemod upgrade patch
```
```bash
# Upgrade to the latest minor (e.g. 15.3.7 -> 15.4.8). This is the default.
npx @next/codemod upgrade minor
```
```bash
# Upgrade to the latest major (e.g. 15.5.7 -> 16.0.7)
npx @next/codemod upgrade major
```
```bash
# Upgrade to a specific version
npx @next/codemod upgrade 16
```
```bash
# Upgrade to the canary release
npx @next/codemod upgrade canary
```
--------------------------------
### Install @next/env with npm
Source: https://nextjs.org/docs/app/guides/environment-variables.md
Install the `@next/env` package using npm to load environment variables outside the Next.js runtime.
```bash
npm install @next/env
```
--------------------------------
### Install @next/env with pnpm
Source: https://nextjs.org/docs/app/guides/environment-variables.md
Install the `@next/env` package using pnpm to load environment variables outside the Next.js runtime.
```bash
pnpm add @next/env
```
--------------------------------
### Numerical Sorting Example in App Router Section
Source: https://nextjs.org/docs/community/contribution-guide.md
This example demonstrates using two-digit numerical prefixes to sort files in the app router section, ordering them by the sequence developers should learn the concepts.
```txt
01-getting-started
├── 01-installation.mdx
├── 02-project-structure.mdx
├── 03-layouts-and-pages.mdx
└── ...
```
--------------------------------
### Example MDX Page Content
Source: https://nextjs.org/docs/app/guides/mdx.md
Demonstrates how to write MDX content, including importing React components and using Markdown syntax.
```mdx
import { MyComponent } from 'my-component'
# Welcome to my MDX page!
This is some **bold** and _italics_ text.
This is a list in markdown:
- One
- Two
- Three
Checkout my React component:
```