instruction
stringlengths
31
302
output
stringlengths
22
4.36k
source_url
stringlengths
41
99
How do I implement Returns in Next.js?
The generateImageMetadata function should return an array of objects containing the image's metadata such as alt and size. In addition, each item must include an id value which will be passed to the props of the image generating function. ```jsx import { ImageResponse } from 'next/og' export function generateImageMetadata() { return [ { contentType: 'image/png', size: { width: 48, height: 48 }, id: 'small', }, { contentType: 'image/png', size: { width: 72, height: 72 }, id: 'medium', }, ] } export default function Icon({ id }) { return new ImageResponse( ( <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 88, background: '#000', color: '#fafafa', }} > Icon {id} </div> ) ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata
What are the best practices for Using external data in Next.js?
```jsx import { ImageResponse } from 'next/og' import { getCaptionForImage, getOGImages } from '@/app/utils/images' export async function generateImageMetadata({ params }) { const images = await getOGImages(params.id) return images.map((image, idx) => ({ id: idx, size: { width: 1200, height: 600 }, alt: image.text, contentType: 'image/png', })) } export default async function Image({ params, id }) { const productId = (await params).id const imageId = id const text = await getCaptionForImage(productId, imageId) return new ImageResponse( ( <div style={ { // ... } } > {text} </div> ) ) } ``` ## Best Practices - This example uses the params object and external data to generate multiple Open Graph images for a route segment. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-image-metadata
How do I implement in Next.js?
This page covers all Config-based Metadata options with generateMetadata and the static metadata object. Good to know: The metadata object and generateMetadata function exports are only supported in Server Components. You cannot export both the metadata object and generateMetadata function from the same route segment. ```javascript // either Static metadata export const metadata = { title: '...', } // or Dynamic metadata export async function generateMetadata({ params }) { return { title: '...', } } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement The metadata object in Next.js?
To define static metadata, export a Metadata object from a layout.js or page.js file. See the Metadata Fields for a complete list of supported options. ```javascript export const metadata = { title: '...', description: '...', } export default function Page() {} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement generateMetadata function in Next.js?
Dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments, can be set by exporting a generateMetadata function that returns a Metadata object. ```jsx export async function generateMetadata({ params, searchParams }, parent) { // read route params const { id } = await params // fetch data const product = await fetch(`https://.../${id}`).then((res) => res.json()) // optionally access and extend (rather than replace) parent metadata const previousImages = (await parent).openGraph?.images || [] return { title: product.title, openGraph: { images: ['/some-specific-page-image.jpg', ...previousImages], }, } } export default function Page({ params, searchParams }) {} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement Template object in Next.js?
title.default can be used to provide a fallback title to child route segments that don't define a title. title.template can be used to add a prefix or a suffix to titles defined in child route segments. Good to know: title.template applies to child route segments and not the segment it's defined in. This means: title.default is required when you add a title.template. title.template defined in layout.js will not apply to a title defined in a page.js of the same route segment. title.template defined in page.js has no effect because a page is always the terminating segment (it doesn't have any children route segments). title.template has no effect if a route has not defined a title or title.default. title.template applies to child route segments and not the segment it's defined in. This means: title.default is required when you add a title.template. title.template defined in layout.js will not apply to a title defined in a page.js of the same route segment. title.template defined in page.js has no effect because a page is always the terminating segment (it doesn't have any children route segments). title.template has no effect if a route has not defined a title or title.default. title.absolute can be used to provide a title that ignores title.template set in parent segments. Good to know: layout.js title (string) and title.default define the default title for child segments (that do not define their own title). It will augment title.template from the closest parent segment if it exists. title.absolute defines the default title for child segments. It ignores title.template from parent segments. title.template defines a new title template for child segments. page.js If a page does not define its own title the closest parents resolved title will be used. title (string) defines the routes title. It will augment title.template from the closest parent segment if it exists. title.absolute defines the route title. It ignores title.template from parent segments. title.template has no effect in page.js because a page is always the terminating segment of a route. layout.js title (string) and title.default define the default title for child segments (that do not define their own title). It will augment title.template from the closest parent segment if it exists. title.absolute defines the default title for child segments. It ignores title.template from parent segments. title.template defines a new title template for child segments. page.js If a page does not define its own title the closest parents resolved title will be used. title (string) defines the routes title. It will augment title.template from the closest parent segment if it exists. title.absolute defines the route title. It ignores title.template from parent segments. title.template has no effect in page.js because a page is always the terminating segment of a route. ```typescript export const metadata = { title: { default: '...', template: '...', absolute: '...', }, } ``` ```typescript import type { Metadata } from 'next' export const metadata: Metadata = { title: { default: 'Acme', }, } ``` ```typescript import type { Metadata } from 'next' export const metadata: Metadata = {} // Output: <title>Acme</title> ``` ```typescript export const metadata = { title: { template: '%s | Acme', default: 'Acme', // a default is required when creating a template }, } ``` ```typescript export const metadata = { title: 'About', } // Output: <title>About | Acme</title> ``` ```typescript export const metadata = { title: { template: '%s | Acme', }, } ``` ```typescript export const metadata = { title: { absolute: 'About', }, } // Output: <title>About</title> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement metadataBase in Next.js?
metadataBase is a convenience option to set a base URL prefix for metadata fields that require a fully qualified URL. metadataBase allows URL-based metadata fields defined in the current route segment and below to use a relative path instead of an otherwise required absolute URL. The field's relative path will be composed with metadataBase to form a fully qualified URL. If not configured, metadataBase is automatically populated with a default value. Good to know: ```javascript export const metadata = { metadataBase: new URL('https://acme.com'), alternates: { canonical: '/', languages: { 'en-US': '/en-US', 'de-DE': '/de-DE', }, }, openGraph: { images: '/og-image.png', }, } ``` ```jsx <link rel="canonical" href="https://acme.com" /> <link rel="alternate" hreflang="en-US" href="https://acme.com/en-US" /> <link rel="alternate" hreflang="de-DE" href="https://acme.com/de-DE" /> <meta property="og:image" content="https://acme.com/og-image.png" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement URL Composition in Next.js?
URL composition favors developer intent over default directory traversal semantics. Trailing slashes between metadataBase and metadata fields are normalized. An "absolute" path in a metadata field (that typically would replace the whole URL path) is treated as a "relative" path (starting from the end of metadataBase). For example, given the following metadataBase: Any metadata fields that inherit the above metadataBase and set their own value will be resolved as follows: ```typescript export const metadata = { metadataBase: new URL('https://acme.com'), } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement openGraph in Next.js?
Good to know: It may be more convenient to use the file-based Metadata API for Open Graph images. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you. ```javascript export const metadata = { openGraph: { title: 'Next.js', description: 'The React Framework for the Web', url: 'https://nextjs.org', siteName: 'Next.js', images: [ { url: 'https://nextjs.org/og.png', // Must be an absolute URL width: 800, height: 600, }, { url: 'https://nextjs.org/og-alt.png', // Must be an absolute URL width: 1800, height: 1600, alt: 'My custom alt', }, ], videos: [ { url: 'https://nextjs.org/video.mp4', // Must be an absolute URL width: 800, height: 600, }, ], audio: [ { url: 'https://nextjs.org/audio.mp3', // Must be an absolute URL }, ], locale: 'en_US', type: 'website', }, } ``` ```jsx <meta property="og:title" content="Next.js" /> <meta property="og:description" content="The React Framework for the Web" /> <meta property="og:url" content="https://nextjs.org/" /> <meta property="og:site_name" content="Next.js" /> <meta property="og:locale" content="en_US" /> <meta property="og:image" content="https://nextjs.org/og.png" /> <meta property="og:image:width" content="800" /> <meta property="og:image:height" content="600" /> <meta property="og:image" content="https://nextjs.org/og-alt.png" /> <meta property="og:image:width" content="1800" /> <meta property="og:image:height" content="1600" /> <meta property="og:image:alt" content="My custom alt" /> <meta property="og:video" content="https://nextjs.org/video.mp4" /> <meta property="og:video:width" content="800" /> <meta property="og:video:height" content="600" /> <meta property="og:audio" content="https://nextjs.org/audio.mp3" /> <meta property="og:type" content="website" /> ``` ```javascript export const metadata = { openGraph: { title: 'Next.js', description: 'The React Framework for the Web', type: 'article', publishedTime: '2023-01-01T00:00:00.000Z', authors: ['Seb', 'Josh'], }, } ``` ```jsx <meta property="og:title" content="Next.js" /> <meta property="og:description" content="The React Framework for the Web" /> <meta property="og:type" content="article" /> <meta property="article:published_time" content="2023-01-01T00:00:00.000Z" /> <meta property="article:author" content="Seb" /> <meta property="article:author" content="Josh" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement icons in Next.js?
Good to know: We recommend using the file-based Metadata API for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you. Good to know: The msapplication-* meta tags are no longer supported in Chromium builds of Microsoft Edge, and thus no longer needed. ```javascript export const metadata = { icons: { icon: '/icon.png', shortcut: '/shortcut-icon.png', apple: '/apple-icon.png', other: { rel: 'apple-touch-icon-precomposed', url: '/apple-touch-icon-precomposed.png', }, }, } ``` ```jsx <link rel="shortcut icon" href="/shortcut-icon.png" /> <link rel="icon" href="/icon.png" /> <link rel="apple-touch-icon" href="/apple-icon.png" /> <link rel="apple-touch-icon-precomposed" href="/apple-touch-icon-precomposed.png" /> ``` ```javascript export const metadata = { icons: { icon: [ { url: '/icon.png' }, new URL('/icon.png', 'https://example.com'), { url: '/icon-dark.png', media: '(prefers-color-scheme: dark)' }, ], shortcut: ['/shortcut-icon.png'], apple: [ { url: '/apple-icon.png' }, { url: '/apple-icon-x3.png', sizes: '180x180', type: 'image/png' }, ], other: [ { rel: 'apple-touch-icon-precomposed', url: '/apple-touch-icon-precomposed.png', }, ], }, } ``` ```tsx <link rel="shortcut icon" href="/shortcut-icon.png" /> <link rel="icon" href="/icon.png" /> <link rel="icon" href="https://example.com/icon.png" /> <link rel="icon" href="/icon-dark.png" media="(prefers-color-scheme: dark)" /> <link rel="apple-touch-icon" href="/apple-icon.png" /> <link rel="apple-touch-icon-precomposed" href="/apple-touch-icon-precomposed.png" /> <link rel="apple-touch-icon" href="/apple-icon-x3.png" sizes="180x180" type="image/png" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement manifest in Next.js?
A web application manifest, as defined in the Web Application Manifest specification. ```javascript export const metadata = { manifest: 'https://nextjs.org/manifest.json', } ``` ```jsx <link rel="manifest" href="https://nextjs.org/manifest.json" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement twitter in Next.js?
The Twitter specification is (surprisingly) used for more than just X (formerly known as Twitter). Learn more about the Twitter Card markup reference. ```javascript export const metadata = { twitter: { card: 'summary_large_image', title: 'Next.js', description: 'The React Framework for the Web', siteId: '1467726470533754880', creator: '@nextjs', creatorId: '1467726470533754880', images: ['https://nextjs.org/og.png'], // Must be an absolute URL }, } ``` ```jsx <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:site:id" content="1467726470533754880" /> <meta name="twitter:creator" content="@nextjs" /> <meta name="twitter:creator:id" content="1467726470533754880" /> <meta name="twitter:title" content="Next.js" /> <meta name="twitter:description" content="The React Framework for the Web" /> <meta name="twitter:image" content="https://nextjs.org/og.png" /> ``` ```javascript export const metadata = { twitter: { card: 'app', title: 'Next.js', description: 'The React Framework for the Web', siteId: '1467726470533754880', creator: '@nextjs', creatorId: '1467726470533754880', images: { url: 'https://nextjs.org/og.png', alt: 'Next.js Logo', }, app: { name: 'twitter_app', id: { iphone: 'twitter_app://iphone', ipad: 'twitter_app://ipad', googleplay: 'twitter_app://googleplay', }, url: { iphone: 'https://iphone_url', ipad: 'https://ipad_url', }, }, }, } ``` ```jsx <meta name="twitter:site:id" content="1467726470533754880" /> <meta name="twitter:creator" content="@nextjs" /> <meta name="twitter:creator:id" content="1467726470533754880" /> <meta name="twitter:title" content="Next.js" /> <meta name="twitter:description" content="The React Framework for the Web" /> <meta name="twitter:card" content="app" /> <meta name="twitter:image" content="https://nextjs.org/og.png" /> <meta name="twitter:image:alt" content="Next.js Logo" /> <meta name="twitter:app:name:iphone" content="twitter_app" /> <meta name="twitter:app:id:iphone" content="twitter_app://iphone" /> <meta name="twitter:app:id:ipad" content="twitter_app://ipad" /> <meta name="twitter:app:id:googleplay" content="twitter_app://googleplay" /> <meta name="twitter:app:url:iphone" content="https://iphone_url" /> <meta name="twitter:app:url:ipad" content="https://ipad_url" /> <meta name="twitter:app:name:ipad" content="twitter_app" /> <meta name="twitter:app:name:googleplay" content="twitter_app" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement archives in Next.js?
Describes a collection of records, documents, or other materials of historical interest (source). ```javascript export const metadata = { archives: ['https://nextjs.org/13'], } ``` ```jsx <link rel="archives" href="https://nextjs.org/13" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement facebook in Next.js?
You can connect a Facebook app or Facebook account to you webpage for certain Facebook Social Plugins Facebook Documentation Good to know: You can specify either appId or admins, but not both. ```javascript export const metadata = { facebook: { appId: '12345678', }, } ``` ```jsx <meta property="fb:app_id" content="12345678" /> ``` ```javascript export const metadata = { facebook: { admins: '12345678', }, } ``` ```jsx <meta property="fb:admins" content="12345678" /> ``` ```javascript export const metadata = { facebook: { admins: ['12345678', '87654321'], }, } ``` ```jsx <meta property="fb:admins" content="12345678" /> <meta property="fb:admins" content="87654321" /> ``` ## Best Practices - If you want to generate multiple fb:admins meta tags you can use array value. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
What are the best practices for facebook in Next.js?
```javascript export const metadata = { facebook: { appId: '12345678', }, } ``` ```jsx <meta property="fb:app_id" content="12345678" /> ``` ```javascript export const metadata = { facebook: { admins: '12345678', }, } ``` ```jsx <meta property="fb:admins" content="12345678" /> ``` ```javascript export const metadata = { facebook: { admins: ['12345678', '87654321'], }, } ``` ```jsx <meta property="fb:admins" content="12345678" /> <meta property="fb:admins" content="87654321" /> ``` ## Best Practices - If you want to generate multiple fb:admins meta tags you can use array value. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement other in Next.js?
All metadata options should be covered using the built-in support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the other option to render any custom metadata tag. ```javascript export const metadata = { other: { custom: 'meta', }, } ``` ```jsx <meta name="custom" content="meta" /> ``` ```javascript export const metadata = { other: { custom: ['meta1', 'meta2'], }, } ``` ```jsx <meta name="custom" content="meta1" /> <meta name="custom" content="meta2" /> ``` ## Best Practices - If you want to generate multiple same key meta tags you can use array value. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
What are the best practices for other in Next.js?
```javascript export const metadata = { other: { custom: 'meta', }, } ``` ```jsx <meta name="custom" content="meta" /> ``` ```javascript export const metadata = { other: { custom: ['meta1', 'meta2'], }, } ``` ```jsx <meta name="custom" content="meta1" /> <meta name="custom" content="meta2" /> ``` ## Best Practices - If you want to generate multiple same key meta tags you can use array value. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement Resource hints in Next.js?
The <link> element has a number of rel keywords that can be used to hint to the browser that an external resource is likely to be needed. The browser uses this information to apply preloading optimizations depending on the keyword. While the Metadata API doesn't directly support these hints, you can use new ReactDOM methods to safely insert them into the <head> of the document. Start loading a resource early in the page rendering (browser) lifecycle. MDN Docs. Preemptively initiate a connection to an origin. MDN Docs. Attempt to resolve a domain name before resources get requested. MDN Docs. Good to know: ```jsx 'use client' import ReactDOM from 'react-dom' export function PreloadResources() { ReactDOM.preload('...', { as: '...' }) ReactDOM.preconnect('...', { crossOrigin: '...' }) ReactDOM.prefetchDNS('...') return '...' } ``` ```css ReactDOM.preload(href: string, options: { as: string }) ``` ```jsx <link rel="preload" href="..." as="..." /> ``` ```css ReactDOM.preconnect(href: string, options?: { crossOrigin?: string }) ``` ```jsx <link rel="preconnect" href="..." crossorigin /> ``` ```jsx <link rel="dns-prefetch" href="..." /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement JavaScript Projects in Next.js?
For JavaScript projects, you can use JSDoc to add type safety. ```javascript /** @type {import("next").Metadata} */ export const metadata = { title: 'Next.js', } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-metadata
How do I implement Example in Next.js?
For example, to split a sitemap using generateSitemaps, return an array of objects with the sitemap id. Then, use the id to generate the unique sitemaps. ```jsx import { BASE_URL } from '@/app/lib/constants' export async function generateSitemaps() { // Fetch the total number of products and calculate the number of sitemaps needed return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }] } export default async function sitemap({ id }) { // Google's limit is 50,000 URLs per sitemap const start = id * 50000 const end = start + 50000 const products = await getProducts( `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}` ) return products.map((product) => ({ url: `${BASE_URL}/product/${id}`, lastModified: product.date, })) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps
How do I implement in Next.js?
The generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time. Good to know: ```jsx // Return a list of `params` to populate the [slug] dynamic segment export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } // Multiple versions of this page will be statically generated // using the `params` returned by `generateStaticParams` export default async function Page({ params }) { const { slug } = await params // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
What are the best practices for Parameters in Next.js?
## Best Practices - If multiple dynamic segments in a route use generateStaticParams, the child generateStaticParams function is executed once for each set of params the parent generates. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
How do I implement All paths at build time in Next.js?
To statically render all paths at build time, supply the full list of paths to generateStaticParams: ```typescript export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) return posts.map((post) => ({ slug: post.slug, })) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
How do I implement Subset of paths at build time in Next.js?
To statically render a subset of paths at build time, and the rest the first time they're visited at runtime, return a partial list of paths: Then, by using the dynamicParams segment config option, you can control what happens when a dynamic segment is visited that was not generated with generateStaticParams. ```typescript export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) // Render the first 10 posts at build time return posts.slice(0, 10).map((post) => ({ slug: post.slug, })) } ``` ```typescript // All posts besides the top 10 will be a 404 export const dynamicParams = false export async function generateStaticParams() { const posts = await fetch('https://.../posts').then((res) => res.json()) const topPosts = posts.slice(0, 10) return topPosts.map((post) => ({ slug: post.slug, })) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
How do I implement All paths at runtime in Next.js?
To statically render all paths the first time they're visited, return an empty array (no paths will be rendered at build time) or utilize export const dynamic = 'force-static': Good to know: You must always return an array from generateStaticParams, even if it's empty. Otherwise, the route will be dynamically rendered. ```javascript export async function generateStaticParams() { return [] } ``` ```javascript export const dynamic = 'force-static' ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
What are the best practices for Multiple Dynamic Segments in a Route in Next.js?
## Best Practices - There are two approaches to generating params for a route with multiple dynamic segments: Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
How do I implement Generate params from the top down in Next.js?
Generate the parent segments first and use the result to generate the child segments. A child route segment's generateStaticParams function is executed once for each segment a parent generateStaticParams generates. The child generateStaticParams function can use the params returned from the parent generateStaticParams function to dynamically generate its own segments. Good to know: fetch requests are automatically memoized for the same data across all generate-prefixed functions, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable. ```jsx // Generate segments for [category] export async function generateStaticParams() { const products = await fetch('https://.../products').then((res) => res.json()) return products.map((product) => ({ category: product.category.slug, })) } export default function Layout({ params }) { // ... } ``` ```jsx // Generate segments for [product] using the `params` passed from // the parent segment's `generateStaticParams` function export async function generateStaticParams({ params: { category } }) { const products = await fetch( `https://.../products?category=${category}` ).then((res) => res.json()) return products.map((product) => ({ product: product.id, })) } export default function Page({ params }) { // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-static-params
How do I implement The viewport object in Next.js?
To define the viewport options, export a viewport object from a layout.jsx or page.jsx file. ```javascript export const viewport = { themeColor: 'black', } export default function Page() {} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-viewport
How do I implement generateViewport function in Next.js?
generateViewport should return a Viewport object containing one or more viewport fields. Good to know: If the viewport doesn't depend on runtime information, it should be defined using the static viewport object rather than generateViewport. ```javascript export function generateViewport({ params }) { return { themeColor: '...', } } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-viewport
How do I implement themeColor in Next.js?
Learn more about theme-color. Simple theme color With media attribute ```javascript export const viewport = { themeColor: 'black', } ``` ```jsx <meta name="theme-color" content="black" /> ``` ```javascript export const viewport = { themeColor: [ { media: '(prefers-color-scheme: light)', color: 'cyan' }, { media: '(prefers-color-scheme: dark)', color: 'black' }, ], } ``` ```tsx <meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" /> <meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-viewport
How do I implement width, initialScale, maximumScale and userScalable in Next.js?
Good to know: The viewport meta tag is automatically set, and manual configuration is usually unnecessary as the default is sufficient. However, the information is provided for completeness. ```javascript export const viewport = { width: 'device-width', initialScale: 1, maximumScale: 1, userScalable: false, // Also supported but less commonly used // interactiveWidget: 'resizes-visual', } ``` ```jsx <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/generate-viewport
How do I implement in Next.js?
headers is an async function that allows you to read the HTTP incoming request headers from a Server Component. ```jsx import { headers } from 'next/headers' export default async function Page() { const headersList = await headers() const userAgent = headersList.get('user-agent') } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/headers
What are the best practices for get(name) in Next.js?
```css // Given incoming request /home // { name: 'show-banner', value: 'false', Path: '/home' } request.cookies.get('show-banner') ``` ## Best Practices - Given a cookie name, return the value of the cookie. If the cookie is not found, undefined is returned. If multiple cookies are found, the first one is returned. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/next-request
How do I implement getAll() in Next.js?
Given a cookie name, return the values of the cookie. If no name is given, return all cookies on the request. ```css // Given incoming request /home // [ // { name: 'experiments', value: 'new-pricing-page', Path: '/home' }, // { name: 'experiments', value: 'winter-launch', Path: '/home' }, // ] request.cookies.getAll('experiments') // Alternatively, get all cookies for the request request.cookies.getAll() ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/next-request
How do I implement nextUrl in Next.js?
The following options are available: Note: The internationalization properties from the Pages Router are not available for usage in the App Router. Learn more about internationalization with the App Router. ```jsx // Given a request to /home, pathname is /home request.nextUrl.pathname // Given a request to /home?name=lee, searchParams is { 'name': 'lee' } request.nextUrl.searchParams ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/next-request
How do I implement notFound() in Next.js?
Good to know: notFound() does not require you to use return notFound() due to using the TypeScript never type. ```javascript import { notFound } from 'next/navigation' async function fetchUser(id) { const res = await fetch('https://...') if (!res.ok) return undefined return res.json() } export default async function Profile({ params }) { const { id } = await params const user = await fetchUser(id) if (!user) { notFound() } // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/not-found
How do I implement Parameters in Next.js?
tag: A string representing the cache tag associated with the data you want to revalidate. Must be less than or equal to 256 characters. This value is case-sensitive. You can add tags to fetch as follows: ```css fetch(url, { next: { tags: [...] } }); ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/revalidateTag
How do I implement in Next.js?
unauthorized can be invoked in Server Components, Server Actions, and Route Handlers. ```jsx import { verifySession } from '@/app/lib/dal' import { unauthorized } from 'next/navigation' export default async function DashboardPage() { const session = await verifySession() if (!session) { unauthorized() } // Render the dashboard for authenticated users return ( <main> <h1>Welcome to the Dashboard</h1> <p>Hi, {session.user.name}.</p> </main> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/unauthorized
How do I implement Displaying login UI to unauthenticated users in Next.js?
You can use unauthorized function to display the unauthorized.js file with a login UI. ```jsx import { verifySession } from '@/app/lib/dal' import { unauthorized } from 'next/navigation' export default async function DashboardPage() { const session = await verifySession() if (!session) { unauthorized() } return <div>Dashboard</div> } ``` ```jsx import Login from '@/app/components/Login' export default function UnauthorizedPage() { return ( <main> <h1>401 - Unauthorized</h1> <p>Please log in to access this page.</p> <Login /> </main> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/unauthorized
How do I implement Mutations with Server Actions in Next.js?
You can invoke unauthorized in Server Actions to ensure only authenticated users can perform specific mutations. ```jsx 'use server' import { verifySession } from '@/app/lib/dal' import { unauthorized } from 'next/navigation' import db from '@/app/lib/db' export async function updateProfile(data) { const session = await verifySession() // If the user is not authenticated, return a 401 if (!session) { unauthorized() } // Proceed with mutation // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/unauthorized
How do I implement Fetching data with Route Handlers in Next.js?
You can use unauthorized in Route Handlers to ensure only authenticated users can access the endpoint. ```jsx import { verifySession } from '@/app/lib/dal' import { unauthorized } from 'next/navigation' export async function GET() { const session = await verifySession() // If the user is not authenticated, return a 401 and render unauthorized.tsx if (!session) { unauthorized() } // Fetch data // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/unauthorized
How do I implement _ in Next.js?
In version 15, we recommend using connection instead of unstable_noStore. unstable_noStore can be used to declaratively opt out of static rendering and indicate a particular component should not be cached. Good to know: unstable_noStore is equivalent to cache: 'no-store' on a fetch unstable_noStore is preferred over export const dynamic = 'force-dynamic' as it is more granular and can be used on a per-component basis Using unstable_noStore inside unstable_cache will not opt out of static generation. Instead, it will defer to the cache configuration to determine whether to cache the result or not. ```javascript import { unstable_noStore as noStore } from 'next/cache'; export default async function ServerComponent() { noStore(); const result = await db.query(...); ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/unstable_noStore
How do I implement in Next.js?
useParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL. ```jsx 'use client' import { useParams } from 'next/navigation' export default function ExampleClientComponent() { const params = useParams() // Route -> /shop/[tag]/[item] // URL -> /shop/shoes/nike-air-max-97 // `params` -> { tag: 'shoes', item: 'nike-air-max-97' } console.log(params) return '...' } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-params
How do I implement in Next.js?
usePathname is a Client Component hook that lets you read the current URL's pathname. usePathname intentionally requires using a Client Component. It's important to note Client Components are not a de-optimization. They are an integral part of the Server Components architecture. For example, a Client Component with usePathname will be rendered into HTML on the initial page load. When navigating to a new route, this component does not need to be re-fetched. Instead, the component is downloaded once (in the client JavaScript bundle), and re-renders based on the current state. Good to know: ```jsx 'use client' import { usePathname } from 'next/navigation' export default function ExampleClientComponent() { const pathname = usePathname() return <p>Current pathname: {pathname}</p> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-pathname
How do I implement in Next.js?
The useReportWebVitals hook allows you to report Core Web Vitals, and can be used in combination with your analytics service. Since the useReportWebVitals hook requires the "use client" directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the WebVitals component. ```javascript 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { console.log(metric) }) return null } ``` ```javascript import { WebVitals } from './_components/web-vitals' export default function Layout({ children }) { return ( <html> <body> <WebVitals /> {children} </body> </html> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals
How do I implement Web Vitals in Next.js?
Web Vitals are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included: You can handle all the results of these metrics using the name property. ```jsx 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { switch (metric.name) { case 'FCP': { // handle FCP results } case 'LCP': { // handle LCP results } // ... } }) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals
How do I implement Sending results to external systems in Next.js?
You can send results to any endpoint to measure and track real user performance on your site. For example: Good to know: If you use Google Analytics, using the id value can allow you to construct metric distributions manually (to calculate percentiles, etc.) Read more about sending results to Google Analytics. Was this helpful? ```typescript useReportWebVitals((metric) => { const body = JSON.stringify(metric) const url = 'https://example.com/analytics' // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. if (navigator.sendBeacon) { navigator.sendBeacon(url, body) } else { fetch(url, { body, method: 'POST', keepalive: true }) } }) ``` ```css useReportWebVitals(metric => { // Use `window.gtag` if you initialized Google Analytics as this example: // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics window.gtag('event', metric.name, { value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), // values must be integers event_label: metric.id, // id unique to current page load non_interaction: true, // avoids affecting bounce rate. }); } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals
How do I implement in Next.js?
useSearchParams is a Client Component hook that lets you read the current URL's query string. useSearchParams returns a read-only version of the URLSearchParams interface. ```jsx 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams = useSearchParams() const search = searchParams.get('search') // URL -> `/dashboard?search=my-project` // `search` -> 'my-project' return <>Search: {search}</> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-search-params
How do I implement Static Rendering in Next.js?
If a route is statically rendered, calling useSearchParams will cause the Client Component tree up to the closest Suspense boundary to be client-side rendered. This allows a part of the route to be statically rendered while the dynamic part that uses useSearchParams is client-side rendered. We recommend wrapping the Client Component that uses useSearchParams in a <Suspense/> boundary. This will allow any Client Components above it to be statically rendered and sent as part of initial HTML. Example. For example: ```jsx 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams = useSearchParams() const search = searchParams.get('search') // This will not be logged on the server when using static rendering console.log(search) return <>Search: {search}</> } ``` ```jsx import { Suspense } from 'react' import SearchBar from './search-bar' // This component passed as a fallback to the Suspense boundary // will be rendered in place of the search bar in the initial HTML. // When the value is available during React hydration the fallback // will be replaced with the `<SearchBar>` component. function SearchBarFallback() { return <>placeholder</> } export default function Page() { return ( <> <nav> <Suspense fallback={<SearchBarFallback />}> <SearchBar /> </Suspense> </nav> <h1>Dashboard</h1> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-search-params
How do I implement Dynamic Rendering in Next.js?
If a route is dynamically rendered, useSearchParams will be available on the server during the initial server render of the Client Component. For example: Good to know: Setting the dynamic route segment config option to force-dynamic can be used to force dynamic rendering. ```jsx 'use client' import { useSearchParams } from 'next/navigation' export default function SearchBar() { const searchParams = useSearchParams() const search = searchParams.get('search') // This will be logged on the server during the initial render // and on the client on subsequent navigations. console.log(search) return <>Search: {search}</> } ``` ```javascript import SearchBar from './search-bar' export const dynamic = 'force-dynamic' export default function Page() { return ( <> <nav> <SearchBar /> </nav> <h1>Dashboard</h1> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-search-params
How do I implement in Next.js?
useSelectedLayoutSegment is a Client Component hook that lets you read the active route segment one level below the Layout it is called from. Good to know: Since useSelectedLayoutSegment is a Client Component hook, and Layouts are Server Components by default, useSelectedLayoutSegment is usually called via a Client Component that is imported into a Layout. useSelectedLayoutSegment only returns the segment one level down. To return all active segments, see useSelectedLayoutSegments ```jsx 'use client' import { useSelectedLayoutSegment } from 'next/navigation' export default function ExampleClientComponent() { const segment = useSelectedLayoutSegment() return <p>Active segment: {segment}</p> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment
How do I implement Parameters in Next.js?
useSelectedLayoutSegment optionally accepts a parallelRoutesKey, which allows you to read the active route segment within that slot. ```javascript const segment = useSelectedLayoutSegment(parallelRoutesKey?: string) ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment
How do I implement in Next.js?
useSelectedLayoutSegments is a Client Component hook that lets you read the active route segments below the Layout it is called from. It is useful for creating UI in parent Layouts that need knowledge of active child segments such as breadcrumbs. Good to know: Since useSelectedLayoutSegments is a Client Component hook, and Layouts are Server Components by default, useSelectedLayoutSegments is usually called via a Client Component that is imported into a Layout. The returned segments include Route Groups, which you might not want to be included in your UI. You can use the filter() array method to remove items that start with a bracket. ```jsx 'use client' import { useSelectedLayoutSegments } from 'next/navigation' export default function ExampleClientComponent() { const segments = useSelectedLayoutSegments() return ( <ul> {segments.map((segment, index) => ( <li key={index}>{segment}</li> ))} </ul> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments
How do I implement Parameters in Next.js?
useSelectedLayoutSegments optionally accepts a parallelRoutesKey, which allows you to read the active route segment within that slot. ```javascript const segments = useSelectedLayoutSegments(parallelRoutesKey?: string) ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments
How do I implement in Next.js?
The userAgent helper extends the Web Request API with additional properties and methods to interact with the user agent object from the request. ```jsx import { NextResponse, userAgent } from 'next/server' export function middleware(request) { const url = request.nextUrl const { device } = userAgent(request) const viewport = device.type === 'mobile' ? 'mobile' : 'desktop' url.searchParams.set('viewport', viewport) return NextResponse.rewrite(url) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/functions/userAgent
How do I implement Configuration in Next.js?
For more in-depth configuration examples, see the Turbopack config documentation. ```javascript module.exports = { experimental: { turbo: { // Example: adding an alias and custom file extension resolveAlias: { underscore: 'lodash', }, resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.json'], }, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/turbopack
How do I implement Adding a nonce with Middleware in Next.js?
Middleware enables you to add headers and generate nonces before the page renders. Every time a page is viewed, a fresh nonce should be generated. This means that you must use dynamic rendering to add nonces. For example: By default, Middleware runs on all requests. You can filter Middleware to run on specific paths using a matcher. ```jsx import { NextResponse } from 'next/server' export function middleware(request) { const nonce = Buffer.from(crypto.randomUUID()).toString('base64') const cspHeader = ` default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}'; img-src 'self' blob: data:; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; ` // Replace newline characters and spaces const contentSecurityPolicyHeaderValue = cspHeader .replace(/\s{2,}/g, ' ') .trim() const requestHeaders = new Headers(request.headers) requestHeaders.set('x-nonce', nonce) requestHeaders.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) const response = NextResponse.next({ request: { headers: requestHeaders, }, }) response.headers.set( 'Content-Security-Policy', contentSecurityPolicyHeaderValue ) return response } ``` ```typescript export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ { source: '/((?!api|_next/static|_next/image|favicon.ico).*)', missing: [ { type: 'header', key: 'next-router-prefetch' }, { type: 'header', key: 'purpose', value: 'prefetch' }, ], }, ], } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
How do I implement Reading the nonce in Next.js?
You can now read the nonce from a Server Component using headers: ```jsx import { headers } from 'next/headers' import Script from 'next/script' export default async function Page() { const nonce = (await headers()).get('x-nonce') return ( <Script src="https://www.googletagmanager.com/gtag/js" strategy="afterInteractive" nonce={nonce} /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
How do I implement C S in Next.js?
Good to know: Take a look at the following example of a custom server: To run the custom server, you'll need to update the scripts in package.json like so: Was this helpful? ```jsx import { createServer } from 'http' import { parse } from 'url' import next from 'next' const port = parseInt(process.env.PORT || '3000', 10) const dev = process.env.NODE_ENV !== 'production' const app = next({ dev }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) handle(req, res, parsedUrl) }).listen(port) console.log( `> Server listening at http://localhost:${port} as ${ dev ? 'development' : process.env.NODE_ENV }` ) }) ``` ```json { "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js" } } ``` ```javascript import next from 'next' const app = next({}) ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/custom-server
How do I implement Server-side code in Next.js?
If you're using npm run dev or yarn dev then you should update the dev script on your package.json: For Chrome: For Firefox: ```jsx { "scripts": { "dev": "NODE_OPTIONS='--inspect' next dev" } } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/debugging
How do I implement Loading Environment Variables with @next/env in Next.js?
To use it, install the package and use the loadEnvConfig function to load the environment variables: Then, you can import the configuration where needed. For example: ```bash npm install @next/env ``` ```jsx import { loadEnvConfig } from '@next/env' const projectDir = process.cwd() loadEnvConfig(projectDir) ``` ```typescript import './envConfig.js' export default defineConfig({ dbCredentials: { connectionString: process.env.DATABASE_URL, }, }) ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
How do I implement Bundling Environment Variables for the Browser in Next.js?
Note that dynamic lookups will not be inlined, such as: ```javascript import setupAnalyticsService from '../lib/my-analytics-service' // 'NEXT_PUBLIC_ANALYTICS_ID' can be used here as it's prefixed by 'NEXT_PUBLIC_'. // It will be transformed at build time to `setupAnalyticsService('abcdefghijk')`. setupAnalyticsService(process.env.NEXT_PUBLIC_ANALYTICS_ID) function HomePage() { return <h1>Hello World</h1> } export default HomePage ``` ```javascript // This will NOT be inlined, because it uses a variable const varName = 'NEXT_PUBLIC_ANALYTICS_ID' setupAnalyticsService(process.env[varName]) // This will NOT be inlined, because it uses a variable const env = process.env setupAnalyticsService(env.NEXT_PUBLIC_ANALYTICS_ID) ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
How do I implement Runtime Environment Variables in Next.js?
You can safely read environment variables on the server during dynamic rendering: Good to know: You can run code on server startup using the register function. We do not recommend using the runtimeConfig option, as this does not work with the standalone output mode. Instead, we recommend incrementally adopting the App Router if you need this feature. ```jsx import { connection } from 'next/server' export default async function Component() { await connection() // cookies, headers, and other Dynamic APIs // will also opt into dynamic rendering, meaning // this env variable is evaluated at runtime const value = process.env.MY_VALUE // ... } ``` ## Best Practices - This allows you to use a singular Docker image that can be promoted through multiple environments with different values. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
What are the best practices for Runtime Environment Variables in Next.js?
```jsx import { connection } from 'next/server' export default async function Component() { await connection() // cookies, headers, and other Dynamic APIs // will also opt into dynamic rendering, meaning // this env variable is evaluated at runtime const value = process.env.MY_VALUE // ... } ``` ## Best Practices - This allows you to use a singular Docker image that can be promoted through multiple environments with different values. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
How do I implement Test Environment Variables in Next.js?
This one is useful when running tests with tools like jest or cypress where you need to set specific environment vars only for testing purposes. Test default values will be loaded if NODE_ENV is set to test, though you usually don't need to do this manually as testing tools will address it for you. There is a small difference between test environment, and both development and production that you need to bear in mind: .env.local won't be loaded, as you expect tests to produce the same results for everyone. This way every test execution will use the same env defaults across different executions by ignoring your .env.local (which is intended to override the default set). Good to know: similar to Default Environment Variables, .env.test file should be included in your repository, but .env.test.local shouldn't, as .env*.local are intended to be ignored through .gitignore. ```jsx // The below can be used in a Jest global setup file or similar for your testing set-up import { loadEnvConfig } from '@next/env' export default async () => { const projectDir = process.cwd() loadEnvConfig(projectDir) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
How do I implement 1. Creating the Web App Manifest in Next.js?
For example, create a app/manifest.ts or app/manifest.json file: You can use tools like favicon generators to create the different icon sets and place the generated files in your public/ folder. ```typescript 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', }, ], } } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
How do I implement 2. Implementing Web Push Notifications in Next.js?
Web Push Notifications are supported with all modern browsers, including: This makes PWAs a viable alternative to native apps. Notably, you can trigger install prompts without needing offline support. First, let's create the main page component in app/page.tsx. We'll break it down into smaller parts for better understanding. First, we’ll add some of the imports and utilities we’ll need. It’s okay that the referenced Server Actions do not yet exist: Let’s now add a component to manage subscribing, unsubscribing, and sending push notifications. Now, let’s create the Server Actions which this file calls. ```javascript 'use client' import { useState, useEffect } from 'react' import { subscribeUser, unsubscribeUser, sendNotification } from './actions' function urlBase64ToUint8Array(base64String) { const padding = '='.repeat((4 - (base64String.length % 4)) % 4) const base64 = (base64String + padding) .replace(/\\-/g, '+') .replace(/_/g, '/') const rawData = window.atob(base64) const outputArray = new Uint8Array(rawData.length) for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i) } return outputArray } ``` ```jsx function PushNotificationManager() { const [isSupported, setIsSupported] = useState(false); const [subscription, setSubscription] = useState(null); const [message, setMessage] = useState(''); useEffect(() => { if ('serviceWorker' in navigator && 'PushManager' in window) { setIsSupported(true); registerServiceWorker(); } }, []); async function registerServiceWorker() { const registration = await navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none', }); const sub = await registration.pushManager.getSubscription(); setSubscription(sub); } async function subscribeToPush() { const registration = await navigator.serviceWorker.ready; const sub = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array( process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY! ), }); setSubscription(sub); await subscribeUser(sub); } async function unsubscribeFromPush() { await subscription?.unsubscribe(); setSubscription(null); await unsubscribeUser(); } async function sendTestNotification() { if (subscription) { await sendNotification(message); setMessage(''); } } if (!isSupported) { return <p>Push notifications are not supported in this browser.</p>; } return ( <div> <h3>Push Notifications</h3> {subscription ? ( <> <p>You are subscribed to push notifications.</p> <button onClick={unsubscribeFromPush}>Unsubscribe</button> <input type="text" placeholder="Enter notification message" value={message} onChange={(e) => setMessage(e.target.value)} /> <button onClick={sendTestNotification}>Send Test</button> </> ) : ( <> <p>You are not subscribed to push notifications.</p> <button onClick={subscribeToPush}>Subscribe</button> </> )} </div> ); } ``` ```jsx function InstallPrompt() { const [isIOS, setIsIOS] = useState(false); const [isStandalone, setIsStandalone] = useState(false); useEffect(() => { setIsIOS( /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream ); setIsStandalone(window.matchMedia('(display-mode: standalone)').matches); }, []); if (isStandalone) { return null; // Don't show install button if already installed } return ( <div> <h3>Install App</h3> <button>Add to Home Screen</button> {isIOS && ( <p> To install this app on your iOS device, tap the share button <span role="img" aria-label="share icon"> {' '} ⎋{' '} </span> and then "Add to Home Screen" <span role="img" aria-label="plus icon"> {' '} ➕{' '} </span> . </p> )} </div> ); } export default function Page() { return ( <div> <PushNotificationManager /> <InstallPrompt /> </div> ); } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
What are the best practices for 3. Implementing Server Actions in Next.js?
## Best Practices - In a production environment, you would want to store the subscription in a database for persistence across server restarts and to manage multiple users' subscriptions. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
How do I implement 4. Generating VAPID Keys in Next.js?
To use the Web Push API, you need to generate VAPID keys. The simplest way is to use the web-push CLI directly: First, install web-push globally: Generate the VAPID keys by running: Copy the output and paste the keys into your .env file: ```bash npm install -g web-push ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
How do I implement 5. Creating a Service Worker in Next.js?
Create a public/sw.js file for your service worker: This service worker supports custom images and notifications. It handles incoming push events and notification clicks. You can set custom icons for notifications using the icon and badge properties. The vibrate pattern can be adjusted to create custom vibration alerts on supported devices. Additional data can be attached to the notification using the data property. Remember to test your service worker thoroughly to ensure it behaves as expected across different devices and browsers. Also, make sure to update the 'https://your-website.com' link in the notificationclick event listener to the appropriate URL for your application. ```javascript self.addEventListener('push', function (event) { if (event.data) { const data = event.data.json() const options = { body: data.body, icon: data.icon || '/icon.png', badge: '/badge.png', vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: '2', }, } event.waitUntil(self.registration.showNotification(data.title, options)) } }) self.addEventListener('notificationclick', function (event) { console.log('Notification click received.') event.notification.close() event.waitUntil(clients.openWindow('<https://your-website.com>')) }) ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
How do I implement 8. Securing your application in Next.js?
Let’s go over each of these options: Global Headers (applied to all routes): X-Content-Type-Options: nosniff: Prevents MIME type sniffing, reducing the risk of malicious file uploads. X-Frame-Options: DENY: Protects against clickjacking attacks by preventing your site from being embedded in iframes. Referrer-Policy: strict-origin-when-cross-origin: Controls how much referrer information is included with requests, balancing security and functionality. Service Worker Specific Headers: Content-Type: application/javascript; charset=utf-8: Ensures the service worker is interpreted correctly as JavaScript. Cache-Control: no-cache, no-store, must-revalidate: Prevents caching of the service worker, ensuring users always get the latest version. Content-Security-Policy: default-src 'self'; script-src 'self': Implements a strict Content Security Policy for the service worker, only allowing scripts from the same origin. X-Content-Type-Options: nosniff: Prevents MIME type sniffing, reducing the risk of malicious file uploads. X-Frame-Options: DENY: Protects against clickjacking attacks by preventing your site from being embedded in iframes. Referrer-Policy: strict-origin-when-cross-origin: Controls how much referrer information is included with requests, balancing security and functionality. Content-Type: application/javascript; charset=utf-8: Ensures the service worker is interpreted correctly as JavaScript. Cache-Control: no-cache, no-store, must-revalidate: Prevents caching of the service worker, ensuring users always get the latest version. Content-Security-Policy: default-src 'self'; script-src 'self': Implements a strict Content Security Policy for the service worker, only allowing scripts from the same origin. ```javascript module.exports = { async headers() { return [ { source: '/(.*)', headers: [ { key: 'X-Content-Type-Options', value: 'nosniff', }, { key: 'X-Frame-Options', value: 'DENY', }, { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin', }, ], }, { source: '/sw.js', headers: [ { key: 'Content-Type', value: 'application/javascript; charset=utf-8', }, { key: 'Cache-Control', value: 'no-cache, no-store, must-revalidate', }, { key: 'Content-Security-Policy', value: "default-src 'self'; script-src 'self'", }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/configuring/progressive-web-apps
How do I implement I S R (ISR) in Next.js?
Incremental Static Regeneration (ISR) enables you to: Here's a minimal example: Here's how this example works: ```jsx // Next.js will invalidate the cache when a // request comes in, at most once every 60 seconds. export const revalidate = 60 // We'll prerender only the params from `generateStaticParams` at build time. // If a request comes in for a path that hasn't been generated, // Next.js will server-render the page on-demand. export const dynamicParams = true // or false, to 404 on unknown paths export async function generateStaticParams() { const posts = await fetch('https://api.vercel.app/blog').then((res) => res.json() ) return posts.map((post) => ({ id: String(post.id), })) } export default async function Page({ params }) { const { id } = await params const post = await fetch(`https://api.vercel.app/blog/${id}`).then((res) => res.json() ) return ( <main> <h1>{post.title}</h1> <p>{post.content}</p> </main> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
How do I implement Time-based revalidation in Next.js?
We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to dynamic rendering. ```jsx export const revalidate = 3600 // invalidate every hour export default async function Page() { const data = await fetch('https://api.vercel.app/blog') const posts = await data.json() return ( <main> <h1>Blog Posts</h1> <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> </main> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
How do I implement On-demand revalidation with revalidatePath in Next.js?
For a more precise method of revalidation, invalidate pages on-demand with the revalidatePath function. For example, this Server Action would get called after adding a new post. Regardless of how you retrieve your data in your Server Component, either using fetch or connecting to a database, this will clear the cache for the entire route and allow the Server Component to fetch fresh data. View a demo and explore the source code. ```jsx 'use server' import { revalidatePath } from 'next/cache' export async function createPost() { // Invalidate the /posts route in the cache revalidatePath('/posts') } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
How do I implement On-demand revalidation with revalidateTag in Next.js?
For most use cases, prefer revalidating entire paths. If you need more granular control, you can use the revalidateTag function. For example, you can tag individual fetch calls: If you are using an ORM or connecting to a database, you can use unstable_cache: You can then use revalidateTag in a Server Actions or Route Handler: ```typescript export default async function Page() { const data = await fetch('https://api.vercel.app/blog', { next: { tags: ['posts'] }, }) const posts = await data.json() // ... } ``` ```jsx import { unstable_cache } from 'next/cache' import { db, posts } from '@/lib/db' const getCachedPosts = unstable_cache( async () => { return await db.select().from(posts) }, ['posts'], { revalidate: 3600, tags: ['posts'] } ) export default async function Page() { const posts = getCachedPosts() // ... } ``` ```jsx 'use server' import { revalidateTag } from 'next/cache' export async function createPost() { // Invalidate all data tagged with 'posts' in the cache revalidateTag('posts') } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
How do I implement Debugging cached data in local development in Next.js?
If you are using the fetch API, you can add additional logging to understand which requests are cached or uncached. Learn more about the logging option. ```javascript module.exports = { logging: { fetches: { fullUrl: true, }, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
How do I implement How to define a zone in Next.js?
The default application handling all paths not routed to another more specific zone does not need an assetPrefix. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { assetPrefix: '/blog-static', } ``` ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { assetPrefix: '/blog-static', async rewrites() { return { beforeFiles: [ { source: '/blog-static/_next/:path+', destination: '/_next/:path+', }, ], } }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/multi-zones
How do I implement How to route requests to the right zone in Next.js?
destination should be a URL that is served by the zone, including scheme and domain. This should point to the zone's production domain, but it can also be used to route requests to localhost in local development. Good to know: URL paths should be unique to a zone. For example, two zones trying to serve /blog would create a routing conflict. ```javascript async rewrites() { return [ { source: '/blog', destination: `${process.env.BLOG_DOMAIN}/blog`, }, { source: '/blog/:path+', destination: `${process.env.BLOG_DOMAIN}/blog/:path+`, } ]; } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/multi-zones
What are the best practices for Routing requests using middleware in Next.js?
```javascript export async function middleware(request) { const { pathname, search } = req.nextUrl; if (pathname === '/your-path' && myFeatureFlag.isEnabled()) { return NextResponse.rewrite(`${rewriteDomain}${pathname}${search}); } } ``` ## Best Practices - Routing requests through rewrites is recommended to minimize latency overhead for the requests, but middleware can also be used when there is a need for a dynamic decision when routing. For example, if you are using a feature flag to decide where a path should be routed such as during a migration, you can use middleware. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/multi-zones
What are the best practices for After deployment in Next.js?
## Best Practices - To get a comprehensive understanding of the best practices for production deployments on Vercel, including detailed strategies for improving website performance, refer to the Vercel Production Checklist. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/production-checklist
How do I implement Client Components in Next.js?
If you want to perform data fetching on the client, you can use a Client Component with SWR to memoize requests. Since route transitions happen client-side, this behaves like a traditional SPA. For example, the following index route allows you to navigate to different posts on the client: ```html import Link from 'next/link' export default function Page() { return ( <> <h1>Index Page</h1> <p> <Link href="/other">Other Page</Link> </p> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/static-exports
How do I implement Image Optimization in Next.js?
This custom loader will define how to fetch images from a remote source. For example, the following loader will construct the URL for Cloudinary: ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', images: { loader: 'custom', loaderFile: './my-loader.ts', }, } module.exports = nextConfig ``` ```jsx export default function cloudinaryLoader({ src, width, quality }) { const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`] return `https://res.cloudinary.com/demo/image/upload/${params.join( ',' )}${src}` } ``` ```jsx import Image from 'next/image' export default function Page() { return <Image alt="turtles" src="/turtles.jpg" width={300} height={300} /> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/static-exports
How do I implement Route Handlers in Next.js?
If you need to read dynamic values from the incoming request, you cannot use a static export. ```typescript export async function GET() { return Response.json({ name: 'Lee' }) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/deploying/static-exports
How do I implement Build Your Own in Next.js?
Since the useReportWebVitals hook requires the "use client" directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the WebVitals component. View the API Reference for more information. ```javascript 'use client' import { useReportWebVitals } from 'next/web-vitals' export function WebVitals() { useReportWebVitals((metric) => { console.log(metric) }) } ``` ```javascript import { WebVitals } from './_components/web-vitals' export default function Layout({ children }) { return ( <html> <body> <WebVitals /> {children} </body> </html> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/analytics
How do I implement Google Fonts in Next.js?
Automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. No requests are sent to Google by the browser. If you can't use a variable font, you will need to specify a weight: ```jsx import { Inter } from 'next/font/google' // If loading a variable font, you don't need to specify the font weight const inter = Inter({ subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={inter.className}> <body>{children}</body> </html> ) } ``` ```jsx import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: '400', subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={roboto.className}> <body>{children}</body> </html> ) } ``` ```javascript const roboto = Roboto({ weight: ['400', '700'], style: ['normal', 'italic'], subsets: ['latin'], display: 'swap', }) ``` ## Best Practices - You can specify multiple weights and/or styles by using an array: - Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
What are the best practices for Google Fonts in Next.js?
```jsx import { Inter } from 'next/font/google' // If loading a variable font, you don't need to specify the font weight const inter = Inter({ subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={inter.className}> <body>{children}</body> </html> ) } ``` ```jsx import { Roboto } from 'next/font/google' const roboto = Roboto({ weight: '400', subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={roboto.className}> <body>{children}</body> </html> ) } ``` ```javascript const roboto = Roboto({ weight: ['400', '700'], style: ['normal', 'italic'], subsets: ['latin'], display: 'swap', }) ``` ## Best Practices - You can specify multiple weights and/or styles by using an array: - Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
How do I implement Specifying a subset in Next.js?
This can be done by adding it to the function call: View the Font API Reference for more information. ```typescript const inter = Inter({ subsets: ['latin'] }) ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
How do I implement Using Multiple Fonts in Next.js?
The first approach is to create a utility function that exports a font, imports it, and applies its className where needed. This ensures the font is preloaded only when it's rendered: In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed. In the example above, Inter will be applied globally, and any <h1> tags will be styled with Roboto Mono. ```typescript import { Inter, Roboto_Mono } from 'next/font/google' export const inter = Inter({ subsets: ['latin'], display: 'swap', }) export const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', }) ``` ```jsx import { inter } from './fonts' export default function Layout({ children }) { return ( <html lang="en" className={inter.className}> <body> <div>{children}</div> </body> </html> ) } ``` ```jsx import { roboto_mono } from './fonts' export default function Page() { return ( <> <h1 className={roboto_mono.className}>My page</h1> </> ) } ``` ```jsx import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], variable: '--font-roboto-mono', display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body> <h1>My App</h1> <div>{children}</div> </body> </html> ) } ``` ## Best Practices - You can import and use multiple fonts in your application. There are two approaches you can take. - Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
What are the best practices for Using Multiple Fonts in Next.js?
```typescript import { Inter, Roboto_Mono } from 'next/font/google' export const inter = Inter({ subsets: ['latin'], display: 'swap', }) export const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', }) ``` ```jsx import { inter } from './fonts' export default function Layout({ children }) { return ( <html lang="en" className={inter.className}> <body> <div>{children}</div> </body> </html> ) } ``` ```jsx import { roboto_mono } from './fonts' export default function Page() { return ( <> <h1 className={roboto_mono.className}>My page</h1> </> ) } ``` ```jsx import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'], variable: '--font-inter', display: 'swap', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], variable: '--font-roboto-mono', display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body> <h1>My App</h1> <div>{children}</div> </body> </html> ) } ``` ```text html { font-family: var(--font-inter); } h1 { font-family: var(--font-roboto-mono); } ``` ## Best Practices - You can import and use multiple fonts in your application. There are two approaches you can take. - Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
What are the best practices for Local Fonts in Next.js?
```jsx import localFont from 'next/font/local' // Font files can be colocated inside of `app` const myFont = localFont({ src: './my-font.woff2', display: 'swap', }) export default function RootLayout({ children }) { return ( <html lang="en" className={myFont.className}> <body>{children}</body> </html> ) } ``` ```typescript const roboto = localFont({ src: [ { path: './Roboto-Regular.woff2', weight: '400', style: 'normal', }, { path: './Roboto-Italic.woff2', weight: '400', style: 'italic', }, { path: './Roboto-Bold.woff2', weight: '700', style: 'normal', }, { path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic', }, ], }) ``` ## Best Practices - If you want to use multiple files for a single font family, src can be an array: Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
How do I implement With Tailwind CSS in Next.js?
Finally, add the CSS variable to your Tailwind CSS config: You can now use the font-sans and font-mono utility classes to apply the font to your elements. ```jsx import { Inter, Roboto_Mono } from 'next/font/google' const inter = Inter({ subsets: ['latin'], display: 'swap', variable: '--font-inter', }) const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', variable: '--font-roboto-mono', }) export default function RootLayout({ children }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body>{children}</body> </html> ) } ``` ```javascript /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}', './app/**/*.{js,ts,jsx,tsx}', ], theme: { extend: { fontFamily: { sans: ['var(--font-inter)'], mono: ['var(--font-roboto-mono)'], }, }, }, plugins: [], } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
What are the best practices for Reusing fonts in Next.js?
## Best Practices - Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it is recommended to do the following: Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
How do I implement Local Images in Next.js?
To use a local image, import your .jpg, .png, or .webp image files. ```javascript import Image from 'next/image' import profilePic from './me.png' export default function Page() { return ( <Image src={profilePic} alt="Picture of the author" // width={500} automatically provided // height={500} automatically provided // blurDataURL="data:..." automatically provided // placeholder="blur" // Optional blur-up while loading /> ) } ``` ```javascript module.exports = { images: { localPatterns: [ { pathname: '/assets/images/**', search: '', }, ], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
How do I implement Remote Images in Next.js?
To use a remote image, the src property should be a URL string. The width and height attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The width and height do not determine the rendered size of the image file. Learn more about Image Sizing. Learn more about remotePatterns configuration. If you want to use relative URLs for the image src, use a loader. ```javascript import Image from 'next/image' export default function Page() { return ( <Image src="https://s3.amazonaws.com/my-bucket/profile.png" alt="Picture of the author" width={500} height={500} /> ) } ``` ```javascript module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 's3.amazonaws.com', port: '', pathname: '/my-bucket/**', search: '', }, ], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
What are the best practices for Loaders in Next.js?
## Best Practices - A loader is a function that generates the URLs for your image. It modifies the provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport. Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
How do I implement Priority in Next.js?
Once you've identified the LCP image, you can add the property like this: ```javascript import Image from 'next/image' import profilePic from '../public/me.png' export default function Page() { return <Image src={profilePic} alt="Picture of the author" priority /> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
What are the best practices for Styling in Next.js?
## Best Practices - Styling the Image component is similar to styling a normal <img> element, but there are a few guidelines to keep in mind: Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
How do I implement Background Image in Next.js?
For examples of the Image component used with the various styles, see the Image Component Demo. ```jsx import Image from 'next/image' import mountains from '../public/mountains.jpg' export default function Background() { return ( <Image alt="Mountains" src={mountains} placeholder="blur" quality={100} fill sizes="100vw" style={{ objectFit: 'cover', }} /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/images
How do I implement Convention in Next.js?
To set up instrumentation, create instrumentation.ts|js file in the root directory of your project (or inside the src folder if using one). Good to know: The instrumentation file should be in the root of your project and not inside the app or pages directory. If you're using the src folder, then place the file inside src alongside pages and app. If you use the pageExtensions config option to add a suffix, you will also need to update the instrumentation filename to match. ```jsx import { registerOTel } from '@vercel/otel' export function register() { registerOTel('next-app') } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
How do I implement Importing files with side effects in Next.js?
Sometimes, it may be useful to import a file in your code because of the side effects it will cause. For example, you might import a file that defines a set of global variables, but never explicitly use the imported file in your code. You would still have access to the global variables the package has declared. We recommend importing files using JavaScript import syntax within your register function. The following example demonstrates a basic usage of import in a register function: Good to know: We recommend importing the file from within the register function, rather than at the top of the file. By doing this, you can colocate all of your side effects in one place in your code, and avoid any unintended consequences from importing globally at the top of the file. ```javascript export async function register() { await import('package-with-side-effect') } ``` Version info: 15.2.1
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation