id
stringlengths 14
15
| text
stringlengths 49
1.09k
| source
stringlengths 38
101
|
---|---|---|
daf4598d9612-1 | 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 the Next.js server and build phases, and it's not included in the browser build.Take a look at the following next.config.js example:next.config.js /**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
module.exports = nextConfigIf you need ECMAScript modules, you can use next.config.mjs:next.config.mjs /**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */ | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
daf4598d9612-2 | */
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.1.0, you can use an async function:next.config.js module.exports = async (phase, { defaultConfig }) => {
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
return nextConfig | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
daf4598d9612-3 | /* 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 (phase === PHASE_DEVELOPMENT_SERVER) {
return {
/* development only config options here */
}
}
return {
/* config options for all phases except development here */
} | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
daf4598d9612-4 | 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 for the features you need to enable or modify in this section and they will show you what to do.
Avoid using new JavaScript features not available in your target Node.js version. next.config.js will not be parsed by Webpack, Babel or TypeScript. | https://nextjs.org/docs/app/api-reference/next-config-js/pageExtensions |
0275274bbb87-0 | 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 suggest you use a custom Asset Prefix for this use case.
To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on.
Open next.config.js and add the assetPrefix config:
next.config.js const isProd = process.env.NODE_ENV === 'production'
module.exports = {
// Use the CDN in production and localhost for development.
assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined,
} | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
0275274bbb87-1 | }
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 become:
https://cdn.mydomain.com/_next/static/chunks/4b9b41aaa062cbbfeff4add70f256968c51ece5d.4d708494b3aed70c04f0.js | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
0275274bbb87-2 | 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 expose your server code and other configuration to the public.
While assetPrefix covers requests to _next/static, it does not influence the following paths:
Files in the public folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself | https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix |
9b242da05360-0 | 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 |
6bc02063a97a-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_PUBLIC_ only has an effect when specifying them through the environment or .env files.
To add environment variables to the JavaScript bundle, open next.config.js and add the env config:
next.config.js module.exports = {
env: {
customKey: 'my-value',
},
}
Now you can access process.env.customKey in your code. For example:
function Page() {
return <h1>The value of customKey is: {process.env.customKey}</h1>
}
export default Page | https://nextjs.org/docs/app/api-reference/next-config-js/env |
6bc02063a97a-1 | }
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:
return <h1>The value of customKey is: {'my-value'}</h1> | https://nextjs.org/docs/app/api-reference/next-config-js/env |
054c63ce89eb-0 | 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 Contentful Paint (LCP), we might want to identify the element corresponding to the LCP for the page.
If the LCP element is an image, knowing the URL of the image resource can help us locate the asset we need to optimize.
Pinpointing the biggest contributor to the Web Vitals score, aka attribution,
allows us to obtain more in-depth information like entries for PerformanceEventTiming, PerformanceNavigationTiming and PerformanceResourceTiming.
Attribution is disabled by default in Next.js but can be enabled per metric by specifying the following in next.config.js.
next.config.js experimental: { | https://nextjs.org/docs/app/api-reference/next-config-js/webVitalsAttribution |
054c63ce89eb-1 | 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 |
8140bc719030-0 | 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 exportPathMap will also be available when using next dev.
Let's start with an example, to create a custom exportPathMap for an app with the following pages:
pages/index.js
pages/about.js
pages/post.js
Open next.config.js and add the following exportPathMap config:
next.config.js module.exports = {
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
'/about': { page: '/about' }, | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
8140bc719030-1 | '/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 exportPathMap cannot be used with automatically statically optimized pages or getStaticProps pages as they are rendered to HTML files at build-time and additional query information cannot be provided during next export.
The pages will then be exported as HTML files, for example, /about will become /about.html. | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
8140bc719030-2 | 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 routes.
dir - Absolute path to the project directory
outDir - Absolute path to the out/ directory (configurable with -o). When dev is true the value of outDir will be null.
distDir - Absolute path to the .next/ directory (configurable with the distDir config)
buildId - The generated build id
The returned object is a map of pages where the key is the pathname and the value is an object that accepts the following fields:
page: String - the page inside the pages directory to render | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
8140bc719030-3 | 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 different than .html.
Adding a trailing slash
It is possible to configure Next.js to export pages as index.html files and require trailing slashes, /about becomes /about/index.html and is routable via /about/. This was the default behavior prior to Next.js 9.
To switch back and add a trailing slash, open next.config.js and enable the trailingSlash config:
next.config.js module.exports = {
trailingSlash: true,
}
Customizing the output directory
next export will use out as the default output directory, you can customize this using the -o argument, like so: | https://nextjs.org/docs/app/api-reference/next-config-js/exportPathMap |
8140bc719030-4 | 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 |
12ee2679474c-0 | 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 to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example:
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
Alternatively, you can use the loader prop to pass the function to each instance of next/image.
Example Loader Configuration
Akamai
Cloudinary
Cloudflare
Contentful
Fastly
Gumlet
ImageEngine
Imgix
Thumbor | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-1 | 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/upload/w_300,c_limit,q_auto/turtles.jpg
export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
return `https://example.com/${params.join(',')}${src}`
}
Cloudflare
// Docs: https://developers.cloudflare.com/images/url-format
export default function cloudflareLoader({ src, width, quality }) { | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-2 | 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 default function contentfulLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('fm', 'webp')
url.searchParams.set('w', width.toString())
url.searchParams.set('q', (quality || 75).toString())
return url.href
}
Fastly
// Docs: https://developer.fastly.com/reference/io/
export default function fastlyLoader({ src, width, quality }) { | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-3 | 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.gumlet.com/reference/image-transform-size
export default function gumletLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('format', 'auto')
url.searchParams.set('w', width.toString())
url.searchParams.set('q', (quality || 75).toString())
return url.href
}
ImageEngine | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-4 | 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}?imgeng=/${params.join('/')`
}
Imgix
// Demo: https://static.imgix.net/daisy.png?format=auto&fit=max&w=300
export default function imgixLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
const params = url.searchParams
params.set('auto', params.getAll('auto').join(',') || 'format')
params.set('fit', params.get('fit') || 'max') | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-5 | 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}x0`, `filters:quality(${quality || 75})`]
return `https://example.com${params.join('/')}${src}`
}
Supabase
// Docs: https://supabase.com/docs/guides/storage/image-transformations#nextjs-loader
export default function supabaseLoader({ src, width, quality }) {
const url = new URL(`https://example.com${src}`)
url.searchParams.set('width', width.toString()) | https://nextjs.org/docs/app/api-reference/next-config-js/images |
12ee2679474c-6 | 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 |
89f24c8b1b7d-0 | 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: [
{
key: 'x-custom-header',
value: 'my custom header value',
},
{
key: 'x-another-custom-header',
value: 'my other custom header value',
},
],
},
]
},
}
headers is an async function that expects an array to be returned holding objects with source and headers properties:
source is the incoming request path pattern.
headers is an array of response header objects, with key and value properties. | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-1 | 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 objects with the type, key and value properties.
missing is an array of missing objects with the type, key and value properties.
Headers are checked before the filesystem which includes pages and /public files.
Header Overriding Behavior
If two headers match the same path and set the same header key, the last header key will override the first. Using the below headers, the path /hello will result in the header x-hello being world due to the last header value set being world.
next.config.js module.exports = {
async headers() {
return [
{
source: '/:path*', | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-2 | return [
{
source: '/:path*',
headers: [
{
key: 'x-hello',
value: 'there',
},
],
},
{
source: '/hello',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
]
},
}
Path Matching
Path matches are allowed, for example /blog/:slug will match /blog/hello-world (no nested paths):
next.config.js module.exports = {
async headers() {
return [
{
source: '/blog/:slug',
headers: [
{
key: 'x-slug',
value: ':slug', // Matched parameters can be used in the value
},
{ | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-3 | },
{
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/hello-world:
next.config.js module.exports = {
async headers() {
return [
{
source: '/blog/:slug*',
headers: [
{
key: 'x-slug',
value: ':slug*', // Matched parameters can be used in the value
},
{
key: 'x-slug-:slug*', // Matched parameters can be used in the key
value: 'my other custom header value',
}, | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-4 | 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() {
return [
{
source: '/blog/:post(\\d{1,})',
headers: [
{
key: 'x-post',
value: ':post',
},
],
},
]
},
}
The following characters (, ), {, }, :, *, +, ? are used for regex path matching, so when used in the source as non-special values they must be escaped by adding \\ before them: | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-5 | 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',
},
],
},
]
},
}
Header, Cookie, and Query Matching
To only apply a header when header, cookie, or query values also match the has field or don't match the missing field can be used. Both the source and all has items must match and all missing items must not match for the header to be applied.
has and missing items can have the following fields:
type: String - must be either header, cookie, host, or query.
key: String - the key from the selected type to match against. | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-6 | 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 the destination with :paramName.
next.config.js module.exports = {
async headers() {
return [
// if the header `x-add-header` is present,
// the `x-another-header` header will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-add-header',
},
],
headers: [
{
key: 'x-another-header',
value: 'hello',
},
], | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-7 | 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',
},
],
headers: [
{
key: 'x-another-header',
value: 'hello',
},
],
},
// if the source, query, and cookie are matched,
// the `x-authorized` header will be applied
{
source: '/specific/:path*',
has: [
{
type: 'query',
key: 'page',
// the page value will not be available in the | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-8 | 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',
value: 'true',
},
],
headers: [
{
key: 'x-authorized',
value: ':authorized',
},
],
},
// if the header `x-authorized` is present and
// contains a matching value, the `x-another-header` will be applied
{
source: '/:path*',
has: [
{
type: 'header',
key: 'x-authorized', | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-9 | {
type: 'header',
key: 'x-authorized',
value: '(?<authorized>yes|true)',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
// if the host is `example.com`,
// this header will be applied
{
source: '/:path*',
has: [
{
type: 'host',
value: 'example.com',
},
],
headers: [
{
key: 'x-another-header',
value: ':authorized',
},
],
},
]
},
}
Headers with basePath support | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-10 | ],
},
]
},
}
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: '/with-basePath', // becomes /docs/with-basePath
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
source: '/without-basePath', // is not modified since basePath: false is set
headers: [
{
key: 'x-hello',
value: 'world',
},
],
basePath: false,
},
]
},
}
Headers with i18n support | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-11 | },
]
},
}
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.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
async headers() {
return [
{
source: '/with-locale', // automatically handles all locales
headers: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// does not handle locales automatically since locale: false is set
source: '/nl/with-locale-manual', | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-12 | 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: [
{
key: 'x-hello',
value: 'world',
},
],
},
{
// this gets converted to /(en|fr|de)/(.*) so will not match the top-level
// `/` or `/fr` routes like /:path* would
source: '/(.*)',
headers: [
{
key: 'x-hello',
value: 'world',
},
],
}, | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-13 | 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: 'John Doe' })
}
You cannot set Cache-Control headers in next.config.js file as these will be overwritten in production to ensure that API Routes and static assets are cached effectively.
If you need to revalidate the cache of a page that has been statically generated, you can do so by setting the revalidate prop in the page's getStaticProps function.
Options
X-DNS-Prefetch-Control | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-14 | 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. This reduces latency when the user clicks a link.
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
}
Strict-Transport-Security
This header informs browsers it should only be accessed using HTTPS, instead of using HTTP. Using the configuration below, all present and future subdomains will use HTTPS for a max-age of 2 years. This blocks access to pages or subdomains that can only be served over HTTP.
If you're deploying to Vercel, this header is not necessary as it's automatically added to all deployments unless you declare headers in your next.config.js.
{ | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-15 | {
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 the use of inline JavaScript ('unsafe-inline'), it can still provide protection for older web browsers that don't support CSP.
{
key: 'X-XSS-Protection',
value: '1; mode=block'
}
X-Frame-Options
This header indicates whether the site should be allowed to be displayed within an iframe. This can prevent against clickjacking attacks. This header has been superseded by CSP's frame-ancestors option, which has better support in modern browsers.
{
key: 'X-Frame-Options', | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-16 | {
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=(), geolocation=(), browsing-topics=()'
}
X-Content-Type-Options
This header prevents the browser from attempting to guess the type of content if the Content-Type header is not explicitly set. This can prevent XSS exploits for websites that allow users to upload and share files. For example, a user trying to download an image, but having it treated as a different Content-Type like an executable, which could be malicious. This header also applies to downloading browser extensions. The only valid value for this header is nosniff.
{ | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-17 | {
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-Security-Policy
This header helps prevent cross-site scripting (XSS), clickjacking and other code injection attacks. Content Security Policy (CSP) can specify allowed origins for content including scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more.
You can read about the many different CSP options here.
You can add Content Security Policy directives using a template string.
// Before defining your Security Headers
// add Content Security Policy directives using a template string. | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
89f24c8b1b7d-18 | // 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, replace the new line with a space.
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
}
Version History
VersionChangesv13.3.0missing added.v10.2.0has added.v9.5.0Headers added. | https://nextjs.org/docs/app/api-reference/next-config-js/headers |
34ed950790bd-0 | 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 prepare your application for the future of React.
React's Strict Mode is a development mode only feature for highlighting potential problems in an application. It helps to identify unsafe lifecycles, legacy API usage, and a number of other features.
The Next.js runtime is Strict Mode-compliant. To opt-in to Strict Mode, configure the following option in your next.config.js:
next.config.js module.exports = {
reactStrictMode: true,
} | https://nextjs.org/docs/app/api-reference/next-config-js/reactStrictMode |
34ed950790bd-1 | 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 |
86bb463b5996-0 | 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 and any options in next.config.js, mapping file extensions to a list of loaders:
next.config.js module.exports = {
experimental: {
turbo: {
loaders: {
// Option format
'.md': [
{
loader: '@mdx-js/loader',
options: {
format: 'md',
},
},
],
// Option-less format
'.mdx': ['@mdx-js/loader'],
},
},
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/turbo |
86bb463b5996-1 | },
},
},
}
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 resolve.alias configuration.
To configure resolve aliases, map imported patterns to their new destination in next.config.js:
next.config.js module.exports = {
experimental: {
turbo: {
resolveAlias: {
underscore: 'lodash',
mocha: { browser: 'mocha/browser-entry.js' },
},
},
},
}
This aliases imports of the underscore package to the lodash package. In other words, import underscore from 'underscore' will load the lodash module instead of underscore. | https://nextjs.org/docs/app/api-reference/next-config-js/turbo |
86bb463b5996-2 | 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 guidance for how to migrate your app to Turbopack from webpack, see Turbopack's documentation on webpack compatibility. | https://nextjs.org/docs/app/api-reference/next-config-js/turbo |
ef8ef9ecea5a-0 | 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 commonly asked for features are available as plugins:
@next/mdx
@next/bundle-analyzer
In order to extend our usage of webpack, you can define a function that extends its config inside next.config.js, like so:
next.config.js module.exports = {
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
// Important: return the modified config
return config
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/webpack |
ef8ef9ecea5a-1 | // 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 following properties:
buildId: String - The build id, used as a unique identifier between builds
dev: Boolean - Indicates if the compilation will be done in development
isServer: Boolean - It's true for server-side compilation, and false for client-side compilation
nextRuntime: String | undefined - The target runtime for server-side compilation; either "edge" or "nodejs", it's undefined for client-side compilation.
defaultLoaders: Object - Default loaders used internally by Next.js:
babel: Object - Default babel-loader configuration
Example usage of defaultLoaders.babel:
// Example config for adding a loader that depends on babel-loader | https://nextjs.org/docs/app/api-reference/next-config-js/webpack |
ef8ef9ecea5a-2 | // 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: [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: pluginOptions.options,
},
],
})
return config
},
}
nextRuntime
Notice that isServer is true when nextRuntime is "edge" or "nodejs", nextRuntime "edge" is currently for middleware and Server Components in edge runtime only. | https://nextjs.org/docs/app/api-reference/next-config-js/webpack |
9166b053416d-0 | 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 directory. For example, ../build is an invalid directory. | https://nextjs.org/docs/app/api-reference/next-config-js/distDir |
4e2509984d97-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 your build or deploy process, otherwise this can be very dangerous.
Open next.config.js and enable the ignoreBuildErrors option in the typescript config:
next.config.js module.exports = {
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete even if
// your project has type errors.
// !! WARN !!
ignoreBuildErrors: true,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/typescript |
d09c45d2bfb0-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 generation during the production build:
next.config.js module.exports = {
productionBrowserSourceMaps: true,
}
When the productionBrowserSourceMaps option is enabled, the source maps will be output in the same directory as the JavaScript files. Next.js will automatically serve these files when requested.
Adding source maps can increase next build time
Increases memory usage during next build | https://nextjs.org/docs/app/api-reference/next-config-js/productionBrowserSourceMaps |
269a12fa2491-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.
Open next.config.js and add the trailingSlash config:
next.config.js module.exports = {
trailingSlash: true,
}
With this option set, urls like /about will redirect to /about/.
Version History
VersionChangesv9.5.0trailingSlash added. | https://nextjs.org/docs/app/api-reference/next-config-js/trailingSlash |
6a18e8fea07b-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 is flagged as stable.
To opt-in, add the allowed URL prefixes inside next.config.js:
next.config.js module.exports = {
experimental: {
urlImports: ['https://example.com/assets/', 'https://cdn.skypack.dev'],
},
}
Then, you can import modules directly from URLs:
import { a, b, c } from 'https://example.com/assets/some/module.js'
URL Imports can be used everywhere normal package imports can be used.
Security Model | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports |
6a18e8fea07b-1 | 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 imports to execute in the browser sandbox using the Edge Runtime.
Lockfile
When using URL imports, Next.js will create a next.lock directory containing a lockfile and fetched assets.
This directory must be committed to Git, not ignored by .gitignore.
When running next dev, Next.js will download and add all newly discovered URL Imports to your lockfile
When running next build, Next.js will use only the lockfile to build the application for production
Typically, no network requests are needed and any outdated lockfile will cause the build to fail.
One exception is resources that respond with Cache-Control: no-cache. | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports |
6a18e8fea07b-2 | 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 () => {
useEffect(() => {
confetti()
})
return <p>Hello</p>
}
Static Image Imports
import Image from 'next/image'
import logo from 'https://example.com/assets/logo.png'
export default () => (
<div>
<Image src={logo} placeholder="blur" />
</div>
)
URLs in CSS
.className {
background: url('https://example.com/assets/hero.jpg');
}
Asset Imports | https://nextjs.org/docs/app/api-reference/next-config-js/urlImports |
6a18e8fea07b-3 | 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 |
6dfb4be7fb03-0 | 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 |
5aecac7471a5-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 can be misplaced on your page, for example, when conflicting with a chat launcher. To change its position, open next.config.js and set the buildActivityPosition in the devIndicators object to bottom-right (default), bottom-left, top-right or top-left:next.config.js module.exports = {
devIndicators: {
buildActivityPosition: 'bottom-right',
},
}In some cases this indicator might not be useful for you. To remove it, open next.config.js and disable the buildActivity config in devIndicators object:next.config.js module.exports = {
devIndicators: {
buildActivity: false, | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators |
5aecac7471a5-1 | devIndicators: {
buildActivity: false,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/devIndicators |
94f374952b00-0 | 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 |
2bd7c01d5523-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 server will keep pages in the buffer
maxInactiveAge: 25 * 1000,
// number of pages that should be kept simultaneously without being disposed
pagesBufferLength: 2,
},
} | https://nextjs.org/docs/app/api-reference/next-config-js/onDemandEntries |
fa6dfa5159d0-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.com/script.js" />
</>
)
}
Props
Here's a summary of the props available for the Script Component:
PropExampleTypeRequiredsrcsrc="http://example.com/script"StringRequired unless inline script is usedstrategystrategy="lazyOnload"String-onLoadonLoad={onLoadFunc}Function-onReadyonReady={onReadyFunc}Function-onErroronError={onErrorFunc}Function-
Required Props
The <Script /> component requires the following properties.
src | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-1 | 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 of additional properties beyond those which are required.
strategy
The loading strategy of the script. There are four different strategies that can be used:
beforeInteractive: Load before any Next.js code and before any page hydration occurs.
afterInteractive: (default) Load early but after some hydration on the page occurs.
lazyOnload: Load during browser idle time.
worker: (experimental) Load in a web worker.
beforeInteractive
Scripts that load with the beforeInteractive strategy are injected into the initial HTML from the server, downloaded before any Next.js module, and executed in the order they are placed before any hydration occurs on the page. | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-2 | 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 script will load when any page in the application has been loaded server-side).
This strategy should only be used for critical scripts that need to be fetched before any part of the page becomes interactive.
app/layout.tsx import Script from 'next/script'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
<Script
src="https://example.com/script.js"
strategy="beforeInteractive"
/>
</html>
)
} | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-3 | 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 detectors
Cookie consent managers
afterInteractive
Scripts that use the afterInteractive strategy are injected into the HTML client-side and will load after some (or all) hydration occurs on the page. This is the default strategy of the Script component and should be used for any script that needs to load as soon as possible but not before any first-party Next.js code.
afterInteractive scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.
app/page.js import Script from 'next/script'
export default function Page() {
return ( | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-4 | 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 the HTML client-side during browser idle time and will load after all resources on the page have been fetched. This strategy should be used for any background or low priority scripts that do not need to load early.
lazyOnload scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.
app/page.js import Script from 'next/script'
export default function Page() {
return (
<> | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-5 | 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 is not yet stable and does not yet work with the app directory. Use with caution.
Scripts that use the worker strategy are off-loaded to a web worker in order to free up the main thread and ensure that only critical, first-party resources are processed on it. While this strategy can be used for any script, it is an advanced use case that is not guaranteed to support all third-party scripts.
To use worker as a strategy, the nextScriptWorkers flag must be enabled in next.config.js:
next.config.js module.exports = {
experimental: { | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-6 | 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="worker" />
</>
)
}
onLoad
Warning: onLoad does not yet work with Server Components and can only be used in Client Components. Further, onLoad can't be used with beforeInteractive – consider using onReady instead.
Some third-party scripts require users to run JavaScript code once after the script has finished loading in order to instantiate content or call a function. If you are loading a script with either afterInteractive or lazyOnload as a loading strategy, you can execute code after it has loaded using the onLoad property. | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-7 | 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={() => {
console.log(_.sample([1, 2, 3, 4]))
}}
/>
</>
)
}
onReady
Warning: onReady does not yet work with Server Components and can only be used in Client Components. | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-8 | 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 property.
Here's an example of how to re-instantiate a Google Maps JS embed every time the component is mounted:
app/page.tsx 'use client'
import { useRef } from 'react'
import Script from 'next/script'
export default function Page() {
const mapRef = useRef()
return (
<>
<div ref={mapRef}></div>
<Script
id="google-maps"
src="https://maps.googleapis.com/maps/api/js"
onReady={() => {
new google.maps.Map(mapRef.current, { | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-9 | 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 with the beforeInteractive loading strategy.
Sometimes it is helpful to catch when a script fails to load. These errors can be handled with the onError property:
app/page.tsx 'use client'
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://example.com/script.js"
onError={(e: Error) => {
console.error('Script failed to load', e)
}}
/> | https://nextjs.org/docs/app/api-reference/components/script |
fa6dfa5159d0-10 | 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 |
2de7a5cca900-0 | <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
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
)
}
Props
Here's a summary of the props available for the Image Component: | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-1 | }
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) 100vw"String-qualityquality={80}Integer (1-100)-prioritypriority={true}Boolean-placeholderplaceholder="blur"String-stylestyle={{objectFit: "contain"}}Object-onLoadingCompleteonLoadingComplete={img => done())}Function-onLoadonLoad={event => done())}Function-onErroronError(event => fail()}Function-loadingloading="lazy"String-blurDataURLblurDataURL="data:image/jpeg..."String-
Required Props
The Image Component requires the following properties: src, width, height, and alt. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-2 | 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>
)
}
src
Must be one of the following:
A statically imported image file
A path string. This can be either an absolute external URL, or an internal path depending on the loader prop.
When using an external URL, you must add it to remotePatterns in next.config.js.
width
The width property represents the rendered width in pixels, so it will affect how large the image appears.
Required, except for statically imported images or images with the fill property.
height | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-3 | 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 the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image.
It should contain text that could replace the image without changing the meaning of the page. It is not meant to supplement the image and should not repeat information that is already provided in the captions above or below the image.
If the image is purely decorative or not intended for the user, the alt property should be an empty string (alt="").
Learn more
Optional Props | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-4 | 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 resolve image URLs.
A loader is a function returning a URL string for the image, given the following parameters:
src
width
quality
Here is an example of using a custom loader:
'use client'
import Image from 'next/image'
const imageLoader = ({ src, width, quality }) => {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
export default function Page() {
return (
<Image
loader={imageLoader}
src="me.png"
alt="Picture of the author"
width={500} | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-5 | 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/image in your application, without passing a prop.
fill
fill={true} // {true} | {false}
A boolean that causes the image to fill the parent element instead of setting width and height.
The parent element must assign position: "relative", position: "fixed", or position: "absolute" style.
By default, the img element will automatically be assigned the position: "absolute" style. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-6 | 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: "cover" will cause the image to fill the entire container and be cropped to preserve aspect ratio. For this to look correct, the overflow: "hidden" style should be assigned to the parent element.
For more information, see also:
position
object-fit
object-position
sizes
A string that provides information about how wide the image will be at different breakpoints. The value of sizes will greatly affect performance for images using fill or which are styled to have a responsive size.
The sizes property serves two important purposes related to image performance: | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-7 | 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 selects an image that is the same size or larger than the viewport. The sizes property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify a sizes value in an image with the fill property, a default value of 100vw (full screen width) is used. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-8 | 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 such as 50vw, which represent a percentage of the viewport width, then the source set is trimmed to not include any values which are too small to ever be necessary.
For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following:
import Image from 'next/image'
export default function Page() {
return (
<div className="grid-element">
<Image
fill
src="/example.png" | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-9 | <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. Because file size is proportional to the square of the width, without sizes the user would download an image that's 9 times larger than necessary.
Learn more about srcset and sizes:
web.dev
mdn
quality
quality={75} // {number 1-100}
The quality of the optimized image, an integer between 1 and 100, where 100 is the best quality and therefore largest file size. Defaults to 75.
priority | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-10 | 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 multiple priority images, as different images may be the LCP element for different viewport sizes.
Should only be used when the image is visible above the fold. Defaults to false.
placeholder
placeholder = 'empty' // {empty} | {blur}
A placeholder to use while the image is loading. Possible values are blur or empty. Defaults to empty.
When blur, the blurDataURL property will be used as the placeholder. If src is an object from a static import and the imported image is .jpg, .png, .webp, or .avif, then blurDataURL will be automatically populated. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-11 | 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 with blurDataURL prop
Advanced Props
In some cases, you may need more advanced usage. The <Image /> component optionally accepts the following advanced properties.
style
Allows passing CSS styles to the underlying image element.
components/ProfileImage.js const imageStyle = {
borderRadius: '50%',
border: '1px solid #fff',
}
export default function ProfileImage() {
return <Image src="..." style={imageStyle} />
} | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-12 | 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 client'
<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
The callback function will be called with one argument, a reference to the underlying <img> element.
Good to know: Using props like onLoadingComplete, which accept a function, require using Client Components to serialize the provided function.
onLoad
<Image onLoad={(e) => console.log(e.target.naturalWidth)} />
A callback function that is invoked when the image is loaded. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-13 | 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 using Client Components to serialize the provided function.
onError
<Image onError={(e) => console.error(e.target.id)} />
A callback function that is invoked if the image fails to load.
Good to know: Using props like onError, which accept a function, require using Client Components to serialize the provided function.
loading
Recommendation: This property is only meant for advanced use cases. Switching an image to load with eager will normally hurt performance. We recommend using the priority property instead, which will eagerly preload the image.
loading = 'lazy' // {lazy} | {eager} | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-14 | 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 before the src image successfully loads. Only takes effect when combined
with placeholder="blur".
Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or
less) is recommended. Including larger images as placeholders may harm your application performance.
Try it out:
Demo the default blurDataURL prop
Demo the shimmer effect with blurDataURL prop
Demo the color effect with blurDataURL prop
You can also generate a solid color Data URL to match the image.
unoptimized | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-15 | 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 <Image {...props} unoptimized />
}
Since Next.js 12.3.0, this prop can be assigned to all images by updating next.config.js with the following configuration:
next.config.js module.exports = {
images: {
unoptimized: true,
},
}
Other Props
Other properties on the <Image /> component will be passed to the underlying
img element with the exception of the following:
srcSet. Use Device Sizes instead.
decoding. It is always "async".
Configuration Options | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-16 | 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 external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the remotePatterns property in your next.config.js file, as shown below:
next.config.js module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
} | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-17 | 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 in the next.config.js file:
next.config.js module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
},
],
},
}
Good to know: The example above will ensure the src property of next/image must start with https://img1.example.com or https://me.avatar.example.com or any number of subdomains. Any other protocol or unmatched hostname will respond with 400 Bad Request. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-18 | 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 remotePatterns instead of domains in order to protect your application from malicious users. Only use domains if you own all the content served from the domain.
Similar to remotePatterns, the domains configuration can be used to provide a list of allowed hostnames for external images.
However, the domains configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.
Below is an example of the domains property in the next.config.js file:
next.config.js module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
loaderFile | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-19 | 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',
loaderFile: './my/image/loader.js',
},
}
This must point to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example:
'use client'
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
Alternatively, you can use the loader prop to configure each instance of next/image.
Examples:
Custom Image Loader Configuration | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-20 | 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 properties below, you will override any changes to the Next.js defaults in future updates.
deviceSizes
If you know the expected device widths of your users, you can specify a list of device width breakpoints using the deviceSizes property in next.config.js. These widths are used when the next/image component uses sizes prop to ensure the correct image is served for user's device.
If no configuration is provided, the default below is used.
next.config.js module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
} | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-21 | },
}
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 for images which provide a sizes prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.
If no configuration is provided, the default below is used.
next.config.js module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
formats
The default Image Optimization API will automatically detect the browser's supported image formats via the request's Accept header. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-22 | 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 below is used.
next.config.js module.exports = {
images: {
formats: ['image/webp'],
},
}
You can enable AVIF support with the following configuration.
next.config.js module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
},
}
Good to know:
AVIF generally takes 20% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower and then subsequent requests that are cached will be faster. | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-23 | 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 request and stored in the <distDir>/cache/images directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date.
The cache status of an image can be determined by reading the value of the x-nextjs-cache response header. The possible values are the following:
MISS - the path is not in the cache (occurs at most once, on the first visit) | https://nextjs.org/docs/app/api-reference/components/image |
2de7a5cca900-24 | 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, whichever is larger. Specifically, the max-age value of the Cache-Control header is used. If both s-maxage and max-age are found, then s-maxage is preferred. The max-age is also passed-through to any downstream clients including CDNs and browsers.
You can configure minimumCacheTTL to increase the cache duration when the upstream image does not include Cache-Control header or the value is very low.
You can configure deviceSizes and imageSizes to reduce the total number of possible generated images.
You can configure formats to disable multiple formats in favor of a single image format.
minimumCacheTTL | https://nextjs.org/docs/app/api-reference/components/image |