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 generate... | 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: ... | 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, searchPa... | 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 twi... | 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 (Ro... | 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 th... | 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 ... | 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.
A... | 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: ... | 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 ... | 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.... | 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="applica... | 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... | 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, y... | 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('../... | 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... | 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 af... | 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 cus... | 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... | 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
We... | 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 become... | 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... | 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 functi... | 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 @o... | 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-co... | 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 OpenT... | 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 te... | 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... | 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 ... | 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
h... | 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
getServerSide... | 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 o... | 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... | 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... | 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. Y... | 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... | 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"
Selec... | 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 ot... | 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 ... | 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}>
<... | 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... | 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://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 shoul... | 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, howeve... | 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... | 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 throug... | 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... | 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 configur... | 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 t... | 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 componen... | 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 usag... | 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.j... | 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: ... | 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 nee... | 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 Co... | 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 o... | 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 ... | 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... | 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 bui... | 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, p... | 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 N... | 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 f... | 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 i... | 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 Variab... | 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 on... | 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 .en... | 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.)
.en... | 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
... | 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 configur... | 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/*"],
... | 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> usi... | 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 @md... | 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,
}
}Upda... | 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 dy... | 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 Ap... | 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 followin... | 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... | 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 obj... | 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,
... | 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... | 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... | 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({
expe... | 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. W... | 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 in... | 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 ... | 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 se... | 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 ... | 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... | 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 ... | 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, ... | 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 manual... | 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 ... | 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 su... | https://nextjs.org/docs/app/building-your-application/deploying/static-exports |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.