new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js App Router · all subjects

app-router/file-conventions

168 notes in this subject, read out of this brain and free to use. This is page 2 of 3.

Dynamic image import with path alias example

Example of dynamic image import using a path alias (e.g., @/): const { default: image } = await import( `@/content/blog/images/${imageFilename}` )

Blur placeholder with statically imported images

When using statically imported images, you can optionally add placeholder="blur" to display a blur-up effect while the image is loading. The blurDataURL is automatically generated.

Dynamic imports in Server Components for image metadata

If you cannot use a static import for images, you can use a dynamic import() in a Server Component to automatically get width, height, and blurDataURL metadata. Example: const { default: image } = await import(`../content/blog/images/${imageFilename}`)

Dynamic image imports must include static prefix

When using dynamic imports for images, the path must include a static prefix (like ../content/blog/images/). Be as specific as possible since all files matching that prefix are bundled. Only files in the specified directory are included, so external input cannot reach outside of it.

Proxy file location convention

Create a proxy.ts (or .js) file in the project root, or inside src if applicable, so that it is located at the same level as pages or app. Only one proxy.ts file is supported per project.

Metadata APIs overview

Next.js provides three ways to define application metadata for improved SEO and web shareability: the static metadata object, the dynamic generateMetadata function, and special file conventions for favicons and OG images. The metadata object and generateMetadata function exports are only supported in Server Components. Next.js automatically generates the relevant head tags for pages.

Default meta tags always added

Two default meta tags are automatically added to every route even if metadata is not defined: a meta charset tag set to utf-8 for character encoding, and a meta viewport tag set to 'width=device-width, initial-scale=1' for device scaling.

Static metadata export syntax

To define static metadata, export a Metadata object from a layout.js or page.js file. The metadata object can include fields like title and description and is evaluated at build time.

generateMetadata function for dynamic metadata

The generateMetadata function allows fetching metadata that depends on dynamic data. It receives props with params (a Promise) and searchParams (a Promise), and an optional parent parameter of type ResolvingMetadata. The function must be async and return a Metadata object. This allows metadata like titles and descriptions to be fetched from external sources based on route parameters.

Streaming metadata behavior for dynamically rendered pages

For dynamically rendered pages, Next.js streams metadata separately and injects it into the HTML once generateMetadata resolves, without blocking UI rendering. This improves perceived performance by allowing visual content to stream first. However, streaming metadata is disabled for bots and crawlers that expect metadata in the head tag, such as Twitterbot, Slackbot, and Bingbot, which are detected via the User Agent header. Streaming metadata can be customized or disabled completely using the htmlLimitedBots option in next.config.js. Prerendered pages do not use streaming since metadata is resolved at build time.

File-based metadata special files

Next.js supports the following special metadata files: favicon.ico, apple-icon.jpg, and icon.jpg for app icons; opengraph-image.jpg and twitter-image.jpg for OG images; robots.txt for search engine instructions; and sitemap.xml for site structure. These files can be static or programmatically generated.

Favicon placement and creation

To add a favicon to an application, create a favicon.ico file and place it in the root of the app folder. Favicons are small icons that represent the site in bookmarks and search results. Favicons can also be programmatically generated using code.

Static Open Graph image placement

To add a static Open Graph (OG) image to an application, create an opengraph-image.jpg file in the root of the app folder. OG images are images that represent the site in social media. OG images can be added for specific routes by creating opengraph-image.jpg files deeper in the folder structure. More specific images take precedence over OG images higher up in the folder structure. Formats supported include jpeg, png, and gif in addition to jpg.

Dynamic OG image generation with ImageResponse

The ImageResponse constructor from 'next/og' allows generating dynamic images using JSX and CSS for OG images that depend on data. To generate unique OG images for dynamic routes like blog posts, create an opengraph-image.tsx file in the route folder. The file must export a size object with width and height properties, a contentType export (e.g. 'image/png'), and a default async function that receives params as a Promise. The function returns new ImageResponse() with a JSX element defining the image content.

ImageResponse example for dynamic blog post OG images

import { ImageResponse } from 'next/og' import { getPost } from '@/app/lib/data' export const size = { width: 1200, height: 630, } export const contentType = 'image/png' export default async function Image({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params const post = await getPost(slug) return new ImageResponse( ( <div style={{ fontSize: 128, background: 'white', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', }} > {post.title} </div> ) ) } This example shows how to generate a dynamic OG image for a blog post that displays the post title.

ImageResponse CSS support and limitations

ImageResponse supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. Only flexbox and a subset of CSS properties are supported; advanced layouts such as display: grid will not work. ImageResponse uses @vercel/og, satori, and resvg to convert HTML and CSS into PNG.

Route Handlers are app directory only, replace API Routes

Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory, meaning you do not need to use API Routes and Route Handlers together.

Route Handlers defined in route.js|ts file

Route Handlers are defined in a route.js or route.ts file inside the app directory. They can be nested anywhere inside the app directory, similar to page.js and layout.js. However, there cannot be a route.js file at the same route segment level as page.js.

Route Handlers supported HTTP methods

Route Handlers support the following HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. If an unsupported method is called, Next.js will return a 405 Method Not Allowed response.

Route Handlers cannot conflict with pages

There cannot be a route.js file at the same route segment level as page.js. Each route.js or page.js file takes over all HTTP verbs for that route. A page.js and route.js in the same directory is a conflict.

Route Handlers do not participate in layouts or client-side navigation

Route Handlers are the lowest level routing primitive. They do not participate in layouts or client-side navigations like page.js files do.

Route Handlers extend Request and Response with NextRequest and NextResponse

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse to provide convenient helpers for advanced use cases in Route Handlers.

Basic GET Route Handler example

export async function GET(request: Request) {}

Special Route Handlers remain static by default

Special Route Handlers like sitemap.ts, opengraph-image.tsx, icon.tsx, and other metadata files remain static by default unless they use Request-time APIs or dynamic config options.

RouteContext TypeScript helper for dynamic routes

In TypeScript, you can type the context parameter for Route Handlers with the globally available RouteContext helper. Example: export async function GET(_req: NextRequest, ctx: RouteContext<'/users/[id]'>) { const { id } = await ctx.params; return Response.json({ id }) }. Types are generated during next dev, next build, or next typegen.

App Router is file-system based

The App Router is a file-system based router that uses React's latest features including Server Components, Suspense, and Server Functions.

Metadata files can be static or dynamic

File-based metadata can be defined as a static file (e.g. opengraph-image.jpg) or a dynamic variant that uses code to generate the file (e.g. opengraph-image.js).

Next.js automatically serves and updates metadata files

Once a metadata file is defined, Next.js will automatically serve the file with hashes in production for caching and update the relevant head elements with the correct metadata, such as the asset's URL, file type, and image size.

manifest.json file location

The manifest file (manifest.json or manifest.webmanifest) must be placed in the root of the app directory to provide information about the web application for the browser.

Static manifest file structure

A static manifest file must follow the Web Manifest Specification and can include properties such as name, short_name, description, and start_url.

Dynamic manifest generation with manifest.js or manifest.ts

A manifest.js or manifest.ts file can be used to dynamically generate a manifest by exporting a default function that returns a MetadataRoute.Manifest object.

Dynamic manifest example with TypeScript

Example of a dynamic manifest file using TypeScript: ```ts import type { MetadataRoute } from 'next' export default function manifest(): MetadataRoute.Manifest { return { name: 'Next.js App', short_name: 'Next.js App', description: 'Next.js App', start_url: '/', display: 'standalone', background_color: '#fff', theme_color: '#fff', icons: [ { src: '/favicon.ico', sizes: 'any', type: 'image/x-icon', }, ], } } ```

Dynamic manifest example with JavaScript

Example of a dynamic manifest file using JavaScript: ```js export default function manifest() { return { name: 'Next.js App', short_name: 'Next.js App', description: 'Next.js App', start_url: '/', display: 'standalone', background_color: '#fff', theme_color: '#fff', icons: [ { src: '/favicon.ico', sizes: 'any', type: 'image/x-icon', }, ], } } ```

Web Manifest Specification compliance

The manifest file must match the Web Manifest Specification as defined by MDN.

favicon file convention - location and format

The favicon file must be placed at app/ (root /app directory only). It must be a .ico file. Next.js automatically generates the <head> output as <link rel="icon" href="/favicon.ico" sizes="any" />.

icon file convention - location, formats, and output

The icon file can be placed at app/**/* (anywhere in the app directory and subdirectories). Supported formats are .ico, .jpg, .jpeg, .png, and .svg. Next.js automatically generates the <head> output as <link rel="icon" href="/icon?<generated>" type="image/<generated>" sizes="<generated>" />.

apple-icon file convention - location, formats, and output

The apple-icon file can be placed at app/**/* (anywhere in the app directory and subdirectories). Supported formats are .jpg, .jpeg, and .png. Next.js automatically generates the <head> output as <link rel="apple-touch-icon" href="/apple-icon?<generated>" type="image/<generated>" sizes="<generated>" />.

Setting multiple icons with numbered suffixes

You can set multiple icons by adding a number suffix to the file name, for example icon1.png, icon2.png, and so on. Numbered files will sort lexically.

Icon attributes generated from file metadata

Next.js determines the <link> tag attributes (rel, href, type, sizes) based on the icon type and metadata of the evaluated file. For example, a 32 by 32px .png file will have type="image/png" and sizes="32x32" attributes. The sizes="any" attribute is added to icons when the extension is .svg or the image size of the file is not determined.

Generating icons using code with ImageResponse

You can programmatically generate icons by creating an icon or apple-icon route that default exports a function. The easiest way is to use the ImageResponse API from next/og. Both .js, .ts, and .tsx file types are supported for code-generated icons.

Generated icons are statically optimized by default

By default, generated icons are statically optimized (generated at build time and cached) unless they use Request-time APIs or uncached data.

Cannot generate favicon using code

You cannot generate a favicon icon using code. Use the icon route or a favicon.ico file instead.

Icon routes are cached by default unless using Request-time APIs

App icons are special Route Handlers that are cached by default unless they use a Request-time API or dynamic config option.

Icon function props - params object

The default export function for an icon receives an optional params prop, which is a promise that resolves to an object containing the dynamic route parameters from the root segment down to the segment where icon or apple-icon is colocated. For example, in app/shop/[slug]/icon.ts at route /shop/1, params resolves to Promise<{ slug: '1' }>.

Icon function return types

The default export function for an icon should return one of: Blob, ArrayBuffer, TypedArray, DataView, ReadableStream, or Response. ImageResponse satisfies this return type.

Icon config exports - size and contentType

You can optionally configure the icon's metadata by exporting size and contentType variables from the icon or apple-icon route. size is an object with { width: number; height: number }. contentType is a string containing the image MIME type.

Generating multiple icons in the same file

You can generate multiple icons in the same file using the generateImageMetadata function. When used, the default export function also receives an id prop that is a promise resolving to the id value from one of the items returned by generateImageMetadata.

Example: generating an icon with ImageResponse

import { ImageResponse } from 'next/og' export const size = { width: 32, height: 32, } export const contentType = 'image/png' export default function Icon() { return new ImageResponse( ( <div style={{ fontSize: 24, background: 'black', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', }} > A </div> ), { ...size, } ) }

Example: icon function with dynamic route parameters

export default async function Icon({ params, }: { params: Promise<{ slug: string }> }) { const { slug } = await params // ... }

Icon routes use route segment configuration

icon and apple-icon are specialized Route Handlers that can use the same route segment configuration options as Pages and Layouts.

robots.txt file location and purpose

Place a robots.txt file in the root of the app directory to tell search engine crawlers which URLs they can access on your site, following the Robots Exclusion Standard.

Static robots.txt format

A static robots.txt file can be placed directly in the app directory with standard robots.txt syntax. Example: User-Agent: *, Allow: /, Disallow: /private/, Sitemap: https://acme.com/sitemap.xml

Dynamic robots.js or robots.ts generation

Add a robots.js or robots.ts file that exports a default function returning a Robots object to dynamically generate the robots.txt file. The file is cached by default unless it uses a Request-time API or dynamic config option.

Robots object type definition

The Robots object has this shape: { rules: { userAgent?: string | string[], allow?: string | string[], disallow?: string | string[], crawlDelay?: number, other?: Record<string, string | number | Array<string | number>> } | Array<{userAgent: string | string[], allow?: string | string[], disallow?: string | string[], crawlDelay?: number, other?: Record<string, string | number | Array<string | number>>}>, sitemap?: string | string[], host?: string }

Dynamic robots example with TypeScript

Example TypeScript robots generator: import type { MetadataRoute } from 'next' export default function robots(): MetadataRoute.Robots { return { rules: { userAgent: '*', allow: '/', disallow: '/private/', }, sitemap: 'https://acme.com/sitemap.xml', } }

Customizing rules for specific user agents

Pass an array of rule objects to the rules property to customize crawling behavior for different search engine bots. Each rule can have a userAgent string or array of strings, and its own allow, disallow, crawlDelay, and other directives.

Multiple user agents example

Example with multiple user agents: rules: [{ userAgent: 'Googlebot', allow: ['/'], disallow: '/private/' }, { userAgent: ['Applebot', 'Bingbot'], disallow: ['/'] }], sitemap: 'https://acme.com/sitemap.xml'

Non-standard robots directives with other field

Use the other field on a rule to include non-standard directives like Request-Rate (Seznam) or Clean-param (Yandex). Keys preserve their casing and array values emit one line per entry, scoped to the rule's User-Agent block.

Non-standard directives example

Example with non-standard directive: { userAgent: 'SeznamBot', allow: '/', other: { 'Request-Rate': '10/1m' } } generates: User-Agent: SeznamBot\nAllow: /\nRequest-Rate: 10/1m

Non-standard directives validation

Values in the other field are passed through verbatim. Next.js does not validate directive names or values, so refer to the target search engine's documentation for the exact syntax.

Give your agent this brain