id stringlengths 14 15 | text stringlengths 49 1.09k | source stringlengths 38 101 |
|---|---|---|
e828fcbbfa62-3 | This strategy is still experimental and can only be used if the nextScriptWorkers flag is enabled in next.config.js:
next.config.js module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
Then, run next (normally npm run dev or yarn dev) and Next.js will guide you through the installation of the requir... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts |
e828fcbbfa62-4 | </>
)
}
There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's tradeoffs documentation for more information.
Inline Scripts
Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can b... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts |
e828fcbbfa62-5 | Executing Additional Code
Event handlers can be used with the Script component to execute additional code after a certain event occurs:
onLoad: Execute code after the script has finished loading.
onReady: Execute code after the script has finished loading and every time the component is mounted.
onError: Execute code i... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts |
e828fcbbfa62-6 | }Refer to the next/script API reference to learn more about each event handler and view examples.
Additional Attributes
There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will autom... | https://nextjs.org/docs/app/building-your-application/optimizing/scripts |
879123bca830-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 |
879123bca830-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 |
92a12b7fcec5-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 |
92a12b7fcec5-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 |
92a12b7fcec5-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 |
92a12b7fcec5-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 |
92a12b7fcec5-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 |
92a12b7fcec5-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 |
b364d2bb158f-0 | Font Optimization
next/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance.
🎥 Watch: Learn more about how to use next/font → YouTube (6 minutes).
next/font includes built-in automatic self-hosting for any font file. This means y... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-1 | Get started by importing the font you would like to use from next/font/google as a function. We recommend using variable fonts for the best performance and flexibility.
app/layout.tsx import { Inter } from 'next/font/google'
// If loading a variable font, you don't need to specify the font weight
const inter = Inter(... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-2 | const roboto = Roboto({
weight: '400',
subsets: ['latin'],
display: 'swap',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}
You can specify multiple weights and/... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-3 | Specifying a subset
Google Fonts are automatically subset. This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while preload is true will result in a warning.
This can be done by adding it to the function call:... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-4 | subsets: ['latin'],
display: 'swap',
})
export const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
})
app/layout.tsx import { inter } from './fonts'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={inter.className}>
... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-5 | </>
)
}
In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed.
Alternatively, you can create a CSS variable and use it with your preferred CSS solution:
app/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google'
import styles from './global.css'
const ... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-6 | children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>
<h1>My App</h1>
<div>{children}</div>
</body>
</html>
)
}
app/global.css html {
font-family: var(--font-inter);
}
h1 {
font-family: var(-... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-7 | Local Fonts
Import next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility.
app/layout.tsx import localFont from 'next/font/local'
// Font files can be colocated inside of `app`
const myFont = localFont({
src: './my-font.woff2',
displ... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-8 | src: [
{
path: './Roboto-Regular.woff2',
weight: '400',
style: 'normal',
},
{
path: './Roboto-Italic.woff2',
weight: '400',
style: 'italic',
},
{
path: './Roboto-Bold.woff2',
weight: '700',
style: 'normal',
},
{
path: './Roboto-Bold... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-9 | With Tailwind CSS
next/font can be used with Tailwind CSS through a CSS variable.
In the example below, we use the font Inter from next/font/google (you can use any font from Google or Local Fonts). Load your font with the variable option to define your CSS variable name and assign it to inter. Then, use inter.variable... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-10 | children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>{children}</body>
</html>
)
}
Finally, add the CSS variable to your Tailwind CSS config:
tailwind.config.js /** @type {import('tailwindcss').Config} */
module.exports... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-11 | },
},
},
plugins: [],
}
You can now use the font-sans and font-mono utility classes to apply the font to your elements.
Preloading
When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on th... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
b364d2bb158f-12 | If it's the root layout, it is preloaded on all routes.
Reusing fonts
Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it... | https://nextjs.org/docs/app/building-your-application/optimizing/fonts |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
179de4cdf8e7-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 |
1c744ec49e18-0 | Image Optimization
Examples
Image Component
According to Web Almanac, images account for a huge portion of the typical website’s page weight and can have a sizable impact on your website's LCP performance.
The Next.js Image component extends the HTML <img> element with features for automatic image optimization:
Size Op... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-1 | You can then define the src for your image (either local or remote).
Local Images
To use a local image, import your .jpg, .png, or .webp image files.
Next.js will automatically determine the width and height of your image based on the imported file. These values are used to prevent Cumulative Layout Shift while your im... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-2 | />
)
}
Warning: Dynamic await import() or require() are not supported. The import must be static so it can be analyzed at build time.
Remote Images
To use a remote image, the src property should be a URL string.
Since Next.js does not have access to remote files during the build process, you'll need to provide the wi... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-3 | width={500}
height={500}
/>
)
}
To safely allow optimizing images, define a list of supported URL patterns in next.config.js. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
next.config.js module.exports = ... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-4 | Domains
Sometimes you may want to optimize a remote image, but still use the built-in Next.js Image Optimization API. To do this, leave the loader at its default setting and enter an absolute URL for the Image src prop.
To protect your application from malicious users, you must define a list of remote hostnames you int... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-5 | The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can write your own loader function with a few ... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-6 | The LCP element is typically the largest image or text block visible within the viewport of the page. When you run next dev, you'll see a console warning if the LCP element is an <Image> without the priority property.
Once you've identified the LCP image, you can add the property like this:
app/page.js import Image fro... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-7 | }
See more about priority in the next/image component documentation.
Image Sizing
One of the ways that images most commonly hurt performance is through layout shift, where the image pushes other elements around on the page as it loads in. This performance problem is so annoying to users that it has its own Core Web Vit... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-8 | What if I don't know the size of my images?
If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do:
Use fill
The fill prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along siz... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-9 | If none of the suggested methods works for sizing your images, the next/image component is designed to work well on a page alongside standard <img> elements.
Styling
Styling the Image component is similar to styling a normal <img> element, but there are a few guidelines to keep in mind:
Use className or style, not styl... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-10 | This is the default for <div> elements but should be specified otherwise.
Examples
Responsive
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
export default function Responsive() {
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<Image
alt="Mount... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-11 | export default function Fill() {
return (
<div
style={{
display: 'grid',
gridGap: '8px',
gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))',
}}
>
<div style={{ position: 'relative', height: '400px' }}>
<Image
alt="Mountains"
src={... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
1c744ec49e18-12 | import mountains from '../public/mountains.jpg'
export default function Background() {
return (
<Image
alt="Mountains"
src={mountains}
placeholder="blur"
quality={100}
fill
sizes="100vw"
style={{
objectFit: 'cover',
}}
/>
)
}
For examples of the Imag... | https://nextjs.org/docs/app/building-your-application/optimizing/images |
4f30ee94c4e0-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
42493c7a2a84-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 |
cc527b0f003e-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 |
cc527b0f003e-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 |
cc527b0f003e-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
eac3a347c199-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 |
c2b0814c7899-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 |
c2b0814c7899-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 |
afafaf626521-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 |
afafaf626521-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 |
afafaf626521-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
995e7d9188a8-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 |
f12ff3537783-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.