Pular para o conteúdo
Documentação do Next.js PT-BR
Esta página ainda está em inglês. A tradução ainda não foi feita; o conteúdo abaixo é o original de nextjs.org.

generateViewport

You can customize the initial viewport of the page with the static viewport object or the dynamic generateViewport function.

Good to know:

  • The viewport object and generateViewport function exports are only supported in Server Components.
  • You cannot export both the viewport object and generateViewport function from the same route segment.
  • If you're coming from migrating metadata exports, you can use metadata-to-viewport-export codemod to update your changes.

The viewport object

To define the viewport options, export a viewport object from a layout.jsx or page.jsx file.

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  themeColor: 'black',
}

export default function Page() {}

generateViewport function

generateViewport should return a Viewport object containing one or more viewport fields.

layout.tsx | page.tsx
export function generateViewport({ params }) {
  return {
    themeColor: '...',
  }
}

In TypeScript, the params argument can be typed via PageProps<'/route'> or LayoutProps<'/route'> depending on where generateViewport is defined.

layout.js | page.js
export function generateViewport({ params }) {
  return {
    themeColor: '...',
  }
}

Good to know:

  • If the viewport doesn't depend on request information, it should be defined using the static viewport object rather than generateViewport.

Viewport Fields

Viewport fields configure the viewport, theme color, and color scheme meta tags.

themeColor

themeColor sets the theme-color meta tag. Use media queries to provide different colors for different conditions.

Learn more about theme-color.

Simple theme color

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  themeColor: 'black',
}
<head> output
<meta name="theme-color" content="black" />

With media attribute

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  themeColor: [
    { media: '(prefers-color-scheme: light)', color: 'cyan' },
    { media: '(prefers-color-scheme: dark)', color: 'black' },
  ],
}
<head> output
<meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" />

themeColor accepts a color string, a { color: string, media?: string } descriptor, or an array of descriptors.

width, initialScale, maximumScale and userScalable

Next.js sets width: 'device-width' and initialScale: 1 by default. A viewport export or generateViewport return value overrides only the fields it provides. Omitted fields retain inherited or default values. To remove the default initial-scale directive, set initialScale: undefined.

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  maximumScale: 1,
  userScalable: false,
}
<head> output
<meta
  name="viewport"
  content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>

Next.js accepts these layout fields. See the viewport reference for directive meanings and browser support.

FieldAccepted input
width, heightstring or number
initialScale, minimumScale, maximumScalenumber
userScalableboolean (emits yes or no)
viewportFit'auto', 'contain', or 'cover'
interactiveWidget'resizes-visual', 'resizes-content', or 'overlays-content'

viewportFit

viewportFit sets the viewport-fit directive in the viewport meta tag.

Use 'cover' to fill the device display. Use CSS safe area inset variables to keep content clear of display cutouts.

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  viewportFit: 'cover',
}

The default width and initialScale values are retained:

<head> output
<meta
  name="viewport"
  content="width=device-width, initial-scale=1, viewport-fit=cover"
/>

colorScheme

colorScheme sets the color-scheme meta tag.

Learn more about color-scheme.

layout.tsx | page.tsx
import type { Viewport } from 'next'

export const viewport: Viewport = {
  colorScheme: 'dark',
}
<head> output
<meta name="color-scheme" content="dark" />

colorScheme accepts 'normal', 'light', 'dark', 'light dark', 'dark light', or 'only light'.

With Cache Components

When Cache Components is enabled, generateViewport follows the same rules as other components. If viewport accesses runtime data (cookies(), headers(), params, searchParams) or performs uncached data fetching, it defers to request time.

Unlike metadata, viewport cannot be streamed because it affects initial page load UI. If generateViewport defers to request time, the page would need to block until resolved.

If viewport depends on external data but not runtime data, use use cache:

app/layout.tsx
export async function generateViewport() {
  'use cache'
  const { width, initialScale } = await db.query('viewport-size')
  return { width, initialScale }
}

If viewport genuinely requires runtime data, wrap the document <body> in a <Suspense> boundary to signal that the entire route should be dynamic. The shell ships immediately and the document streams in once the viewport resolves:

app/layout.tsx
import { Suspense } from 'react'
import { cookies } from 'next/headers'

export async function generateViewport() {
  const cookieJar = await cookies()
  return {
    themeColor: cookieJar.get('theme-color')?.value,
  }
}

export default function RootLayout({ children }) {
  return (
    <Suspense>
      <html>
        <body>{children}</body>
      </html>
    </Suspense>
  )
}

Alternatively, opt the segment out of instant-navigation validation with instant = false. The route renders on every request and the navigation blocks until the render completes:

app/dashboard/layout.tsx
import { cookies } from 'next/headers'

export const instant = false

export async function generateViewport() {
  const cookieJar = await cookies()
  return {
    themeColor: cookieJar.get('theme-color')?.value,
  }
}

export default function DashboardLayout({ children }) {
  return <section>{children}</section>
}

Setting instant = false opts only the segment that exports it out. Descendant segments are still validated by the global default. See Next.js encountered runtime data in generateViewport() for the full set of fix options, trade-offs, and the subtree-wide opt-out.

Good to know: Use multiple root layouts to isolate fully dynamic viewport to specific routes, while still letting other routes in your application generate a static shell.

Types

You can add type safety to your viewport object by using the Viewport type. If you are using the built-in TypeScript plugin in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.

viewport object

import type { Viewport } from 'next'

export const viewport: Viewport = {
  themeColor: 'black',
}

generateViewport function

Regular function

import type { Viewport } from 'next'

export function generateViewport(): Viewport {
  return {
    themeColor: 'black',
  }
}

With segment props

import type { Viewport } from 'next'

type Props = {
  params: Promise<{ id: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}

export function generateViewport({ params, searchParams }: Props): Viewport {
  return {
    themeColor: 'black',
  }
}

export default function Page({ params, searchParams }: Props) {}

JavaScript Projects

For JavaScript projects, you can use JSDoc to add type safety.

/** @type {import("next").Viewport} */
export const viewport = {
  themeColor: 'black',
}

Version History

VersionChanges
v14.0.0viewport and generateViewport introduced.

Next Steps

View all the Metadata API options.