id
stringlengths
14
15
text
stringlengths
49
1.09k
source
stringlengths
46
101
0819febb67d8-0
MetadataNext.js has a Metadata API that can be used to define your application metadata (e.g. meta and link tags inside your HTML head element) for improved SEO and web shareability. There are two ways you can add metadata to your application: Config-based Metadata: Export a static metadata object or a dynamic generateMetadata function in a layout.js or page.js file. File-based Metadata: Add static or dynamically generated special files to route segments. With both these options, Next.js will automatically generate the relevant <head> elements for your pages. You can also create dynamic OG images using the ImageResponse constructor. Static Metadata To define static metadata, export a Metadata object from a layout.js or static page.js file. layout.tsx / page.tsx import { Metadata } from 'next' export const metadata: Metadata = { title: '...', description: '...', } export default function Page() {}
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-1
description: '...', } export default function Page() {} For all the available options, see the API Reference. Dynamic Metadata You can use generateMetadata function to fetch metadata that requires dynamic values. app/products/[id]/page.tsx import { Metadata, ResolvingMetadata } from 'next' type Props = { params: { id: string } searchParams: { [key: string]: string | string[] | undefined } } export async function generateMetadata( { params, searchParams }: Props, parent?: ResolvingMetadata ): Promise<Metadata> { // read route params const id = params.id // fetch data const product = await fetch(`https://.../${id}`).then((res) => res.json()) // optionally access and extend (rather than replace) parent metadata
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-2
// 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 }: Props) {} For all the available params, see the API Reference. Good to know: Both static and dynamic metadata through generateMetadata are only supported in Server Components. When rendering a route, Next.js will automatically deduplicate fetch requests for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable.
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-3
Next.js will wait for data fetching inside generateMetadata to complete before streaming UI to the client. This guarantees the first part of a streamed response includes <head> tags. File-based metadata These special files are available for metadata: favicon.ico, apple-icon.jpg, and icon.jpg opengraph-image.jpg and twitter-image.jpg robots.txt sitemap.xml You can use these for static metadata, or you can programmatically generate these files with code. For implementation and examples, see the Metadata Files API Reference and Dynamic Image Generation. Behavior File-based metadata has the higher priority and will override any config-based metadata. Default Fields There are two default meta tags that are always added even if a route doesn't define metadata: The meta charset tag sets the character encoding for the website. The meta viewport tag sets the viewport width and scale for the website to adjust for different devices. <meta charset="utf-8" />
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-4
<meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> Good to know: You can overwrite the default viewport meta tag. Ordering Metadata is evaluated in order, starting from the root segment down to the segment closest to the final page.js segment. For example: app/layout.tsx (Root Layout) app/blog/layout.tsx (Nested Blog Layout) app/blog/[slug]/page.tsx (Blog Page) Merging Following the evaluation order, Metadata objects exported from multiple segments in the same route are shallowly merged together to form the final metadata output of a route. Duplicate keys are replaced based on their ordering. This means metadata with nested fields such as openGraph and robots that are defined in an earlier segment are overwritten by the last segment to define them. Overwriting fields app/layout.js export const metadata = { title: 'Acme',
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-5
app/layout.js export const metadata = { title: 'Acme', openGraph: { title: 'Acme', description: 'Acme is a...', }, } app/blog/page.js export const metadata = { title: 'Blog', openGraph: { title: 'Blog', }, } // Output: // <title>Blog</title> // <meta property="og:title" content="Blog" /> In the example above: title from app/layout.js is replaced by title in app/blog/page.js. All openGraph fields from app/layout.js are replaced in app/blog/page.js because app/blog/page.js sets openGraph metadata. Note the absence of openGraph.description. If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable:
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-6
app/shared-metadata.js export const openGraphImage = { images: ['http://...'] } app/page.js import { openGraphImage } from './shared-metadata' export const metadata = { openGraph: { ...openGraphImage, title: 'Home', }, } app/about/page.js import { openGraphImage } from '../shared-metadata' export const metadata = { openGraph: { ...openGraphImage, title: 'About', }, } In the example above, the OG image is shared between app/layout.js and app/about/page.js while the titles are different. Inheriting fields app/layout.js export const metadata = { title: 'Acme', openGraph: { title: 'Acme', description: 'Acme is a...', }, }
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-7
description: 'Acme is a...', }, } app/about/page.js export const metadata = { title: 'About', } // Output: // <title>About</title> // <meta property="og:title" content="Acme" /> // <meta property="og:description" content="Acme is a..." /> Notes title from app/layout.js is replaced by title in app/about/page.js. All openGraph fields from app/layout.js are inherited in app/about/page.js because app/about/page.js doesn't set openGraph metadata. Dynamic Image Generation The ImageResponse constructor allows you to generate dynamic images using JSX and CSS. This is useful for creating social media images such as Open Graph images, Twitter cards, and more. ImageResponse uses the Edge Runtime, and Next.js automatically adds the correct headers to cached images at the edge, helping improve performance and reducing recomputation.
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-8
To use it, you can import ImageResponse from next/server: app/about/route.js import { ImageResponse } from 'next/server' export const runtime = 'edge' export async function GET() { return new ImageResponse( ( <div style={{ fontSize: 128, background: 'white', width: '100%', height: '100%', display: 'flex', textAlign: 'center', alignItems: 'center', justifyContent: 'center', }} > Hello world! </div> ), { width: 1200, height: 600, } ) }
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-9
height: 600, } ) } ImageResponse integrates well with other Next.js APIs, including Route Handlers and file-based Metadata. For example, you can use ImageResponse in a opengraph-image.tsx file to generate Open Graph images at build time or dynamically at request time. ImageResponse supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. See the full list of supported CSS properties. Good to know: Examples are available in the Vercel OG Playground. ImageResponse uses @vercel/og, Satori, and Resvg to convert HTML and CSS into PNG. Only the Edge Runtime is supported. The default Node.js runtime will not work. Only flexbox and a subset of CSS properties are supported. Advanced layouts (e.g. display: grid) will not work.
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-10
Maximum bundle size of 500KB. The bundle size includes your JSX, CSS, fonts, images, and any other assets. If you exceed the limit, consider reducing the size of any assets or fetching at runtime. Only ttf, otf, and woff font formats are supported. To maximize the font parsing speed, ttf or otf are preferred over woff. JSON-LD JSON-LD is a format for structured data that can be used by search engines to understand your content. For example, you can use it to describe a person, an event, an organization, a movie, a book, a recipe, and many other types of entities. Our current recommendation for JSON-LD is to render structured data as a <script> tag in your layout.js or page.js components. For example: app/products/[id]/page.tsx export default async function Page({ params }) { const product = await getProduct(params.id)
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-11
const product = await getProduct(params.id) const jsonLd = { '@context': 'https://schema.org', '@type': 'Product', name: product.name, image: product.image, description: product.description, } return ( <section> {/* Add JSON-LD to your page */} <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} /> {/* ... */} </section> ) } You can validate and test your structured data with the Rich Results Test for Google or the generic Schema Markup Validator. You can type your JSON-LD with TypeScript using community packages like schema-dts: import { Product, WithContext } from 'schema-dts'
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
0819febb67d8-12
import { Product, WithContext } from 'schema-dts' const jsonLd: WithContext<Product> = { '@context': 'https://schema.org', '@type': 'Product', name: 'Next.js Sticker', image: 'https://nextjs.org/imgs/sticker.png', description: 'Dynamic at the speed of static.', }
https://nextjs.org/docs/app/building-your-application/optimizing/metadata
415cdb6e1cf0-0
Static Assets Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/). For example, if you add me.png inside public, the following code will access the image: Avatar.js import Image from 'next/image' export function Avatar() { return <Image src="/me.png" alt="me" width="64" height="64" /> } For static metadata files, such as robots.txt, favicon.ico, etc, you should use special metadata files inside the app folder. Good to know: The directory must be named public. The name cannot be changed and it's the only directory used to serve static assets.
https://nextjs.org/docs/app/building-your-application/optimizing/static-assets
415cdb6e1cf0-1
Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third-party service like AWS S3 for persistent file storage.
https://nextjs.org/docs/app/building-your-application/optimizing/static-assets
444d1c061cc6-0
Lazy Loading Lazy loading in Next.js helps improve the initial loading performance of an application by decreasing the amount of JavaScript needed to render a route. It allows you to defer loading of Client Components and imported libraries, and only include them in the client bundle when they're needed. For example, you might want to defer loading a modal until a user clicks to open it. There are two ways you can implement lazy loading in Next.js: Using Dynamic Imports with next/dynamic Using React.lazy() with Suspense By default, Server Components are automatically code split, and you can use streaming to progressively send pieces of UI from the server to the client. Lazy loading applies to Client Components. next/dynamic next/dynamic is a composite of React.lazy() and Suspense. It behaves the same way in the app and pages directories to allow for incremental migration. Examples Importing Client Components app/page.js 'use client'
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
444d1c061cc6-1
Examples Importing Client Components app/page.js 'use client' import { useState } from 'react' import dynamic from 'next/dynamic' // Client Components: const ComponentA = dynamic(() => import('../components/A')) const ComponentB = dynamic(() => import('../components/B')) const ComponentC = dynamic(() => import('../components/C'), { ssr: false }) export default function ClientComponentExample() { const [showMore, setShowMore] = useState(false) return ( <div> {/* Load immediately, but in a separate client bundle */} <ComponentA /> {/* Load on demand, only when/if the condition is met */} {showMore && <ComponentB />} <button onClick={() => setShowMore(!showMore)}>Toggle</button>
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
444d1c061cc6-2
<button onClick={() => setShowMore(!showMore)}>Toggle</button> {/* Load only on the client side */} <ComponentC /> </div> ) }Skipping SSR When using React.lazy() and Suspense, Client Components will be pre-rendered (SSR) by default.If you want to disable pre-rendering for a Client Component, you can use the ssr option set to false: const ComponentC = dynamic(() => import('../components/C'), { ssr: false })Importing Server Components If you dynamically import a Server Component, only the Client Components that are children of the Server Component will be lazy-loaded - not the Server Component itself.app/page.js import dynamic from 'next/dynamic' // Server Component: const ServerComponent = dynamic(() => import('../components/ServerComponent')) export default function ServerComponentExample() { return ( <div>
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
444d1c061cc6-3
export default function ServerComponentExample() { return ( <div> <ServerComponent /> </div> ) }Loading External Libraries External libraries can be loaded on demand using the import() function. This example uses the external library fuse.js for fuzzy search. The module is only loaded on the client after the user types in the search input.app/page.js 'use client' import { useState } from 'react' const names = ['Tim', 'Joe', 'Bel', 'Lee'] export default function Page() { const [results, setResults] = useState() return ( <div> <input type="text" placeholder="Search" onChange={async (e) => { const { value } = e.currentTarget // Dynamically load fuse.js
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
444d1c061cc6-4
const { value } = e.currentTarget // Dynamically load fuse.js const Fuse = (await import('fuse.js')).default const fuse = new Fuse(names) setResults(fuse.search(value)) }} /> <pre>Results: {JSON.stringify(results, null, 2)}</pre> </div> ) }Adding a custom loading component app/page.js import dynamic from 'next/dynamic' const WithCustomLoading = dynamic( () => import('../components/WithCustomLoading'), { loading: () => <p>Loading...</p>, } ) export default function Page() { return ( <div> {/* The loading component will be rendered while <WithCustomLoading/> is loading */} <WithCustomLoading /> </div> )
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
444d1c061cc6-5
<WithCustomLoading /> </div> ) }Importing Named Exports To dynamically import a named export, you can return it from the Promise returned by import() function:components/hello.js 'use client' export function Hello() { return <p>Hello!</p> }app/page.js import dynamic from 'next/dynamic' const ClientComponent = dynamic(() => import('../components/hello').then((mod) => mod.Hello) )
https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
bc476e93bd3f-0
Analytics Next.js Speed Insights allows you to analyze and measure the performance of pages using different metrics. You can start collecting your Real Experience Score with zero-configuration on Vercel deployments. The rest of this documentation describes the built-in relayer Next.js Speed Insights uses. Web Vitals 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: Time to First Byte (TTFB) First Contentful Paint (FCP) Largest Contentful Paint (LCP) First Input Delay (FID) Cumulative Layout Shift (CLS) Interaction to Next Paint (INP) (experimental)
https://nextjs.org/docs/app/building-your-application/optimizing/analytics
b9c862b437d7-0
OpenTelemetry Good to know: This feature is experimental, you need to explicitly opt-in by providing experimental.instrumentationHook = true; in your next.config.js. Observability is crucial for understanding and optimizing the behavior and performance of your Next.js app. As applications become more complex, it becomes increasingly difficult to identify and diagnose issues that may arise. By leveraging observability tools, such as logging and metrics, developers can gain insights into their application's behavior and identify areas for optimization. With observability, developers can proactively address issues before they become major problems and provide a better user experience. Therefore, it is highly recommended to use observability in your Next.js applications to improve performance, optimize resources, and enhance user experience. We recommend using OpenTelemetry for instrumenting your apps. It's a platform-agnostic way to instrument apps that allows you to change your observability provider without changing your code.
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-1
Read Official OpenTelemetry docs for more information about OpenTelemetry and how it works. This documentation uses terms like Span, Trace or Exporter throughout this doc, all of which can be found in the OpenTelemetry Observability Primer. Next.js supports OpenTelemetry instrumentation out of the box, which means that we already instrumented Next.js itself. When you enable OpenTelemetry we will automatically wrap all your code like getStaticProps in spans with helpful attributes. Good to know: We currently support OpenTelemetry bindings only in serverless functions. We don't provide any for edge or client side code. Getting Started OpenTelemetry is extensible but setting it up properly can be quite verbose. That's why we prepared a package @vercel/otel that helps you get started quickly. It's not extensible and you should configure OpenTelemetry manually if you need to customize your setup. Using @vercel/otel
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-2
Using @vercel/otel To get started, you must install @vercel/otel: Terminal npm install @vercel/otel Next, create a custom instrumentation.ts (or .js) file in the root directory of the project (or inside src folder if using one): your-project/instrumentation.ts import { registerOTel } from '@vercel/otel' export function register() { registerOTel('next-app') } 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. We have created a basic with-opentelemetry example that you can use. Manual OpenTelemetry configuration
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-3
Manual OpenTelemetry configuration If our wrapper @vercel/otel doesn't suit your needs, you can configure OpenTelemetry manually. Firstly you need to install OpenTelemetry packages: Terminal npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http Now you can initialize NodeSDK in your instrumentation.ts. OpenTelemetry APIs are not compatible with edge runtime, so you need to make sure that you are importing them only when process.env.NEXT_RUNTIME === 'nodejs'. We recommend creating a new file instrumentation.node.ts which you conditionally import only when using node: instrumentation.ts export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { await import('./instrumentation.node.ts') } }
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-4
await import('./instrumentation.node.ts') } } instrumentation.node.ts import { NodeSDK } from '@opentelemetry/sdk-node' import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' import { Resource } from '@opentelemetry/resources' import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions' import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node' const sdk = new NodeSDK({ resource: new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: 'next-app', }), spanProcessor: new SimpleSpanProcessor(new OTLPTraceExporter()), }) sdk.start() Doing this is equivalent to using @vercel/otel, but it's possible to modify and extend.
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-5
For example, you could use @opentelemetry/exporter-trace-otlp-grpc instead of @opentelemetry/exporter-trace-otlp-http or you can specify more resource attributes. Testing your instrumentation You need an OpenTelemetry collector with a compatible backend to test OpenTelemetry traces locally. We recommend using our OpenTelemetry dev environment. If everything works well you should be able to see the root server span labeled as GET /requested/pathname. All other spans from that particular trace will be nested under it. Next.js traces more spans than are emitted by default. To see more spans, you must set NEXT_OTEL_VERBOSE=1. Deployment Using OpenTelemetry Collector When you are deploying with OpenTelemetry Collector, you can use @vercel/otel. It will work both on Vercel and when self-hosted. Deploying on Vercel
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-6
Deploying on Vercel We made sure that OpenTelemetry works out of the box on Vercel. Follow Vercel documentation to connect your project to an observability provider. Self-hosting Deploying to other platforms is also straightforward. You will need to spin up your own OpenTelemetry Collector to receive and process the telemetry data from your Next.js app. To do this, follow the OpenTelemetry Collector Getting Started guide, which will walk you through setting up the collector and configuring it to receive data from your Next.js app. Once you have your collector up and running, you can deploy your Next.js app to your chosen platform following their respective deployment guides. Custom Exporters We recommend using OpenTelemetry Collector. If that is not possible on your platform, you can use a custom OpenTelemetry exporter with manual OpenTelemetry configuration Custom Spans You can add a custom span with OpenTelemetry APIs.
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-7
Custom Spans You can add a custom span with OpenTelemetry APIs. Terminal npm install @opentelemetry/api The following example demonstrates a function that fetches GitHub stars and adds a custom fetchGithubStars span to track the fetch request's result: import { trace } from '@opentelemetry/api' export async function fetchGithubStars() { return await trace .getTracer('nextjs-example') .startActiveSpan('fetchGithubStars', async (span) => { try { return await getValue() } finally { span.end() } }) } The register function will execute before your code runs in a new environment. You can start creating new spans, and they should be correctly added to the exported trace. Default Spans in Next.js Next.js automatically instruments several spans for you to provide useful insights into your application's performance.
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-8
Next.js automatically instruments several spans for you to provide useful insights into your application's performance. Attributes on spans follow OpenTelemetry semantic conventions. We also add some custom attributes under the next namespace: next.span_name - duplicates span name next.span_type - each span type has a unique identifier next.route - The route pattern of the request (e.g., /[param]/user). next.page This is an internal value used by an app router. You can think about it as a route to a special file (like page.ts, layout.ts, loading.ts and others) It can be used as a unique identifier only when paired with next.route because /layout can be used to identify both /(groupA)/layout.ts and /(groupB)/layout.ts [http.method] [next.route] next.span_type: BaseServer.handleRequest
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-9
[http.method] [next.route] next.span_type: BaseServer.handleRequest This span represents the root span for each incoming request to your Next.js application. It tracks the HTTP method, route, target, and status code of the request. Attributes: Common HTTP attributes http.method http.status_code Server HTTP attributes http.route http.target next.span_name next.span_type next.route render route (app) [next.route] next.span_type: AppRender.getBodyResult. This span represents the process of rendering a route in the app router. Attributes: next.span_name next.span_type next.route fetch [http.method] [http.url] next.span_type: AppRender.fetch This span represents the fetch request executed in your code. Attributes: Common HTTP attributes http.method Client HTTP attributes http.url net.peer.name net.peer.port (only if specified) next.span_name
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-10
http.url net.peer.name net.peer.port (only if specified) next.span_name next.span_type executing api route (app) [next.route] next.span_type: AppRouteRouteHandlers.runHandler. This span represents the execution of an API route handler in the app router. Attributes: next.span_name next.span_type next.route getServerSideProps [next.route] next.span_type: Render.getServerSideProps. This span represents the execution of getServerSideProps for a specific route. Attributes: next.span_name next.span_type next.route getStaticProps [next.route] next.span_type: Render.getStaticProps. This span represents the execution of getStaticProps for a specific route. Attributes: next.span_name next.span_type next.route render route (pages) [next.route] next.span_type: Render.renderDocument.
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
b9c862b437d7-11
render route (pages) [next.route] next.span_type: Render.renderDocument. This span represents the process of rendering the document for a specific route. Attributes: next.span_name next.span_type next.route generateMetadata [next.page] next.span_type: ResolveMetadata.generateMetadata. This span represents the process of generating metadata for a specific page (a single route can have multiple of these spans). Attributes: next.span_name next.span_type next.page
https://nextjs.org/docs/app/building-your-application/optimizing/open-telemetry
4204567cba57-0
Instrumentation If you export a function named register from a instrumentation.ts (or .js) file in the root directory of your project (or inside the src folder if using one), we will call that function whenever a new Next.js server instance is bootstrapped. Good to know This feature is experimental. To use it, you must explicitly opt in by defining experimental.instrumentationHook = true; in your next.config.js. 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. We have created a basic with-opentelemetry example that you can use. When your register function is deployed, it will be called on each cold boot (but exactly once in each environment).
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
4204567cba57-1
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. You can import files with side effects in instrumentation.ts, which you might want to use in your register function as demonstrated in the following example: your-project/instrumentation.ts import { init } from 'package-init' export function register() { init() } However, we recommend importing files with side effects using import from within your register function instead. The following example demonstrates a basic usage of import in a register function: your-project/instrumentation.ts export async function register() { await import('package-with-side-effect') }
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
4204567cba57-2
await import('package-with-side-effect') } By doing this, you can colocate all of your side effects in one place in your code, and avoid any unintended consequences from importing files. We call register in all environments, so it's necessary to conditionally import any code that doesn't support both edge and nodejs. You can use the environment variable NEXT_RUNTIME to get the current environment. Importing an environment-specific code would look like this: your-project/instrumentation.ts export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { await import('./instrumentation-node') } if (process.env.NEXT_RUNTIME === 'edge') { await import('./instrumentation-edge') } }
https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation
ec80654191bd-0
TypeScript Next.js provides a TypeScript-first development experience for building your React application. It comes with built-in TypeScript support for automatically installing the necessary packages and configuring the proper settings. As well as a TypeScript Plugin for your editor. 🎥 Watch: Learn about the built-in TypeScript plugin → YouTube (3 minutes) New Projects create-next-app now ships with TypeScript by default. Terminal npx create-next-app@latest Existing Projects Add TypeScript to your project by renaming a file to .ts / .tsx. Run next dev and next build to automatically install the necessary dependencies and add a tsconfig.json file with the recommended config options. If you already had a jsconfig.json file, copy the paths compiler option from the old jsconfig.json into the new tsconfig.json file, and delete the old jsconfig.json file. TypeScript Plugin
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-1
TypeScript Plugin Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion.You can enable the plugin in VS Code by: Opening the command palette (Ctrl/⌘ + Shift + P) Searching for "TypeScript: Select TypeScript Version" Selecting "Use Workspace Version" Now, when editing files, the custom plugin will be enabled. When running next build, the custom type checker will be used.Plugin Features The TypeScript plugin can help with: Warning if the invalid values for segment config options are passed. Showing available options and in-context documentation. Ensuring the use client directive is used correctly. Ensuring client hooks (like useState) are only used in Client Components. Good to know: More features will be added in the future. Minimum TypeScript Version
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-2
Good to know: More features will be added in the future. Minimum TypeScript Version It is highly recommended to be on at least v4.5.2 of TypeScript to get syntax features such as type modifiers on import names and performance improvements. Statically Typed Links Next.js can statically type links to prevent typos and other errors when using next/link, improving type safety when navigating between pages.To opt-into this feature, experimental.typedRoutes need to be enabled and the project needs to be using TypeScript.next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { typedRoutes: true, }, }
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-3
experimental: { typedRoutes: true, }, } module.exports = nextConfigNext.js will generate a link definition in .next/types that contains information about all existing routes in your application, which TypeScript can then use to provide feedback in your editor about invalid links.Currently, experimental support includes any string literal, including dynamic segments. For non-literal strings, you currently need to manually cast the href with as Route: import type { Route } from 'next'; import Link from 'next/link' // No TypeScript errors if href is a valid route <Link href="/about" /> <Link href="/blog/nextjs" /> <Link href={`/blog/${slug}`} /> <Link href={('/blog' + slug) as Route} /> // TypeScript errors if href is not a valid route
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-4
// TypeScript errors if href is not a valid route <Link href="/aboot" />To accept href in a custom component wrapping next/link, use a generic: import type { Route } from 'next' import Link from 'next/link' function Card<T extends string>({ href }: { href: Route<T> | URL }) { return ( <Link href={href}> <div>My Card</div> </Link> ) } How does it work? When running next dev or next build, Next.js generates a hidden .d.ts file inside .next that contains information about all existing routes in your application (all valid routes as the href type of Link). This .d.ts file is included in tsconfig.json and the TypeScript compiler will check that .d.ts and provide feedback in your editor about invalid links. End-to-End Type Safety
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-5
End-to-End Type Safety Next.js 13 has enhanced type safety. This includes: No serialization of data between fetching function and page: You can fetch directly in components, layouts, and pages on the server. This data does not need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since app uses Server Components by default, we can use values like Date, Map, Set, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types. Streamlined data flow between components: With the removal of _app in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual pages and _app were difficult to type and could introduce confusing bugs. With colocated data fetching in Next.js 13, this is no longer an issue.
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-6
Data Fetching in Next.js now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.We're able to type the response data as you would expect with normal TypeScript. For example:app/page.tsx async function getData() { const res = await fetch('https://api.example.com/...') // The return value is *not* serialized // You can return Date, Map, Set, etc. return res.json() } export default async function Page() { const name = await getData() return '...' }For complete end-to-end type safety, this also requires your database or content provider to support TypeScript. This could be through using an ORM or type-safe query builder.Async Server Component TypeScript Error
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-7
To use an async Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher.If you are using an older version of TypeScript, you may see a 'Promise<Element>' is not a valid JSX element type error. Updating to the latest version of TypeScript and @types/react should resolve this issue.Passing Data Between Server & Client Components When passing data between a Server and Client Component through props, the data is still serialized (converted to a string) for use in the browser. However, it does not need a special type. It’s typed the same as passing any other props between components.Further, there is less code to be serialized, as un-rendered data does not cross between the server and client (it remains on the server). This is only now possible through support for Server Components. Path aliases and baseUrl
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-8
Path aliases and baseUrl Next.js automatically supports the tsconfig.json "paths" and "baseUrl" options. You can learn more about this feature on the Module Path aliases documentation. Type checking next.config.js The next.config.js file must be a JavaScript file as it does not get parsed by Babel or TypeScript, however you can add some type checking in your IDE using JSDoc as below: // @ts-check /** * @type {import('next').NextConfig} **/ const nextConfig = { /* config options here */ } module.exports = nextConfig Incremental type checking Since v10.2.1 Next.js supports incremental type checking when enabled in your tsconfig.json, this can help speed up type checking in larger applications. Ignoring TypeScript Errors Next.js fails your production build (next build) when TypeScript errors are present in your project.
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-9
Next.js fails your production build (next build) when TypeScript errors are present in your project. If you'd like Next.js to dangerously produce production code even when your application has errors, you can disable the built-in type checking step. If disabled, be sure you are running type checks as part of your build or deploy process, otherwise this can be very dangerous. Open next.config.js and enable the ignoreBuildErrors option in the typescript config: next.config.js module.exports = { typescript: { // !! WARN !! // Dangerously allow production builds to successfully complete even if // your project has type errors. // !! WARN !! ignoreBuildErrors: true, }, } Version Changes
https://nextjs.org/docs/app/building-your-application/configuring/typescript
ec80654191bd-10
ignoreBuildErrors: true, }, } Version Changes VersionChangesv13.2.0Statically typed links are available in beta.v12.0.0SWC is now used by default to compile TypeScript and TSX for faster builds.v10.2.1Incremental type checking support added when enabled in your tsconfig.json.
https://nextjs.org/docs/app/building-your-application/configuring/typescript
37619058cc26-0
ESLint Next.js provides an integrated ESLint experience out of the box. Add next lint as a script to package.json: package.json { "scripts": { "lint": "next lint" } } Then run npm run lint or yarn lint: Terminal yarn lint If you don't already have ESLint configured in your application, you will be guided through the installation and configuration process. Terminal yarn lint You'll see a prompt like this: ? How would you like to configure ESLint? ❯ Strict (recommended) Base Cancel One of the following three options can be selected: Strict: Includes Next.js' base ESLint configuration along with a stricter Core Web Vitals rule-set. This is the recommended configuration for developers setting up ESLint for the first time. .eslintrc.json { "extends": "next/core-web-vitals" }
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-1
"extends": "next/core-web-vitals" } Base: Includes Next.js' base ESLint configuration. .eslintrc.json { "extends": "next" } Cancel: Does not include any ESLint configuration. Only select this option if you plan on setting up your own custom ESLint configuration. If either of the two configuration options are selected, Next.js will automatically install eslint and eslint-config-next as development dependencies in your application and create an .eslintrc.json file in the root of your project that includes your selected configuration. You can now run next lint every time you want to run ESLint to catch errors. Once ESLint has been set up, it will also automatically run during every build (next build). Errors will fail the build, while warnings will not. If you do not want ESLint to run during next build, refer to the documentation for Ignoring ESLint.
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-2
We recommend using an appropriate integration to view warnings and errors directly in your code editor during development. ESLint Config The default configuration (eslint-config-next) includes everything you need to have an optimal out-of-the-box linting experience in Next.js. If you do not have ESLint already configured in your application, we recommend using next lint to set up ESLint along with this configuration. If you would like to use eslint-config-next along with other ESLint configurations, refer to the Additional Configurations section to learn how to do so without causing any conflicts. Recommended rule-sets from the following ESLint plugins are all used within eslint-config-next: eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-next This will take precedence over the configuration from next.config.js. ESLint Plugin
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-3
This will take precedence over the configuration from next.config.js. ESLint Plugin Next.js provides an ESLint plugin, eslint-plugin-next, already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application. The full set of rules is as follows: Enabled in the recommended configuration
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-4
RuleDescription@next/next/google-font-displayEnforce font-display behavior with Google Fonts.@next/next/google-font-preconnectEnsure preconnect is used with Google Fonts.@next/next/inline-script-idEnforce id attribute on next/script components with inline content.@next/next/next-script-for-gaPrefer next/script component when using the inline script for Google Analytics.@next/next/no-assign-module-variablePrevent assignment to the module variable.@next/next/no-async-client-componentPrevent client components from being async functions.@next/next/no-before-interactive-script-outside-documentPrevent usage of next/script's beforeInteractive strategy outside of pages/_document.js.@next/next/no-css-tagsPrevent manual stylesheet tags.@next/next/no-document-import-in-pagePrevent importing next/document outside of pages/_document.js.@next/next/no-duplicate-headPrevent duplicate usage of <Head> in pages/_document.js.@next/next/no-head-elementPrevent usage
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-5
usage of <Head> in pages/_document.js.@next/next/no-head-elementPrevent usage of <head> element.@next/next/no-head-import-in-documentPrevent usage of next/head in pages/_document.js.@next/next/no-html-link-for-pagesPrevent usage of <a> elements to navigate to internal Next.js pages.@next/next/no-img-elementPrevent usage of <img> element due to slower LCP and higher bandwidth.@next/next/no-page-custom-fontPrevent page-only custom fonts.@next/next/no-script-component-in-headPrevent usage of next/script in next/head component.@next/next/no-styled-jsx-in-documentPrevent usage of styled-jsx in pages/_document.js.@next/next/no-sync-scriptsPrevent synchronous scripts.@next/next/no-title-in-document-headPrevent usage of <title> with Head component from next/document.@next/next/no-typosPrevent common typos in Next.js's data fetching
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-6
common typos in Next.js's data fetching functions@next/next/no-unwanted-polyfillioPrevent duplicate polyfills from Polyfill.io.
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-7
If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including eslint-config-next unless a few conditions are met. Refer to the Recommended Plugin Ruleset to learn more. Custom Settings rootDir If you're using eslint-plugin-next in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell eslint-plugin-next where to find your Next.js application using the settings property in your .eslintrc: .eslintrc.json { "extends": "next", "settings": { "next": { "rootDir": "packages/my-app/" } } } rootDir can be a path (relative or absolute), a glob (i.e. "packages/*/"), or an array of paths and/or globs. Linting Custom Directories and Files
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-8
Linting Custom Directories and Files By default, Next.js will run ESLint for all files in the pages/, app/, components/, lib/, and src/ directories. However, you can specify which directories using the dirs option in the eslint config in next.config.js for production builds: next.config.js module.exports = { eslint: { dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build) }, } Similarly, the --dir and --file flags can be used for next lint to lint specific directories and files: Terminal next lint --dir pages --dir utils --file bar.js Caching
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-9
Terminal next lint --dir pages --dir utils --file bar.js Caching To improve performance, information of files processed by ESLint are cached by default. This is stored in .next/cache or in your defined build directory. If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the --no-cache flag with next lint. Terminal next lint --no-cache Disabling Rules If you would like to modify or disable any rules provided by the supported plugins (react, react-hooks, next), you can directly change them using the rules property in your .eslintrc: .eslintrc.json { "extends": "next", "rules": { "react/no-unescaped-entities": "off", "@next/next/no-page-custom-font": "off" } } Core Web Vitals
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-10
} } Core Web Vitals The next/core-web-vitals rule set is enabled when next lint is run for the first time and the strict option is selected. .eslintrc.json { "extends": "next/core-web-vitals" } next/core-web-vitals updates eslint-plugin-next to error on a number of rules that are warnings by default if they affect Core Web Vitals. The next/core-web-vitals entry point is automatically included for new applications built with Create Next App. Usage With Other Tools Prettier ESLint also contains code formatting rules, which can conflict with your existing Prettier setup. We recommend including eslint-config-prettier in your ESLint config to make ESLint and Prettier work together. First, install the dependency: Terminal npm install --save-dev eslint-config-prettier yarn add --dev eslint-config-prettier
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-11
yarn add --dev eslint-config-prettier Then, add prettier to your existing ESLint config: .eslintrc.json { "extends": ["next", "prettier"] } lint-staged If you would like to use next lint with lint-staged to run the linter on staged git files, you'll have to add the following to the .lintstagedrc.js file in the root of your project in order to specify usage of the --file flag. .lintstagedrc.js const path = require('path') const buildEslintCommand = (filenames) => `next lint --fix --file ${filenames .map((f) => path.relative(process.cwd(), f)) .join(' --file ')}` module.exports = { '*.{js,jsx,ts,tsx}': [buildEslintCommand],
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-12
'*.{js,jsx,ts,tsx}': [buildEslintCommand], } Migrating Existing Config Recommended Plugin Ruleset If you already have ESLint configured in your application and any of the following conditions are true: You have one or more of the following plugins already installed (either separately or through a different config such as airbnb or react-app): react react-hooks jsx-a11y import You've defined specific parserOptions that are different from how Babel is configured within Next.js (this is not recommended unless you have customized your Babel configuration) You have eslint-plugin-import installed with Node.js and/or TypeScript resolvers defined to handle imports Then we recommend either removing these settings if you prefer how these properties have been configured within eslint-config-next or extending directly from the Next.js ESLint plugin instead: module.exports = { extends: [ //...
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-13
module.exports = { extends: [ //... 'plugin:@next/next/recommended', ], } The plugin can be installed normally in your project without needing to run next lint: Terminal npm install --save-dev @next/eslint-plugin-next yarn add --dev @next/eslint-plugin-next This eliminates the risk of collisions or errors that can occur due to importing the same plugin or parser across multiple configurations. Additional Configurations If you already use a separate ESLint configuration and want to include eslint-config-next, ensure that it is extended last after other configurations. For example: .eslintrc.json { "extends": ["eslint:recommended", "next"] } The next configuration already handles setting default values for the parser, plugins and settings properties. There is no need to manually re-declare any of these properties unless you need a different configuration for your use case.
https://nextjs.org/docs/app/building-your-application/configuring/eslint
37619058cc26-14
If you include any other shareable configurations, you will need to make sure that these properties are not overwritten or modified. Otherwise, we recommend removing any configurations that share behavior with the next configuration or extending directly from the Next.js ESLint plugin as mentioned above.
https://nextjs.org/docs/app/building-your-application/configuring/eslint
8404cd2451c8-0
Environment Variables Examples Environment Variables Next.js comes with built-in support for environment variables, which allows you to do the following: Use .env.local to load environment variables Bundle environment variables for the browser by prefixing with NEXT_PUBLIC_ Loading Environment Variables Next.js has built-in support for loading environment variables from .env.local into process.env. .env.local DB_HOST=localhost DB_USER=myuser DB_PASS=mypassword This loads process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically allowing you to use them in Route Handlers.For example:app/api/route.js export async function GET() { const db = await myDB.connect({ host: process.env.DB_HOST, username: process.env.DB_USER, password: process.env.DB_PASS, }) // ... } Referencing Other Variables
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-1
}) // ... } Referencing Other Variables Next.js will automatically expand variables that use $ to reference other variables e.g. $VARIABLE inside of your .env* files. This allows you to reference other secrets. For example: .env TWITTER_USER=nextjs TWITTER_URL=https://twitter.com/$TWITTER_USER In the above example, process.env.TWITTER_URL would be set to https://twitter.com/nextjs. Good to know: If you need to use variable with a $ in the actual value, it needs to be escaped e.g. \$. Bundling Environment Variables for the Browser Non-NEXT_PUBLIC_ environment variables are only available in the Node.js environment, meaning they aren't accessible to the browser (the client runs in a different environment).
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-2
In order to make the value of an environment variable accessible in the browser, Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to process.env.[variable] with a hard-coded value. To tell it to do this, you just have to prefix the variable with NEXT_PUBLIC_. For example: Terminal NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk This will tell Next.js to replace all references to process.env.NEXT_PUBLIC_ANALYTICS_ID in the Node.js environment with the value from the environment in which you run next build, allowing you to use it anywhere in your code. It will be inlined into any JavaScript sent to the browser.
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-3
Note: After being built, your app will no longer respond to changes to these environment variables. For instance, if you use a Heroku pipeline to promote slugs built in one environment to another environment, or if you build and deploy a single Docker image to multiple environments, all NEXT_PUBLIC_ variables will be frozen with the value evaluated at build time, so these values need to be set appropriately when the project is built. If you need access to runtime environment values, you'll have to setup your own API to provide them to the client (either on demand or during initialization). pages/index.js 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() {
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-4
function HomePage() { return <h1>Hello World</h1> } export default HomePage Note that dynamic lookups will not be inlined, such as: // 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) Default Environment Variables In general only one .env.local file is needed. However, sometimes you might want to add some defaults for the development (next dev) or production (next start) environment. Next.js allows you to set defaults in .env (all environments), .env.development (development environment), and .env.production (production environment). .env.local always overrides the defaults set.
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-5
.env.local always overrides the defaults set. Good to know: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored. Environment Variables on Vercel When deploying your Next.js application to Vercel, Environment Variables can be configured in the Project Settings. All types of Environment Variables should be configured there. Even Environment Variables used in Development – which can be downloaded onto your local device afterwards. If you've configured Development Environment Variables you can pull them into a .env.local for usage on your local machine using the following command: Terminal vercel env pull .env.local Test Environment Variables
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-6
Terminal vercel env pull .env.local Test Environment Variables Apart from development and production environments, there is a 3rd option available: test. In the same way you can set defaults for development or production environments, you can do the same with a .env.test file for the testing environment (though this one is not as common as the previous two). Next.js will not load environment variables from .env.development or .env.production in the testing environment. 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.
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-7
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. While running unit tests you can make sure to load your environment variables the same way Next.js does by leveraging the loadEnvConfig function from the @next/env package. // 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 () => {
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
8404cd2451c8-8
export default async () => { const projectDir = process.cwd() loadEnvConfig(projectDir) } Environment Variable Load Order Environment variables are looked up in the following places, in order, stopping once the variable is found. process.env .env.$(NODE_ENV).local .env.local (Not checked when NODE_ENV is test.) .env.$(NODE_ENV) .env For example, if NODE_ENV is development and you define a variable in both .env.development.local and .env, the value in .env.development.local will be used. Good to know: The allowed values for NODE_ENV are production, development and test. Good to know If you are using a /src directory, .env.* files should remain in the root of your project. If the environment variable NODE_ENV is unassigned, Next.js automatically assigns development when running the next dev command, or production for all other commands.
https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
969d964bad5d-0
Absolute Imports and Module Path Aliases Examples Absolute Imports and Aliases Next.js has in-built support for the "paths" and "baseUrl" options of tsconfig.json and jsconfig.json files. These options allow you to alias project directories to absolute paths, making it easier to import modules. For example: // before import { Button } from '../../../components/button' // after import { Button } from '@/components/button' Good to know: create-next-app will prompt to configure these options for you. Absolute Imports The baseUrl configuration option allows you to import directly from the root of the project. An example of this configuration: tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": "." } } components/button.tsx export default function Button() { return <button>Click me</button> } app/page.tsx import Button from 'components/button'
https://nextjs.org/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases
969d964bad5d-1
} app/page.tsx import Button from 'components/button' export default function HomePage() { return ( <> <h1>Hello World</h1> <Button /> </> ) } Module Aliases In addition to configuring the baseUrl path, you can use the "paths" option to "alias" module paths. For example, the following configuration maps @/components/* to components/*: tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": ".", "paths": { "@/components/*": ["components/*"] } } } components/button.tsx export default function Button() { return <button>Click me</button> } app/page.tsx import Button from '@/components/button' export default function HomePage() { return ( <>
https://nextjs.org/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases
969d964bad5d-2
export default function HomePage() { return ( <> <h1>Hello World</h1> <Button /> </> ) } Each of the "paths" are relative to the baseUrl location. For example: // tsconfig.json or jsconfig.json { "compilerOptions": { "baseUrl": "src/", "paths": { "@/styles/*": ["styles/*"], "@/components/*": ["components/*"] } } } // pages/index.js import Button from '@/components/button' import '@/styles/styles.css' import Helper from 'utils/helper' export default function HomePage() { return ( <Helper> <h1>Hello World</h1> <Button /> </Helper> ) }
https://nextjs.org/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases
7cbea5741ded-0
MDX Markdown is a lightweight markup language used to format text. It allows you to write using plain text syntax and convert it to structurally valid HTML. It's commonly used for writing content on websites and blogs. You write... I **love** using [Next.js](https://nextjs.org/) Output: <p>I <strong>love</strong> using <a href="https://nextjs.org/">Next.js</a></p> MDX is a superset of markdown that lets you write JSX directly in your markdown files. It is a powerful way to add dynamic interactivity and embed React components within your content. Next.js can support both local MDX content inside your application, as well as remote MDX files fetched dynamically on the server. The Next.js plugin handles transforming Markdown and React components into HTML, including support for usage in Server Components (default in app). @next/mdx
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-1
@next/mdx The @next/mdx package is configured in the next.config.js file at your projects root. It sources data from local files, allowing you to create pages with a .mdx extension, directly in your /pages or /app directory. Getting Started Install the @next/mdx package:Terminal npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdxCreate mdx-components.tsx in the root of your application (the parent folder of app/ or src/):mdx-components.tsx import type { MDXComponents } from 'mdx/types' // This file allows you to provide custom React components // to be used in MDX files. You can import and use any // React component you want, including components from // other libraries. // This file is required to use MDX in `app` directory.
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-2
// This file is required to use MDX in `app` directory. export function useMDXComponents(components: MDXComponents): MDXComponents { return { // Allows customizing built-in components, e.g. to add styling. // h1: ({ children }) => <h1 style={{ fontSize: "100px" }}>{children}</h1>, ...components, } }Update next.config.js to use mdxRs:next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { mdxRs: true, }, } const withMDX = require('@next/mdx')() module.exports = withMDX(nextConfig)Add a new file with MDX content to your app directory:app/hello.mdx Hello, Next.js!
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-3
You can import and use React components in MDX files.Import the MDX file inside a page to display the content:app/page.tsx import HelloWorld from './hello.mdx' export default function Page() { return <HelloWorld /> } Remote MDX If your Markdown or MDX files do not live inside your application, you can fetch them dynamically on the server. This is useful for fetching content from a CMS or other data source. There are two popular community packages for fetching MDX content: next-mdx-remote and contentlayer. For example, the following example uses next-mdx-remote: Good to know: Please proceed with caution. MDX compiles to JavaScript and is executed on the server. You should only fetch MDX content from a trusted source, otherwise this can lead to remote code execution (RCE).
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-4
app/page.tsx import { MDXRemote } from 'next-mdx-remote/rsc' export default async function Home() { const res = await fetch('https://...') const markdown = await res.text() return <MDXRemote source={markdown} /> } Layouts To share a layout around MDX content, you can use the built-in layouts support with the App Router. Remark and Rehype Plugins You can optionally provide remark and rehype plugins to transform the MDX content. For example, you can use remark-gfm to support GitHub Flavored Markdown. Since the remark and rehype ecosystem is ESM only, you'll need to use next.config.mjs as the configuration file. next.config.mjs import remarkGfm from 'remark-gfm' import createMDX from '@next/mdx'
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-5
import createMDX from '@next/mdx' /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, }, } const withMDX = createMDX({ options: { extension: /\.mdx?$/, remarkPlugins: [remarkGfm], rehypePlugins: [], // If you use `MDXProvider`, uncomment the following line. // providerImportSource: "@mdx-js/react", }, }) export default withMDX(nextConfig) Frontmatter Frontmatter is a YAML like key/value pairing that can be used to store data about a page. @next/mdx does not support frontmatter by default, though there are many solutions for adding frontmatter to your MDX content, such as gray-matter.
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-6
To access page metadata with @next/mdx, you can export a meta object from within the .mdx file: export const meta = { author: 'Rich Haines', } # My MDX page Custom Elements One of the pleasant aspects of using markdown, is that it maps to native HTML elements, making writing fast, and intuitive: This is a list in markdown: - One - Two - Three The above generates the following HTML: <p>This is a list in markdown:</p> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul>
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-7
<li>Three</li> </ul> When you want to style your own elements to give a custom feel to your website or application, you can pass in shortcodes. These are your own custom components that map to HTML elements. To do this you use the MDXProvider and pass a components object as a prop. Each object key in the components object maps to a HTML element name. To enable you need to specify providerImportSource: "@mdx-js/react" in next.config.js. next.config.js const withMDX = require('@next/mdx')({ // ... options: { providerImportSource: '@mdx-js/react', }, }) Then setup the provider in your page pages/index.js import { MDXProvider } from '@mdx-js/react' import Image from 'next/image' import { Heading, InlineCode, Pre, Table, Text } from 'my-components'
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-8
import { Heading, InlineCode, Pre, Table, Text } from 'my-components' const ResponsiveImage = (props) => ( <Image alt={props.alt} sizes="100vw" style={{ width: '100%', height: 'auto' }} {...props} /> ) const components = { img: ResponsiveImage, h1: Heading.H1, h2: Heading.H2, p: Text, pre: Pre, code: InlineCode, } export default function Post(props) { return ( <MDXProvider components={components}> <main {...props} /> </MDXProvider> ) }
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-9
<main {...props} /> </MDXProvider> ) } If you use it across the site you may want to add the provider to _app.js so all MDX pages pick up the custom element config. Deep Dive: How do you transform markdown into HTML? React does not natively understand Markdown. The markdown plaintext needs to first be transformed into HTML. This can be accomplished with remark and rehype. remark is an ecosystem of tools around markdown. rehype is the same, but for HTML. For example, the following code snippet transforms markdown into HTML: import { unified } from 'unified' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' main() async function main() {
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-10
main() async function main() { const file = await unified() .use(remarkParse) // Convert into markdown AST .use(remarkRehype) // Transform to HTML AST .use(rehypeSanitize) // Sanitize HTML input .use(rehypeStringify) // Convert AST into serialized HTML .process('Hello, Next.js!') console.log(String(file)) // <p>Hello, Next.js!</p> } The remark and rehype ecosystem contains plugins for syntax highlighting, linking headings, generating a table of contents, and more. When using @next/mdx as shown below, you do not need to use remark or rehype directly, as it is handled for you. Using the Rust-based MDX compiler (Experimental)
https://nextjs.org/docs/app/building-your-application/configuring/mdx
7cbea5741ded-11
Using the Rust-based MDX compiler (Experimental) Next.js supports a new MDX compiler written in Rust. This compiler is still experimental and is not recommended for production use. To use the new compiler, you need to configure next.config.js when you pass it to withMDX: next.config.js module.exports = withMDX({ experimental: { mdxRs: true, }, }) Helpful Links MDX @next/mdx remark rehype
https://nextjs.org/docs/app/building-your-application/configuring/mdx
c6ec912627f5-0
src Directory As an alternative to having the special Next.js app or pages directories in the root of your project, Next.js also supports the common pattern of placing application code under the src directory. This separates application code from project configuration files which mostly live in the root of a project. Which is preferred by some individuals and teams. To use the src directory, move the app Router folder or pages Router folder to src/app or src/pages respectively. Good to know The /public directory should remain in the root of your project. Config files like package.json, next.config.js and tsconfig.json should remain in the root of your project. .env.* files should remain in the root of your project. src/app or src/pages will be ignored if app or pages are present in the root directory. If you're using src, you'll probably also move other application folders such as /components or /lib.
https://nextjs.org/docs/app/building-your-application/configuring/src-directory
c6ec912627f5-1
If you're using Tailwind CSS, you'll need to add the /src prefix to the tailwind.config.js file in the content section.
https://nextjs.org/docs/app/building-your-application/configuring/src-directory
f6d31d7ef0e5-0
Draft ModeStatic rendering is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to view the draft immediately on your page. You’d want Next.js to render these pages at request time instead of build time and fetch the draft content instead of the published content. You’d want Next.js to switch to dynamic rendering only for this specific case. Next.js has a feature called Draft Mode which solves this problem. Here are instructions on how to use it. Step 1: Create and access the Route Handler First, create a Route Handler. It can have any name - e.g. app/api/draft/route.ts Then, import draftMode from next/headers and call the enable() method. app/api/draft/route.ts // route handler enabling draft mode import { draftMode } from 'next/headers'
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-1
import { draftMode } from 'next/headers' export async function GET(request: Request) { draftMode().enable() return new Response('Draft mode is enabled') } This will set a cookie to enable draft mode. Subsequent requests containing this cookie will trigger Draft Mode changing the behavior for statically generated pages (more on this later). You can test this manually by visiting /api/draft and looking at your browser’s developer tools. Notice the Set-Cookie response header with a cookie named __prerender_bypass. Securely accessing it from your Headless CMS In practice, you’d want to call this Route Handler securely from your headless CMS. The specific steps will vary depending on which headless CMS you’re using, but here are some common steps you could take.
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-2
These steps assume that the headless CMS you’re using supports setting custom draft URLs. If it doesn’t, you can still use this method to secure your draft URLs, but you’ll need to construct and access the draft URL manually. First, you should create a secret token string using a token generator of your choice. This secret will only be known by your Next.js app and your headless CMS. This secret prevents people who don’t have access to your CMS from accessing draft URLs. Second, if your headless CMS supports setting custom draft URLs, specify the following as the draft URL. This assumes that your Route Handler is located at app/api/draft/route.ts Terminal https://<your-site>/api/draft?secret=<token>&slug=<path> <your-site> should be your deployment domain. <token> should be replaced with the secret token you generated.
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-3
<token> should be replaced with the secret token you generated. <path> should be the path for the page that you want to view. If you want to view /posts/foo, then you should use &slug=/posts/foo. Your headless CMS might allow you to include a variable in the draft URL so that <path> can be set dynamically based on the CMS’s data like so: &slug=/posts/{entry.fields.slug} Finally, in the Route Handler: Check that the secret matches and that the slug parameter exists (if not, the request should fail). Call draftMode.enable() to set the cookie. Then redirect the browser to the path specified by slug. app/api/draft/route.ts // route handler with secret and slug import { draftMode } from 'next/headers' import { redirect } from 'next/navigation' export async function GET(request: Request) { // Parse query string parameters
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-4
export async function GET(request: Request) { // Parse query string parameters const { searchParams } = new URL(request.url) const secret = searchParams.get('secret') const slug = searchParams.get('slug') // Check the secret and next parameters // This secret should only be known to this route handler and the CMS if (secret !== 'MY_SECRET_TOKEN' || !slug) { return new Response('Invalid token', { status: 401 }) } // Fetch the headless CMS to check if the provided `slug` exists // getPostBySlug would implement the required fetching logic to the headless CMS const post = await getPostBySlug(slug) // If the slug doesn't exist prevent draft mode from being enabled if (!post) {
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-5
if (!post) { return new Response('Invalid slug', { status: 401 }) } // Enable Draft Mode by setting the cookie draftMode().enable() // Redirect to the path from the fetched post // We don't redirect to searchParams.slug as that might lead to open redirect vulnerabilities redirect(post.slug) } If it succeeds, then the browser will be redirected to the path you want to view with the draft mode cookie. Step 2: Update page The next step is to update your page to check the value of draftMode().isEnabled. If you request a page which has the cookie set, then data will be fetched at request time (instead of at build time). Furthermore, the value of isEnabled will be true. app/page.tsx // page that fetches data import { draftMode } from 'next/headers'
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-6
import { draftMode } from 'next/headers' async function getData() { const { isEnabled } = draftMode() const url = isEnabled ? 'https://draft.example.com' : 'https://production.example.com' const res = await fetch(url) return res.json() } export default async function Page() { const { title, desc } = await getData() return ( <main> <h1>{title}</h1> <p>{desc}</p> </main> ) } That's it! If you access the draft Route Handler (with secret and slug) from your headless CMS or manually, you should now be able to see the draft content. And if you update your draft without publishing, you should be able to view the draft.
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-7
Set this as the draft URL on your headless CMS or access manually, and you should be able to see the draft. Terminal https://<your-site>/api/draft?secret=<token>&slug=<path> More Details Clear the Draft Mode cookie By default, the Draft Mode session ends when the browser is closed. To clear the Draft Mode cookie manually, create a Route Handler that calls draftMode().disable(): app/api/disable-draft/route.ts import { draftMode } from 'next/headers' export async function GET(request: Request) { draftMode().disable() return new Response('Draft mode is disabled') } Then, send a request to /api/disable-draft to invoke the Route Handler. If calling this route using next/link, you must pass prefetch={false} to prevent accidentally deleting the cookie on prefetch. Unique per next build
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
f6d31d7ef0e5-8
Unique per next build A new bypass cookie value will be generated each time you run next build. This ensures that the bypass cookie can’t be guessed. Good to know: To test Draft Mode locally over HTTP, your browser will need to allow third-party cookies and local storage access.
https://nextjs.org/docs/app/building-your-application/configuring/draft-mode
3a945247eb53-0
Static Exports Next.js enables starting as a static site or Single-Page Application (SPA), then later optionally upgrading to use features that require a server. When running next build, Next.js generates an HTML file per route. By breaking a strict SPA into individual HTML files, Next.js can avoid loading unnecessary JavaScript code on the client-side, reducing the bundle size and enabling faster page loads. Since Next.js supports this static export, it can be deployed and hosted on any web server that can serve HTML/CSS/JS static assets. Configuration To enable a static export, change the output mode inside next.config.js: next.config.js /** * @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // Optional: Add a trailing slash to all paths `/about` -> `/about/` // trailingSlash: true,
https://nextjs.org/docs/app/building-your-application/deploying/static-exports
3a945247eb53-1
// trailingSlash: true, // Optional: Change the output directory `out` -> `dist` // distDir: 'dist', } module.exports = nextConfig After running next build, Next.js will produce an out folder which contains the HTML/CSS/JS assets for your application. Supported Features The core of Next.js has been designed to support static exports.Server Components When you run next build to generate a static export, Server Components consumed inside the app directory will run during the build, similar to traditional static-site generation.The resulting component will be rendered into static HTML for the initial page load and a static payload for client navigation between routes. No changes are required for your Server Components when using the static export, unless they consume dynamic server functions.app/page.tsx export default async function Page() { // This fetch will run on the server during `next build`
https://nextjs.org/docs/app/building-your-application/deploying/static-exports