### Create a basic JSON response API Route in Next.js (TypeScript/JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This snippet demonstrates how to create a fundamental API Route in Next.js that returns a JSON response with a 200 status code. API Routes are server-side only and are mapped from `pages/api/*` to `/api/*`. ```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!' }) } ``` -------------------------------- ### Implement Catch-all Dynamic Route Segments in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/dynamic-routes.mdx This example illustrates how to define a catch-all dynamic route segment using `[...slug]`. This allows the route to match multiple subsequent path segments, which are then provided as an array in the `slug` property of the `params` object to the page component. ```javascript // app/shop/[...slug]/page.js export default function Page({ params }) { const { slug } = params; // slug will be an array like ['a', 'b'] return (

Catch-all Page

Path segments: {slug.join('/')}

); } ``` -------------------------------- ### Define Catch-All API Route in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This code defines a Next.js API route using the `[...slug]` convention to catch all path segments. It demonstrates how to access the matched segments as an array from `req.query.slug` and use them in the response. ```ts import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { const { slug } = req.query res.end(`Post: ${slug.join(', ')}`) } ``` ```js export default function handler(req, res) { const { slug } = req.query res.end(`Post: ${slug.join(', ')}`) } ``` -------------------------------- ### Next.js router.push to dynamic route Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/04-api-reference/03-functions/use-router.mdx Illustrates navigating to a dynamic route like `pages/post/[pid].js` using `router.push`. The example pushes a specific path (`/post/abc`) which matches the dynamic route pattern. ```jsx import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return ( ) } ``` -------------------------------- ### Enable Next.js API Route External Resolver (JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Explains how to enable the `externalResolver` flag for a Next.js API route. This flag tells the server that an external resolver (e.g., Express or Connect) is handling the route, which prevents warnings for unresolved requests. ```js export const config = { api: { externalResolver: true, }, } ``` -------------------------------- ### Incorrectly Using Shallow Routing for Page Navigation in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/03-linking-and-navigating.mdx This snippet demonstrates an incorrect attempt to use shallow routing for navigating to a new page (`/about`) while also changing query parameters. Despite setting `shallow: true`, Next.js will still unload the current page and load the new one because it's a different route, thereby defeating the purpose of shallow routing and triggering data fetching. ```js router.push('/?counter=10', '/about?counter=10', { shallow: true }) ``` -------------------------------- ### Handle specific HTTP methods in Next.js API Routes (TypeScript/JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This example demonstrates how to implement conditional logic within a Next.js API Route handler to respond differently based on the incoming HTTP request method. By checking `req.method`, you can process distinct logic for methods like 'POST' or 'GET' within a single route file. ```typescript import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } } ``` ```javascript export default function handler(req, res) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } } ``` -------------------------------- ### Implement Dynamic Routes in Next.js API Handlers Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This snippet shows how to create dynamic API routes in Next.js, mirroring the behavior of dynamic pages. It captures a dynamic parameter (e.g., `pid`) from the URL path, such as `/api/post/abc`, and uses it in the response, demonstrating how to access and utilize variable segments in the API endpoint. ```ts import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(req: NextApiRequest, res: NextApiResponse) { const { pid } = req.query res.end(`Post: ${pid}`) } ``` ```js export default function handler(req, res) { const { pid } = req.query res.end(`Post: ${pid}`) } ``` -------------------------------- ### GET /users/[id] (Dynamic Route) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/route.mdx Handles GET requests for dynamic routes, extracting path parameters using the `context` object and `RouteContext` helper. ```APIDOC ## GET /users/[id] ### Description Handles GET requests for dynamic routes, extracting path parameters using the `context` object and `RouteContext` helper. ### Method GET ### Endpoint /users/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the user. #### Handler Function Parameters - **_req** (NextRequest) - Optional - An extended Web Request object (often ignored when using `context.params`). - **ctx** (RouteContext<'/users/[id]'>) - Optional - Helper providing strongly typed `params`. - **ctx.params** (object) - An object containing dynamic route parameters, e.g., `{ id: '123' }`. ### Request Example (No explicit request body for GET) ### Response #### Success Response (200) - **id** (string) - The ID extracted from the route. #### Response Example { "id": "123" } ``` -------------------------------- ### Access Dynamic Route Parameters in Next.js Route Handlers Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/route.mdx Demonstrates how to retrieve dynamic route parameters from the `context` object in a Next.js Route Handler. The `params` object, available through destructuring `context`, is a promise that resolves to an object containing the dynamic segments of the URL, such as `team` in `app/dashboard/[team]/route.ts`. ```ts export async function GET( request: Request, { params }: { params: Promise<{ team: string }> } ) { const { team } = await params } ``` ```js export async function GET(request, { params }) { const { team } = await params } ``` -------------------------------- ### GET /api/post/[...slug] Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Demonstrates how to create a catch-all API route that matches multiple path segments and collects them into a 'slug' array. This is useful for handling dynamic paths with variable depth. ```APIDOC ## GET /api/post/[...slug] ### Description This endpoint uses a catch-all route to capture multiple path segments following `/api/post/`. For example, `/api/post/a/b/c` will result in `slug` being `["a", "b", "c"]`. ### Method GET ### Endpoint /api/post/[...slug] ### Parameters #### Query Parameters - **slug** (array of strings) - Required - An array containing all matched path segments after `/api/post/`. ### Request Example ``` GET /api/post/hello/world ``` ### Response #### Success Response (200) - **body** (string) - A string showing the joined slug segments, formatted as `Post: [segment1], [segment2], ...`. #### Response Example ``` Post: a, b, c ``` ``` -------------------------------- ### Create GET route handler - TypeScript/JavaScript Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/15-route-handlers.mdx Defines a basic GET route handler exported from a route.ts/route.js file inside the app directory. No external dependencies are required beyond Next.js; the handler receives a Request object and should return a Response. Note: route files cannot live at the same route segment as page.js. ```typescript export async function GET(request: Request) {} ``` ```javascript export async function GET(request) {} ``` -------------------------------- ### GET /api/post/[[...slug]] Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Illustrates an optional catch-all API route that matches the base path (`/api/post`) as well as multiple path segments. The `slug` array will be empty if only the base path is matched. ```APIDOC ## GET /api/post/[[...slug]] ### Description This endpoint provides an optional catch-all mechanism, allowing it to match the base path `/api/post` (where `slug` is an empty object) or paths with segments like `/api/post/a/b`. The `slug` query parameter will be an array if segments are present, or absent otherwise. ### Method GET ### Endpoint /api/post/[[...slug]] ### Parameters #### Query Parameters - **slug** (array of strings) - Optional - An array containing all matched path segments after `/api/post/`. This parameter will be an empty array or undefined if only the base path `/api/post` is requested. ### Request Example ``` GET /api/post/optional/path ``` ### Response #### Success Response (200) - **body** (string) - A string showing the joined slug segments, or `Post: ` if no segments are provided. #### Response Example ```json { "query_for_post_a": { "slug": ["a"] }, "query_for_base_post": { } } ``` ``` -------------------------------- ### Read Active Route Segment with `useSelectedLayoutSegment` in Next.js Layout Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/parallel-routes.mdx This snippet demonstrates how to use the `useSelectedLayoutSegment` hook in a Next.js App Router layout. It accepts a `parallelRoutesKey` to read the active route segment within a specified parallel route slot, enabling dynamic logic based on the currently active route. ```tsx 'use client' import { useSelectedLayoutSegment } from 'next/navigation' export default function Layout({ auth }: { auth: React.ReactNode }) { const loginSegment = useSelectedLayoutSegment('auth') // ... } ``` ```jsx 'use client' import { useSelectedLayoutSegment } from 'next/navigation' export default function Layout({ auth }) { const loginSegment = useSelectedLayoutSegment('auth') // ... } ``` -------------------------------- ### Conditional proxy routing with TypeScript Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/proxy.mdx TypeScript proxy middleware that conditionally rewrites URLs based on pathname patterns, redirecting /about and /dashboard routes to specific internal paths. ```typescript import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function proxy(request: NextRequest) { if (request.nextUrl.pathname.startsWith('/about')) { return NextResponse.rewrite(new URL('/about-2', request.url)) } if (request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.rewrite(new URL('/dashboard/user', request.url)) } } ``` ```javascript import { NextResponse } from 'next/server' export function proxy(request) { if (request.nextUrl.pathname.startsWith('/about')) { return NextResponse.rewrite(new URL('/about-2', request.url)) } if (request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.rewrite(new URL('/dashboard/user', request.url)) } } ``` -------------------------------- ### Import App Route Module Compiled Dependency in JavaScript Source: https://github.com/vercel/next.js/blob/canary/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/app-route/output.md This snippet performs a direct import of the `app-route/module.compiled` from the Next.js server's future route modules. It represents a fundamental dependency for setting up application routes. ```javascript import '../../server/future/route-modules/app-route/module.compiled'; ``` -------------------------------- ### Handle dynamic route segments in Next.js Route Handlers Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/route.mdx This snippet demonstrates how to extract dynamic parameters from a URL path within a Next.js Route Handler. It defines a `GET` function that accesses the `slug` parameter from the `params` object, enabling the handler to serve dynamic content based on the URL segment, such as `/items/a`. ```typescript export async function GET( request: Request, { params }: { params: Promise<{ slug: string }> } ) { const { slug } = await params // 'a', 'b', or 'c' } ``` ```javascript export async function GET(request, { params }) { const { slug } = await params // 'a', 'b', or 'c' } ``` -------------------------------- ### GET /api/hello Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Demonstrates an API route that streams Server-Sent Events (SSE) responses. It sends incremental data over time, typically used for real-time updates or long-polling scenarios. ```APIDOC ## GET /api/hello ### Description This endpoint provides a streaming response using Server-Sent Events (SSE). It sends a series of data events over a period, with each event containing an incrementing number. It sets appropriate headers for SSE communication. ### Method GET ### Endpoint /api/hello ### Parameters (None) ### Request Example ``` GET /api/hello ``` ### Response #### Success Response (200) - **Content-Type** (header) - `text/event-stream` - **Cache-Control** (header) - `no-store` - **data** (string) - A series of Server-Sent Events, each containing a number from 0 to 9, sent approximately every second. #### Response Example ``` data: 0 data: 1 data: 2 ... data: 9 ``` ``` -------------------------------- ### Define Main Login Page Route in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/parallel-routes.mdx This code defines the primary `/login` route that renders the `` component. This page serves as the standalone login interface and is displayed when a user directly navigates to `/login` or refreshes the page on this route. ```tsx import { Login } from '@/app/ui/login' export default function Page() { return } ``` ```jsx import { Login } from '@/app/ui/login' export default function Page() { return } ``` -------------------------------- ### Create Optional Catch-all Dynamic Route Segments in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/dynamic-routes.mdx This snippet demonstrates how to implement an optional catch-all dynamic route segment using `[[...slug]]`. This convention matches both the base path and any subsequent path segments, providing an array for `slug` or `undefined` if no segments are present. ```javascript // app/shop/[[...slug]]/page.js export default function Page({ params }) { const { slug } = params; // slug will be an array or undefined return (

Optional Catch-all Page

{slug ?

Path segments: {slug.join('/')}

:

No specific segments.

}
); } ``` -------------------------------- ### Define Next.js API Route handler function parameters (TypeScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This snippet illustrates the standard function signature for a Next.js API Route handler. It accepts `req` as an instance of `NextApiRequest` for the incoming request and `res` as `NextApiResponse` for sending the response, both imported from the `next` module. ```tsx export default function handler(req: NextApiRequest, res: NextApiResponse) { // ... } ``` -------------------------------- ### Cache GET route with force-static - TypeScript/JavaScript Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/15-route-handlers.mdx Opt into caching for a GET route by exporting a route config (dynamic = 'force-static') and returning a JSON response. This example fetches data from an external API using fetch and environment variables, then returns Response.json({ data }). Only GET methods can be cached this way; other HTTP methods remain uncached. ```typescript export const dynamic = 'force-static' export async function GET() { const res = await fetch('https://data.mongodb-api.com/...', { headers: { 'Content-Type': 'application/json', 'API-Key': process.env.DATA_API_KEY, }, }) const data = await res.json() return Response.json({ data }) } ``` ```javascript export const dynamic = 'force-static' export async function GET() { const res = await fetch('https://data.mongodb-api.com/...', { headers: { 'Content-Type': 'application/json', 'API-Key': process.env.DATA_API_KEY, }, }) const data = await res.json() return Response.json({ data }) } ``` -------------------------------- ### Access Dynamic Route Params in Next.js Server Layout Component Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/layout.mdx This Next.js server component, `DashboardLayout`, shows how to access dynamic route parameters (`params`) from the URL within an `async` layout. It safely destructs the `team` property from the `params` promise to display personalized content, leveraging dynamic routing capabilities. ```tsx export default async function DashboardLayout({ children, params, }: { children: React.ReactNode params: Promise<{ team: string }> }) { const { team } = await params return (

Welcome to {team}'s Dashboard

{children}
) } ``` ```jsx export default async function DashboardLayout({ children, params }) { const { team } = await params return (

Welcome to {team}'s Dashboard

{children}
) } ``` -------------------------------- ### Configure Next.js Rewrites for Multi-Zone Path Routing Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/multi-zones.mdx This snippet demonstrates how to configure Next.js `rewrites` in `next.config.js` to route requests to different zones in a multi-zone setup. It shows how to define rewrite rules for specific paths and their static assets, directing them to the `BLOG_DOMAIN`. The `destination` should be a full URL, and URL paths must be unique to avoid routing conflicts. ```javascript async rewrites() { return [ { source: '/blog', destination: `${process.env.BLOG_DOMAIN}/blog`, }, { source: '/blog/:path+', destination: `${process.env.BLOG_DOMAIN}/blog/:path+`, }, { source: '/blog-static/:path+', destination: `${process.env.BLOG_DOMAIN}/blog-static/:path+`, } ]; } ``` -------------------------------- ### Define Standard Dynamic Route Segments in Next.js Pages Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/dynamic-routes.mdx This example demonstrates how to create a standard dynamic route segment using square brackets in the folder name, e.g., `[slug]`. The `slug` parameter is passed to the page component via the `params` prop, allowing the page to render content based on the dynamic part of the URL. ```tsx export default async function Page({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params return
My Post: {slug}
} ``` ```jsx export default async function Page({ params }) { const { slug } = await params return
My Post: {slug}
} ``` -------------------------------- ### Intercept Login Route to Render Modal in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/parallel-routes.mdx This code intercepts the `/login` route within the `@auth` parallel route slot using the `(.)login` convention. It imports the `` and `` components, rendering the login form inside the modal component to display it as an overlay. ```tsx import { Modal } from '@/app/ui/modal' import { Login } from '@/app/ui/login' export default function Page() { return ( ) } ``` ```jsx import { Modal } from '@/app/ui/modal' import { Login } } from '@/app/ui/login' export default function Page() { return ( ) } ``` -------------------------------- ### Define GET API Route Handler in Next.js App Directory Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/migrating/app-router-migration.mdx This snippet illustrates how to create a GET request handler using Route Handlers in the Next.js `app` directory. Route Handlers replace traditional API Routes and leverage Web Request and Response APIs for handling HTTP requests, supporting both TypeScript and JavaScript. ```ts export async function GET(request: Request) {} ``` ```js export async function GET(request) {} ``` -------------------------------- ### Use Statically Typed Routes with Link in Next.js Pages Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/05-config/02-typescript.mdx This example shows a Next.js page component using `next/link` with a statically typed `href`. It demonstrates how to cast a string to `Route` when the route might involve a proxy or non-literal path. ```tsx import type { Route } from 'next' export default function Page() { return Link Text } ``` -------------------------------- ### Generate Static Params for Dynamic Routes (Next.js/React) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/04-linking-and-navigating.mdx This snippet illustrates how to use the `generateStaticParams` function in a dynamic route (`app/blog/[slug]/page.tsx` or `.js`) to pre-render dynamic segments at build time. It fetches posts and maps them to an array of `slug` parameters, ensuring the route is statically generated instead of falling back to dynamic rendering at request time. ```tsx export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } export default async function Page({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params // ... } ``` ```jsx export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } export default async function Page({ params }) { const { slug } = await params // ... } ``` -------------------------------- ### Configure Next.js i18n for Sub-path Routing Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/02-guides/internationalization.mdx This configuration sets up Next.js internationalization using the sub-path routing strategy. It defines a list of supported locales (`en-US`, `fr`, `nl-NL`) and a default locale (`en-US`), where the locale identifier is included directly in the URL path (e.g., `/fr/blog`). This approach simplifies routing for different language versions of your content. ```js module.exports = { i18n: { locales: ['en-US', 'fr', 'nl-NL'], defaultLocale: 'en-US', }, } ``` -------------------------------- ### Type Next.js Route Handler Context with RouteContext Helper (TypeScript) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/15-route-handlers.mdx This example demonstrates how to use the `RouteContext` helper in TypeScript to provide type safety for the `context` parameter in a Next.js Route Handler. By typing the context with `RouteContext<'path/to/[param]'>`, developers can safely destructure and access dynamic route parameters like `id` from `ctx.params`. ```typescript import type { NextRequest } from 'next/server' export async function GET(_req: NextRequest, ctx: RouteContext<'/users/[id]'>) { const { id } = await ctx.params return Response.json({ id }) } ``` -------------------------------- ### Revalidate Next.js data and re-render route segments by path Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/caching.mdx This snippet illustrates how to use `revalidatePath('/')` to manually revalidate data and re-render all route segments below a specified path. This operation purges both the Data Cache and the Full Route Cache, ensuring fresh data and UI. It can be utilized in Route Handlers or Server Actions. ```jsx revalidatePath('/') ``` -------------------------------- ### Generate Static Params for Dynamic Routes in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/dynamic-routes.mdx This example illustrates how to use the `generateStaticParams` function in Next.js to pre-render dynamic routes at build time, rather than on-demand. It fetches a list of posts from an API and maps them to an array of objects, where each object defines the `slug` parameter for a unique static page. Requests within this function are automatically deduplicated. ```tsx export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } ``` ```jsx export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } ``` -------------------------------- ### Implement `loading.tsx` for Dynamic Routes (Next.js/React) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/04-linking-and-navigating.mdx This example shows how to use `loading.tsx` (or `loading.js`) within a dynamic route, such as `app/blog/[slug]/loading.tsx`. It provides an immediate loading UI (`LoadingSkeleton`) during navigation to a dynamic route, preventing perceived slowness by the user. ```tsx export default function Loading() { return } ``` ```jsx export default function Loading() { return } ``` -------------------------------- ### Link to Dynamic Next.js Paths using a URL Object Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/03-linking-and-navigating.mdx This snippet provides an alternative method for linking to dynamic Next.js routes by passing a URL object to the `href` prop. It clearly separates the `pathname` (page file) from the `query` parameters (dynamic segments), improving readability for complex routes. ```jsx import Link from 'next/link' function Posts({ posts }) { return (
    {posts.map((post) => (
  • {post.title}
  • ))}
) } export default Posts ``` -------------------------------- ### Next.js API Route to Resolve Redirect Data Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/redirecting.mdx This Next.js API Route (or Route Handler), available in TypeScript and partially in JavaScript, serves as a lookup service for redirect entries. It accepts a `pathname` query parameter from the proxy, searches a local `redirects.json` file for a matching entry, and returns the redirect's `destination` and `permanent` status. This route confirms actual redirects, accounting for potential false positives from a preceding Bloom filter check, and ensures accurate redirection. It depends on `next/server` and a local `redirects.json` file. ```typescript import { NextRequest, NextResponse } from 'next/server' import redirects from '@/app/redirects/redirects.json' type RedirectEntry = { destination: string permanent: boolean } export function GET(request: NextRequest) { const pathname = request.nextUrl.searchParams.get('pathname') if (!pathname) { return new Response('Bad Request', { status: 400 }) } // Get the redirect entry from the redirects.json file const redirect = (redirects as Record)[pathname] // Account for bloom filter false positives if (!redirect) { return new Response('No redirect', { status: 400 }) } // Return the redirect entry return NextResponse.json(redirect) } ``` ```javascript import { NextResponse } from 'next/server' import redirects from '@/app/redirects/redirects.json' export function GET(request) { const pathname = request.nextUrl.searchParams.get('pathname') if (!pathname) { return new Response('Bad Request', { status: 400 }) } ``` -------------------------------- ### Defining a Next.js Pages Route Module (JavaScript) Source: https://github.com/vercel/next.js/blob/canary/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/template-pages/output.md This snippet illustrates the creation of a `PagesRouteModule` in Next.js, which is fundamental for defining how a page route behaves. It imports core components like `App` and `Document`, integrates userland code, and specifies the route's kind, page, and path information. This module is responsible for handling page requests. ```javascript import "__TURBOPACK_PART__" assert { __turbopack_part__: 0 }; import { PagesRouteModule } from '../../server/future/route-modules/pages/module.compiled'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 2 }; import { RouteKind } from '../../server/future/route-kind'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 8 }; import App from 'VAR_MODULE_APP'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 6 }; import Document from 'VAR_MODULE_DOCUMENT'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 10 }; import * as userland from 'VAR_USERLAND'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 22 }; const routeModule = new PagesRouteModule({ definition: { kind: RouteKind.PAGES, page: 'VAR_DEFINITION_PAGE', pathname: 'VAR_DEFINITION_PATHNAME', bundlePath: '', filename: '' }, components: { App, Document }, userland }); export { routeModule }; export { routeModule as l } from "__TURBOPACK_VAR__" assert { __turbopack_var__: true }; export { }; ``` -------------------------------- ### Configure Next.js API Route with Body Parser Size Limit and Max Duration (JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx Demonstrates how to set a custom maximum `sizeLimit` for the request body parser and define a `maxDuration` for the API route's execution, overriding the default Next.js configurations. This configuration applies to a specific API route. ```js export const config = { api: { bodyParser: { sizeLimit: '1mb', }, }, // Specifies the maximum allowed duration for this function to execute (in seconds) maxDuration: 5, } ``` -------------------------------- ### Render Parallel Route Slot and Link in Next.js Layout Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/parallel-routes.mdx This layout component receives the `@auth` parallel route slot as a prop and renders it alongside the main children. It includes a `Link` to `/login`, which, due to the intercepting route setup, will open the login modal on client-side navigation instead of redirecting to the full login page. ```tsx import Link from 'next/link' export default function Layout({ auth, children, }: { auth: React.ReactNode children: React.ReactNode }) { return ( <>
{auth}
{children}
) } ``` ```jsx import Link from 'next/link' export default function Layout({ auth, children }) { return ( <>
{auth}
{children}
) } ``` -------------------------------- ### Next.js Link with URL Object for Advanced Routing Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/02-components/link.mdx This code illustrates how to pass a URL object to the `href` prop of the Next.js `Link` component. This allows for more structured routing, including defining `pathname` and `query` parameters for both static and dynamic routes, automatically formatting the URL string. ```tsx import Link from 'next/link' function Home() { return (
  • About us
  • Blog Post
) } export default Home ``` ```jsx import Link from 'next/link' function Home() { return (
  • About us
  • Blog Post
) } export default Home ``` -------------------------------- ### Generate Static Dynamic Routes with Params Source: https://context7.com/vercel/next.js/llms.txt Implements dynamic routes with static site generation using generateStaticParams. Shows how to fetch data, generate metadata, and handle 404 cases for blog posts or similar content types. ```typescript // app/posts/[slug]/page.tsx import { Metadata } from "next"; import { notFound } from "next/navigation"; import { getAllPosts, getPostBySlug } from "@/lib/api"; export default async function Post(props: Params) { const params = await props.params; const post = getPostBySlug(params.slug); if (!post) { return notFound(); } const content = await markdownToHtml(post.content || ""); return (
); } type Params = { params: Promise<{ slug: string; }>; }; export async function generateMetadata(props: Params): Promise { const params = await props.params; const post = getPostBySlug(params.slug); if (!post) { return notFound(); } const title = `${post.title} | Next.js Blog Example`; return { title, openGraph: { title, images: [post.ogImage.url], }, }; } export async function generateStaticParams() { const posts = getAllPosts(); return posts.map((post) => ({ slug: post.slug, })); } ``` -------------------------------- ### Configure Route Segment Options in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/route.mdx This snippet shows how to define route segment configuration options directly within a Next.js Route Handler file. It demonstrates setting properties like `dynamic`, `dynamicParams`, `revalidate`, `fetchCache`, `runtime`, and `preferredRegion`. These options control caching behavior, data revalidation, and runtime environment for the route. ```typescript export const dynamic = 'auto' export const dynamicParams = true export const revalidate = false export const fetchCache = 'auto' export const runtime = 'nodejs' export const preferredRegion = 'auto' ``` ```javascript export const dynamic = 'auto' export const dynamicParams = true export const revalidate = false export const fetchCache = 'auto' export const runtime = 'nodejs' export const preferredRegion = 'auto' ``` -------------------------------- ### Demonstrate Next.js Page and Route Handler Coexistence Conflict (TypeScript/JavaScript) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/01-getting-started/15-route-handlers.mdx This snippet illustrates the conflict that arises when both a `page.js` (or `page.ts`) and a `route.js` (or `route.ts`) file are placed at the exact same route level in a Next.js application. It shows a basic page component and a conflicting POST handler, which would lead to an error due to the routing primitive rules. ```typescript export default function Page() { return

Hello, Next.js!

} // Conflict // `app/route.ts` export async function POST(request: Request) {} ``` ```javascript export default function Page() { return

Hello, Next.js!

} // Conflict // `app/route.js` export async function POST(request) {} ``` -------------------------------- ### Assemble Next.js App Route Module (JavaScript) Source: https://github.com/vercel/next.js/blob/canary/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/app-route/output.md This JavaScript code snippet combines several Turbopack parts, imports necessary Next.js components like `AppRouteRouteModule` and `RouteKind`, and then instantiates `AppRouteRouteModule`. It defines the route's properties and exports the constructed module, central to Next.js application routing. ```javascript import "__TURBOPACK_PART__" assert { __turbopack_part__: 0 }; import { AppRouteRouteModule } from '../../server/future/route-modules/app-route/module.compiled'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 2 }; import { RouteKind } from '../../server/future/route-kind'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 6 }; import * as userland from 'VAR_USERLAND'; import "__TURBOPACK_PART__" assert { __turbopack_part__: 6 }; import "__TURBOPACK_PART__" assert { __turbopack_part__: 5 }; const routeModule = new AppRouteRouteModule({ definition: { kind: RouteKind.APP_ROUTE, page: 'VAR_DEFINITION_PAGE', pathname: 'VAR_DEFINITION_PATHNAME', filename: 'VAR_DEFINITION_FILENAME', bundlePath: 'VAR_DEFINITION_BUNDLE_PATH' }, resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH', nextConfigOutput, userland }); export { routeModule as a } from "__TURBOPACK_VAR__" assert { __turbopack_var__: true }; export { }; ``` -------------------------------- ### Generate Static Params for All Dynamic Routes in Next.js Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/02-guides/caching.mdx Illustrates how to use `generateStaticParams` to pre-render all possible paths for a dynamic route at build time. It fetches a list of posts and maps them to `slug` parameters for static generation. ```jsx export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } ``` -------------------------------- ### Send HTTP Response with Error Handling in Next.js API Routes Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This example shows how to send a generic HTTP response from a Next.js API route. Similar to JSON responses, it includes error handling to return an appropriate status code and message. The response body can be a string, object, or Buffer, offering more flexibility than just JSON. ```ts import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` ```js export default async function handler(req, res) { try { const result = await someAsyncOperation() res.status(200).send({ result }) } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` -------------------------------- ### Define Next.js Pages Router API Routes Source: https://context7.com/vercel/next.js/llms.txt These TypeScript examples illustrate creating traditional API routes within the `pages/api` directory using Next.js Pages Router. The first example returns a static list of users, while the second defines a dynamic route for a single user, supporting GET and PUT HTTP methods and handling method not allowed scenarios. ```typescript // pages/api/users.ts import type { NextApiRequest, NextApiResponse } from "next"; import type { User } from "../../interfaces"; const users: User[] = [{ id: 1 }, { id: 2 }, { id: 3 }]; export default function handler( _req: NextApiRequest, res: NextApiResponse, ) { res.status(200).json(users); } ``` ```typescript // pages/api/user/[id].ts import type { NextApiRequest, NextApiResponse } from "next"; import type { User } from "../../../interfaces"; export default function userHandler( req: NextApiRequest, res: NextApiResponse, ) { const { query, method } = req; const id = parseInt(query.id as string, 10); const name = query.name as string; switch (method) { case "GET": res.status(200).json({ id, name: `User ${id}` }); break; case "PUT": res.status(200).json({ id, name: name || `User ${id}` }); break; default: res.setHeader("Allow", ["GET", "PUT"]); res.status(405).end(`Method ${method} Not Allowed`); } } ``` -------------------------------- ### Access Next.js Dynamic Segment with useRouter Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/02-dynamic-routes.mdx This Next.js example demonstrates how to create a dynamic route (e.g., `pages/blog/[slug].js`) and access the dynamic segment's value (e.g., 'slug') using the `useRouter` hook. The `router.query` object provides access to the URL parameters, allowing the page to display content based on the dynamic segment. ```jsx import { useRouter } from 'next/router' export default function Page() { const router = useRouter() return

Post: {router.query.slug}

} ``` -------------------------------- ### Stream Response from Next.js API Route Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This example demonstrates how to create a streaming response from a Next.js API route. It sets appropriate headers for server-sent events (`text/event-stream`) and iteratively writes data to the response over a period before ending the stream. ```ts import { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', }) let i = 0 while (i < 10) { res.write(`data: ${i}\n\n`) i++ await new Promise((resolve) => setTimeout(resolve, 1000)) } res.end() } ``` ```js export default async function handler(req, res) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', }) let i = 0 while (i < 10) { res.write(`data: ${i}\n\n`) i++ await new Promise((resolve) => setTimeout(resolve, 1000)) } res.end() } ``` -------------------------------- ### Implement Default Fallbacks for Nested Parallel Routes with Route Groups in Next.js Source: https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/parallel-routes-leaf-segments/fixtures/build-error/README.md Adds `default.tsx` files for `@analytics` and `@metrics` parallel routes within a complex nested segment `app/with-groups-and-children/(dashboard)/(overview)/`. This resolves `MissingDefaultParallelRouteError` in scenarios involving route groups and child routes by providing essential fallback UIs for the parallel slots. ```tsx // app/with-groups-and-children/(dashboard)/(overview)/@analytics/default.tsx export default function AnalyticsDefault() { return
Analytics Fallback
} // app/with-groups-and-children/(dashboard)/(overview)/@metrics/default.tsx export default function MetricsDefault() { return
Metrics Fallback
} ``` -------------------------------- ### Access Dynamic Route Parameters in default.js (Next.js) Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/default.mdx This code demonstrates how to access dynamic route parameters within a `default.js` file for a Parallel Route slot, such as `@sidebar`. The `params` prop is a promise that resolves to an object containing the dynamic segments from the URL. It requires the use of `async/await` to extract the parameter values, allowing for dynamic content based on the current route. ```tsx export default async function Default({ params, }: { params: Promise<{ artist: string }> }) { const { artist } = await params } ``` ```jsx export default async function Default({ params }) { const { artist } = await params } ``` -------------------------------- ### Next.js getStaticPaths for Pre-rendering Dynamic Routes Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/02-rendering/02-static-site-generation.mdx Illustrates the use of `getStaticPaths` in Next.js to specify which dynamic routes should be pre-rendered at build time. This function fetches data from an external API to determine the paths, maps the data to `params` for each route, and configures the `fallback` behavior. ```jsx // This function gets called at build time export async function getStaticPaths() { // Call an external API endpoint to get posts const res = await fetch('https://.../posts') const posts = await res.json() // Get the paths we want to pre-render based on posts const paths = posts.map((post) => ({ params: { id: post.id }, })) // We'll pre-render only these paths at build time. // { fallback: false } means other routes should 404. return { paths, fallback: false } } ``` -------------------------------- ### Perform Redirects in Next.js API Routes Source: https://github.com/vercel/next.js/blob/canary/docs/02-pages/03-building-your-application/01-routing/07-api-routes.mdx This snippet illustrates how to redirect a client to a specific path or URL after an operation, such as a successful form submission. It uses `res.redirect(307, '/')` for a temporary redirect and includes basic error handling to send a 500 status if an error occurs during the operation. ```ts import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { name, message } = req.body try { await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { res.status(500).send({ error: 'Failed to fetch data' }) } } ``` ```js export default async function handler(req, res) { const { name, message } = req.body try { await handleFormInputAsync({ name, message }) res.redirect(307, '/') } catch (err) { res.status(500).send({ error: 'failed to fetch data' }) } } ``` -------------------------------- ### Accessing Dynamic Route Parameters in Next.js Image Functions Source: https://github.com/vercel/next.js/blob/canary/docs/01-app/03-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx This snippet demonstrates how to access dynamic route parameters (`params`) within an `opengraph-image` or `twitter-image` page component in Next.js. The `params` object is a promise that resolves to an object containing the dynamic route segments. ```tsx export default async function Image({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params // ... } ``` ```jsx export default async function Image({ params }) { const { slug } = await params // ... } ``` -------------------------------- ### Import AppRouteRouteModule in JavaScript Source: https://github.com/vercel/next.js/blob/canary/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/app-route/output.md Imports the `AppRouteRouteModule` class from the Next.js server-side future route modules. This class is essential for defining and managing application routes within the Next.js framework. ```javascript import { AppRouteRouteModule } from '../../server/future/route-modules/app-route/module.compiled'; ``` -------------------------------- ### Import RouteKind enum in JavaScript Source: https://github.com/vercel/next.js/blob/canary/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/app-route/output.md Imports the `RouteKind` enum from the Next.js server-side future route kind definitions. This enum is used to specify the type of a route, such as `APP_ROUTE`, providing clear categorization for routing logic. ```javascript import { RouteKind } from '../../server/future/route-kind'; ```