text stringlengths 49 1.09k | source stringclasses 119
values | id stringlengths 14 15 |
|---|---|---|
experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig)For custom advanced configuration of Next.js, you can create a next.config.js or next.config.mjs file in the root of your project directory (next to package.json).next.config.js is a regular Node.js module, not a JSON file. It gets used by th... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-1 |
*/
const nextConfig = {
/* config options here */
}
export default nextConfigYou can also use a function:next.config.mjs module.exports = (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig
}Since Next.js 12.... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-2 |
/* config options here */
}
return nextConfig
}phase is the current context in which the configuration is loaded. You can see the available phases. Phases can be imported from next/constants: const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
module.exports = (phase, { defaultConfig }) => {
if (phas... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-3 |
return {
/* config options for all phases except development here */
}
}The commented lines are the place where you can put the configs allowed by next.config.js, which are defined in this file.However, none of the configs are required, and it's not necessary to understand what each config does. Instead, search f... | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions | daf4598d9612-4 |
assetPrefix
Attention: Deploying to Vercel automatically configures a global CDN for your Next.js project.
You do not need to manually setup an Asset Prefix.
Good to know: Next.js 9.5+ added support for a customizable Base Path, which is better
suited for hosting your application on a sub-path like /docs.
We do not sug... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix | 0275274bbb87-0 |
}
Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the /_next/ path (.next/static/ folder). For example, with the above configuration, the following request for a JS chunk:
/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js
Would instead... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix | 0275274bbb87-1 |
The exact configuration for uploading your files to a given CDN will depend on your CDN of choice. The only folder you need to host on your CDN is the contents of .next/static/, which should be uploaded as _next/static/ as the above URL request indicates. Do not upload the rest of your .next/ folder, as you should not ... | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix | 0275274bbb87-2 |
typedRoutes (experimental)Experimental support for statically typed links. This feature requires using the App Router as well as TypeScript in your project.
next.config.js /** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
typedRoutes: true,
},
}
module.exports = nextConfig | https://nextjs.org/docs/app/api-reference/next-config-js/typedRoutes | 9b242da05360-0 |
env
Since the release of Next.js 9.4 we now have a more intuitive and ergonomic experience for adding environment variables. Give it a try!
Examples
With env
Good to know: environment variables specified in this way will always be included in the JavaScript bundle, prefixing the environment variable name with NEXT_PUBL... | https://nextjs.org/docs/app/api-reference/next-config-js/env | 6bc02063a97a-0 |
}
export default Page
Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.
For example, the following line:
return <h1>The value of customKey is: {process.env.customKey}</h1>
Will end up being:
ret... | https://nextjs.org/docs/app/api-reference/next-config-js/env | 6bc02063a97a-1 |
webVitalsAttribution
When debugging issues related to Web Vitals, it is often helpful if we can pinpoint the source of the problem.
For example, in the case of Cumulative Layout Shift (CLS), we might want to know the first element that shifted when the single largest layout shift occurred.
Or, in the case of Largest Co... | https://nextjs.org/docs/app/api-reference/next-config-js/webVitalsAttribution | 054c63ce89eb-0 |
next.config.js experimental: {
webVitalsAttribution: ['CLS', 'LCP']
}
Valid attribution values are all web-vitals metrics specified in the NextWebVitalsMetric type. | https://nextjs.org/docs/app/api-reference/next-config-js/webVitalsAttribution | 054c63ce89eb-1 |
exportPathMap (Deprecated)
This feature is exclusive to next export and currently deprecated in favor of getStaticPaths with pages or generateStaticParams with app.
Examples
Static Export
exportPathMap allows you to specify a mapping of request paths to page destinations, to be used during export. Paths defined in expo... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap | 8140bc719030-0 |
'/about': { page: '/about' },
'/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } },
'/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } },
'/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } },
}
},
}
Good to know: the query field in exportPa... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap | 8140bc719030-1 |
exportPathMap is an async function that receives 2 arguments: the first one is defaultPathMap, which is the default map used by Next.js. The second argument is an object with:
dev - true when exportPathMap is being called in development. false when running next export. In development exportPathMap is used to define rou... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap | 8140bc719030-2 |
page: String - the page inside the pages directory to render
query: Object - the query object passed to getInitialProps when prerendering. Defaults to {}
The exported pathname can also be a filename (for example, /readme.md), but you may need to set the Content-Type header to text/html when serving its content if it is... | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap | 8140bc719030-3 |
Terminal next export -o outdir
Warning: Using exportPathMap is deprecated and is overridden by getStaticPaths inside pages. We don't recommend using them together. | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap | 8140bc719030-4 |
images
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure next.config.js with the following:
next.config.js module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
This loaderFile must point t... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-0 |
Contentful
Fastly
Gumlet
ImageEngine
Imgix
Thumbor
Supabase
Akamai
// Docs: https://techdocs.akamai.com/ivm/reference/test-images-on-demand
export default function akamaiLoader({ src, width, quality }) {
return `https://example.com/${src}?imwidth=${width}`
}
Cloudinary
// Demo: https://res.cloudinary.com/demo/image... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-1 |
export default function cloudflareLoader({ src, width, quality }) {
const params = [`width=${width}`, `quality=${quality || 75}`, 'format=auto']
return `https://example.com/cdn-cgi/image/${params.join(',')}/${src}`
}
Contentful
// Docs: https://www.contentful.com/developers/docs/references/images-api/
export defau... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-2 |
export default function fastlyLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('auto', 'webp')
url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
}
Gumlet
// Docs: https://docs.guml... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-3 |
return url.href
}
ImageEngine
// Docs: https://support.imageengine.io/hc/en-us/articles/360058880672-Directives
export default function imageengineLoader({ src, width, quality }) {
const compression = 100 - (quality || 50)
const params = [`w_${width}`, `cmpr_${compression}`)]
return `https://example.com${src}?im... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-4 |
params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
params.set('q', (quality || 50).toString())
return url.href
}
Thumbor
// Docs: https://thumbor.readthedocs.io/en/latest/
export default function thumborLoader({ src, width, quality }) {
const params = [`${width}x... | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-5 |
url.searchParams.set('width', width.toString())
url.searchParams.set('quality', (quality || 75).toString())
return url.href
} | https://nextjs.org/docs/app/api-reference/next-config-js/images | 12ee2679474c-6 |
headers
Headers allow you to set custom HTTP headers on the response to an incoming request on a given path.
To set custom HTTP headers you can use the headers key in next.config.js:
next.config.js module.exports = {
async headers() {
return [
{
source: '/about',
headers: [
{
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-0 |
headers is an array of response header objects, with key and value properties.
basePath: false or undefined - if false the basePath won't be included when matching, can be used for external rewrites only.
locale: false or undefined - whether the locale should not be included when matching.
has is an array of has object... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-1 |
return [
{
source: '/:path*',
headers: [
{
key: 'x-hello',
value: 'there',
},
],
},
{
source: '/hello',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-2 |
},
{
key: 'x-slug-:slug', // Matched parameters can be used in the key
value: 'my other custom header value',
},
],
},
]
},
}
Wildcard Path Matching
To match a wildcard path you can use * after a parameter, for example /blog/:slug* will match /blog/a/b/c/d... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-3 |
value: 'my other custom header value',
},
],
},
]
},
}
Regex Path Matching
To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\\d{1,}) will match /blog/123 but not /blog/abc:
next.config.js module.exports = {
async headers() {
retur... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-4 |
next.config.js module.exports = {
async headers() {
return [
{
// this will match `/english(default)/something` being requested
source: '/english\\(default\\)/:slug',
headers: [
{
key: 'x-header',
value: 'value',
},
],
},
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-5 |
key: String - the key from the selected type to match against.
value: String or undefined - the value to check for, if undefined any value will match. A regex like string can be used to capture a specific part of the value, e.g. if the value first-(?<paramName>.*) is used for first-second then second will be usable in ... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-6 |
value: 'hello',
},
],
},
// if the header `x-no-header` is not present,
// the `x-another-header` header will be applied
{
source: '/:path*',
missing: [
{
type: 'header',
key: 'x-no-header',
},
],
heade... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-7 |
key: 'page',
// the page value will not be available in the
// header key/values since value is provided and
// doesn't use a named capture group e.g. (?<page>home)
value: 'home',
},
{
type: 'cookie',
key: 'authorized',
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-8 |
{
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
// if the host is `example.com`,
// this... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-9 |
],
},
]
},
}
Headers with basePath support
When leveraging basePath support with headers each source is automatically prefixed with the basePath unless you add basePath: false to the header:
next.config.js module.exports = {
basePath: '/docs',
async headers() {
return [
{
source: '/w... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-10 |
},
]
},
}
Headers with i18n support
When leveraging i18n support with headers each source is automatically prefixed to handle the configured locales unless you add locale: false to the header. If locale: false is used you must prefix the source with a locale for it to be matched correctly.
next.config.js module.e... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-11 |
source: '/nl/with-locale-manual',
locale: false,
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// this matches '/' since `en` is the defaultLocale
source: '/en',
locale: false,
headers: [
... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-12 |
value: 'world',
},
],
},
]
},
}
Cache-Control
You can set the Cache-Control header in your Next.js API Routes by using the res.setHeader method:
pages/api/user.js export default function handler(req, res) {
res.setHeader('Cache-Control', 's-maxage=86400')
res.status(200).json({ name: '... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-13 |
Options
X-DNS-Prefetch-Control
This header controls DNS prefetching, allowing browsers to proactively perform domain name resolution on external links, images, CSS, JavaScript, and more. This prefetching is performed in the background, so the DNS is more likely to be resolved by the time the referenced items are needed... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-14 |
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
}
X-XSS-Protection
This header stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although this protection is not necessary when sites implement a strong Content-Security-Policy disabling t... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-15 |
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
}
Permissions-Policy
This header allows you to control which features and APIs can be used in the browser. It was previously named Feature-Policy. You can view the full list of permission options here.
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), ... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-16 |
{
key: 'X-Content-Type-Options',
value: 'nosniff'
}
Referrer-Policy
This header controls how much information the browser includes when navigating from the current website (origin) to another. You can read about the different options here.
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin'
}
Content-S... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-17 |
// add Content Security Policy directives using a template string.
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self';
child-src example.com;
style-src 'self' example.com;
font-src 'self';
`
When a directive uses a keyword such as self, wrap it in single quotes ''.
In the header's value, ... | https://nextjs.org/docs/app/api-reference/next-config-js/headers | 89f24c8b1b7d-18 |
reactStrictMode
Good to know: Since Next.js 13.4, Strict Mode is true by default with app router, so the above configuration is only necessary for pages. You can still disable Strict Mode by setting reactStrictMode: false.
Suggested: We strongly suggest you enable Strict Mode in your Next.js application to better prepa... | https://nextjs.org/docs/app/api-reference/next-config-js/reactStrictMode | 34ed950790bd-0 |
next.config.js module.exports = {
reactStrictMode: true,
}
If you or your team are not ready to use Strict Mode in your entire application, that's OK! You can incrementally migrate on a page-by-page basis using <React.StrictMode>. | https://nextjs.org/docs/app/api-reference/next-config-js/reactStrictMode | 34ed950790bd-1 |
turbo (Experimental)
Warning: These features are experimental and will only work with next --turbo.
webpack loaders
Currently, Turbopack supports a subset of webpack's loader API, allowing you to use some webpack loaders to transform code in Turbopack.
To configure loaders, add the names of the loaders you've installed... | https://nextjs.org/docs/app/api-reference/next-config-js/turbo | 86bb463b5996-0 |
},
},
},
}
Then, given the above configuration, you can use transformed code from your app:
import MyDoc from './my-doc.mdx'
export default function Home() {
return <MyDoc />
}
Resolve Alias
Through next.config.js, Turbopack can be configured to modify module resolution through aliases, similar to webpack's ... | https://nextjs.org/docs/app/api-reference/next-config-js/turbo | 86bb463b5996-1 |
Turbopack also supports conditional aliasing through this field, similar to Node.js's conditional exports. At the moment only the browser condition is supported. In the case above, imports of the mocha module will be aliased to mocha/browser-entry.js when Turbopack targets browser environments.
For more information and... | https://nextjs.org/docs/app/api-reference/next-config-js/turbo | 86bb463b5996-2 |
Custom Webpack Config
Good to know: changes to webpack config are not covered by semver so proceed at your own risk
Before continuing to add custom webpack configuration to your application make sure Next.js doesn't already support your use-case:
CSS imports
CSS modules
Sass/SCSS imports
Sass/SCSS modules
preact
Some c... | https://nextjs.org/docs/app/api-reference/next-config-js/webpack | ef8ef9ecea5a-0 |
// Important: return the modified config
return config
},
}
The webpack function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using the isServer property.
The second argument to the webpack function is an object with the fol... | https://nextjs.org/docs/app/api-reference/next-config-js/webpack | ef8ef9ecea5a-1 |
// Example config for adding a loader that depends on babel-loader
// This source was taken from the @next/mdx plugin source:
// https://github.com/vercel/next.js/tree/canary/packages/next-mdx
module.exports = {
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx/,
use: [
o... | https://nextjs.org/docs/app/api-reference/next-config-js/webpack | ef8ef9ecea5a-2 |
distDir
You can specify a name to use for a custom build directory to use instead of .next.
Open next.config.js and add the distDir config:
next.config.js module.exports = {
distDir: 'build',
}
Now if you run next build Next.js will use build instead of the default .next folder.
distDir should not leave your project ... | https://nextjs.org/docs/app/api-reference/next-config-js/distDir | 9166b053416d-0 |
typescript
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... | https://nextjs.org/docs/app/api-reference/next-config-js/typescript | 4e2509984d97-0 |
productionBrowserSourceMaps
Source Maps are enabled by default during development. During production builds, they are disabled to prevent you leaking your source on the client, unless you specifically opt-in with the configuration flag.
Next.js provides a configuration flag you can use to enable browser source map gene... | https://nextjs.org/docs/app/api-reference/next-config-js/productionBrowserSourceMaps | d09c45d2bfb0-0 |
trailingSlash
By default Next.js will redirect urls with trailing slashes to their counterpart without a trailing slash. For example /about/ will redirect to /about. You can configure this behavior to act the opposite way, where urls without trailing slashes are redirected to their counterparts with trailing slashes.
O... | https://nextjs.org/docs/app/api-reference/next-config-js/trailingSlash | 269a12fa2491-0 |
urlImports
URL imports are an experimental feature that allows you to import modules directly from external servers (instead of from the local disk).
Warning: This feature is experimental. Only use domains that you trust to download and execute on your machine. Please exercise
discretion, and caution until the feature ... | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports | 6a18e8fea07b-0 |
URL Imports can be used everywhere normal package imports can be used.
Security Model
This feature is being designed with security as the top priority. To start, we added an experimental flag forcing you to explicitly allow the domains you accept URL imports from. We're working to take this further by limiting URL impo... | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports | 6a18e8fea07b-1 |
One exception is resources that respond with Cache-Control: no-cache.
These resources will have a no-cache entry in the lockfile and will always be fetched from the network on each build.
Examples
Skypack
import confetti from 'https://cdn.skypack.dev/canvas-confetti'
import { useEffect } from 'react'
export default ... | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports | 6a18e8fea07b-2 |
background: url('https://example.com/assets/hero.jpg');
}
Asset Imports
const logo = new URL('https://example.com/assets/file.txt', import.meta.url)
console.log(logo.pathname)
// prints "/_next/static/media/file.a9727b5d.txt" | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports | 6a18e8fea07b-3 |
mdxRsFor use with @next/mdx. Compile MDX files using the new Rust compiler.
next.config.js const withMDX = require('@next/mdx')()
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['ts', 'tsx', 'mdx'],
experimental: {
mdxRs: true,
},
}
module.exports = withMDX(nextConfig) | https://nextjs.org/docs/app/api-reference/next-config-js/mdxRs | 6dfb4be7fb03-0 |
devIndicators
When you edit your code, and Next.js is compiling the application, a compilation indicator appears in the bottom right corner of the page.
Good to know: This indicator is only present in development mode and will not appear when building and running the app in production mode.
In some cases this indicator... | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators | 5aecac7471a5-0 |
devIndicators: {
buildActivity: false,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators | 5aecac7471a5-1 |
poweredByHeader
By default Next.js will add the x-powered-by header. To opt-out of it, open next.config.js and disable the poweredByHeader config:
next.config.js module.exports = {
poweredByHeader: false,
} | https://nextjs.org/docs/app/api-reference/next-config-js/poweredByHeader | 94f374952b00-0 |
onDemandEntries
Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development.
To change the defaults, open next.config.js and add the onDemandEntries config:
next.config.js module.exports = {
onDemandEntries: {
// period (in ms) where the se... | https://nextjs.org/docs/app/api-reference/next-config-js/onDemandEntries | 2bd7c01d5523-0 |
<Script>
This API reference will help you understand how to use props available for the Script Component. For features and usage, please see the Optimizing Scripts page.
app/dashboard/page.tsx import Script from 'next/script'
export default function Dashboard() {
return (
<>
<Script src="https://example.c... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-0 |
Required Props
The <Script /> component requires the following properties.
src
A path string specifying the URL of an external script. This can be either an absolute external URL or an internal path. The src property is required unless an inline script is used.
Optional Props
The <Script /> component accepts a number o... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-1 |
Scripts denoted with this strategy are preloaded and fetched before any first-party code, but their execution does not block page hydration from occurring.
beforeInteractive scripts must be placed inside the root layout (app/layout.tsx) and are designed to load scripts that are needed by the entire site (i.e. the scrip... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-2 |
strategy="beforeInteractive"
/>
</html>
)
}
Good to know: Scripts with beforeInteractive will always be injected inside the head of the HTML document regardless of where it's placed in the component.
Some examples of scripts that should be loaded as soon as possible with beforeInteractive include:
Bot detec... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-3 |
export default function Page() {
return (
<>
<Script src="https://example.com/script.js" strategy="afterInteractive" />
</>
)
}
Some examples of scripts that are good candidates for afterInteractive include:
Tag managers
Analytics
lazyOnload
Scripts that use the lazyOnload strategy are injected into t... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-4 |
export default function Page() {
return (
<>
<Script src="https://example.com/script.js" strategy="lazyOnload" />
</>
)
}
Examples of scripts that do not need to load immediately and can be fetched with lazyOnload include:
Chat support plugins
Social media widgets
worker
Warning: The worker strategy i... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-5 |
next.config.js module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
worker scripts can only currently be used in the pages/ directory:
pages/home.tsx import Script from 'next/script'
export default function Home() {
return (
<>
<Script src="https://example.com/script.js" strategy="work... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-6 |
Here's an example of executing a lodash method only after the library has been loaded.
app/page.tsx 'use client'
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
onLoad={() =... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-7 |
Some third-party scripts require users to run JavaScript code after the script has finished loading and every time the component is mounted (after a route navigation for example). You can execute code after the script's load event when it first loads and then after every subsequent component re-mount using the onReady ... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-8 |
onReady={() => {
new google.maps.Map(mapRef.current, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
})
}}
/>
</>
)
}
onError
Warning: onError does not yet work with Server Components and can only be used in Client Components. onError cannot be used wit... | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-9 |
console.error('Script failed to load', e)
}}
/>
</>
)
}
Version History
VersionChangesv13.0.0beforeInteractive and afterInteractive is modified to support app.v12.2.4onReady prop added.v12.2.2Allow next/script with beforeInteractive to be placed in _document.v11.0.0next/script introduced. | https://nextjs.org/docs/app/api-reference/components/script | fa6dfa5159d0-10 |
<Image>
Examples
Image Component
This API reference will help you understand how to use props and configuration options available for the Image Component. For features and usage, please see the Image Component page.
app/page.js import Image from 'next/image'
export default function Page() {
return (
<Image
... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-0 |
}
Props
Here's a summary of the props available for the Image Component:
PropExampleTypeRequiredsrcsrc="/profile.png"StringYeswidthwidth={500}Integer (px)Yesheightheight={500}Integer (px)Yesaltalt="Picture of the author"StringYesloaderloader={imageLoader}Function-fillfill={true}Boolean-sizessizes="(max-width: 768px) 10... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-1 |
The Image Component requires the following properties: src, width, height, and alt.
app/page.js import Image from 'next/image'
export default function Page() {
return (
<div>
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-2 |
Required, except for statically imported images or images with the fill property.
height
The height property represents the rendered height in pixels, so it will affect how large the image appears.
Required, except for statically imported images or images with the fill property.
alt
The alt property is used to describe... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-3 |
Learn more
Optional Props
The <Image /> component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the Advanced Props section.
loader
A custom function used to res... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-4 |
alt="Picture of the author"
width={500}
height={500}
/>
)
}
Good to know: Using props like loader, which accept a function, require using Client Components to serialize the provided function.
Alternatively, you can use the loaderFile configuration in next.config.js to configure every instance of next/... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-5 |
By default, the img element will automatically be assigned the position: "absolute" style.
The default image fit behavior will stretch the image to fit the container. You may prefer to set object-fit: "contain" for an image which is letterboxed to fit the container and preserve aspect ratio.
Alternatively, object-fit: ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-6 |
The sizes property serves two important purposes related to image performance:
First, the value of sizes is used by the browser to determine which size of the image to download, from next/image's automatically-generated source set. When the browser chooses, it does not yet know the size of the image on the page, so it ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-7 |
Second, the sizes property configures how next/image automatically generates an image source set. If no sizes value is present, a small source set is generated, suitable for a fixed-size image. If sizes is defined, a large source set is generated, suitable for a responsive image. If the sizes property includes sizes su... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-8 |
<Image
fill
src="/example.png"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
)
}
This example sizes could have a dramatic effect on performance metrics. Without the 33vw sizes, the image selected from the server would be 3 times as wide as it needs to be.... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-9 |
priority
priority={false} // {false} | {true}
When true, the image will be considered high priority and
preload. Lazy loading is automatically disabled for images using priority.
You should use the priority property on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have mult... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-10 |
For dynamic images, you must provide the blurDataURL property. Solutions such as Plaiceholder can help with base64 generation.
When empty, there will be no placeholder while the image is loading, only empty space.
Try it out:
Demo the blur placeholder
Demo the shimmer effect with blurDataURL prop
Demo the color effect ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-11 |
return <Image src="..." style={imageStyle} />
}
Remember that the required width and height props can interact with your styling. If you use styling to modify an image's width, you should also style its height to auto to preserve its intrinsic aspect ratio, or your image will be distorted.
onLoadingComplete
'use clien... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-12 |
A callback function that is invoked when the image is loaded.
The load event might occur before the image placeholder is removed and the image is fully decoded. If you want to wait until the image has fully loaded, use onLoadingComplete instead.
Good to know: Using props like onLoad, which accept a function, require us... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-13 |
loading = 'lazy' // {lazy} | {eager}
The loading behavior of the image. Defaults to lazy.
When lazy, defer loading the image until it reaches a calculated distance from
the viewport.
When eager, load the image immediately.
Learn more about the loading attribute.
blurDataURL
A Data URL to
be used as a placeholder image ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-14 |
You can also generate a solid color Data URL to match the image.
unoptimized
unoptimized = {false} // {false} | {true}
When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to false.
import Image from 'next/image'
const UnoptimizedImage = (props) => {
return <Imag... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-15 |
decoding. It is always "async".
Configuration Options
In addition to props, you can configure the Image Component in next.config.js. The following options are available:
remotePatterns
To protect your application from malicious users, configuration is required in order to use external images. This ensures that only ext... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-16 |
pathname: '/account123/**',
},
],
},
}
Good to know: The example above will ensure the src property of next/image must start with https://example.com/account123/. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request.
Below is another example of the remotePatterns property ... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-17 |
Wildcard patterns can be used for both pathname and hostname and have the following syntax:
* match a single path segment or subdomain
** match any number of path segments at the end or subdomains at the beginning
The ** syntax does not work in the middle of the pattern.
domains
Warning: We recommend configuring strict... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-18 |
domains: ['assets.acme.com'],
},
}
loaderFile
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the loaderFile in your next.config.js like the following:
next.config.js module.exports = {
images: {
loader: 'custom',
loaderF... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-19 |
Examples:
Custom Image Loader Configuration
Good to know: Customizing the image loader file, which accepts a function, require using Client Components to serialize the provided function.
Advanced
The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the propertie... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-20 |
},
}
imageSizes
You can specify a list of image widths using the images.imageSizes property in your next.config.js file. These widths are concatenated with the array of device sizes to form the full array of sizes used to generate image srcsets.
The reason there are two separate lists is that imageSizes is only used fo... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-21 |
If the Accept head matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match (or the source image is animated), the Image Optimization API will fallback to the original image's format.
If no configuration is provided, the default belo... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-22 |
If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the Accept header.
Caching Behavior
The following describes the caching algorithm for the default loader. For all other loaders, please refer to your cloud provider's documentation.
Images are optimized dynamically upon reque... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-23 |
STALE - the path is in the cache but exceeded the revalidate time so it will be updated in the background
HIT - the path is in the cache and has not exceeded the revalidate time
The expiration (or rather Max Age) is defined by either the minimumCacheTTL configuration or the upstream image Cache-Control header, whicheve... | https://nextjs.org/docs/app/api-reference/components/image | 2de7a5cca900-24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.