instruction
stringlengths
31
302
output
stringlengths
22
4.36k
source_url
stringlengths
41
99
How do I implement With the default template in Next.js?
To create a new app using the default template, run the following command in your terminal: You will then be asked the following prompts: Once you've answered the prompts, a new project will be created with your chosen configuration. ```bash npx create-next-app@latest ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/cli/create-next-app
How do I implement With any public GitHub example in Next.js?
To create a new app using any public GitHub example, use the --example option with the GitHub repo's URL. For example: Was this helpful? ```bash npx create-next-app@latest --example "https://github.com/.../" [your-project-name] ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/cli/create-next-app
How do I implement className in Next.js?
Returns a read-only CSS className for the loaded font to be passed to an HTML element. ```jsx <p className={inter.className}>Hello, Next.js!</p> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/font
How do I implement style in Next.js?
Returns a read-only CSS style object for the loaded font to be passed to an HTML element, including style.fontFamily to access the font family name and fallback fonts. ```jsx <p style={inter.style}>Hello World</p> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/font
How do I implement CSS Variables in Next.js?
If you would like to set your styles in an external style sheet and specify additional options there, use the CSS variable method. In addition to importing the font, also import the CSS file where the CSS variable is defined and set the variable option of the font loader object as follows: To use the font, set the className of the parent container of the text you would like to style to the font loader's variable value and the className of the text to the styles property from the external CSS file. Define the text selector class in the component.module.css CSS file as follows: In the example above, the text Hello World is styled using the Inter font and the generated font fallback with font-weight: 200 and font-style: italic. ```jsx import { Inter } from 'next/font/google' import styles from '../styles/component.module.css' const inter = Inter({ variable: '--font-inter', }) ``` ```jsx <main className={inter.variable}> <p className={styles.text}>Hello World</p> </main> ``` ```css .text { font-family: var(--font-inter); font-weight: 200; font-style: italic; } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/font
How do I implement Using a font definitions file in Next.js?
For example, create a fonts.ts file in a styles folder at the root of your app directory. Then, specify your font definitions as follows: You can now use these definitions in your code as follows: To make it easier to access the font definitions in your code, you can define a path alias in your tsconfig.json or jsconfig.json files as follows: You can now import any font definition as follows: ```typescript import { Inter, Lora, Source_Sans_3 } from 'next/font/google' import localFont from 'next/font/local' // define your variable fonts const inter = Inter() const lora = Lora() // define 2 weights of a non-variable font const sourceCodePro400 = Source_Sans_3({ weight: '400' }) const sourceCodePro700 = Source_Sans_3({ weight: '700' }) // define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' }) export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes } ``` ```jsx import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts' export default function Page() { return ( <div> <p className={inter.className}>Hello world using Inter font</p> <p style={lora.style}>Hello world using Lora font</p> <p className={sourceCodePro700.className}> Hello world using Source_Sans_3 font with weight 700 </p> <p className={greatVibes.className}>My title in Great Vibes font</p> </div> ) } ``` ```json { "compilerOptions": { "paths": { "@/fonts": ["./styles/fonts"] } } } ``` ```javascript import { greatVibes, sourceCodePro400 } from '@/fonts' ``` ## Best Practices - Every time you call the localFont or Google font function, that font will be hosted as one instance in your application. Therefore, if you need to use the same font in multiple places, you should load it in one place and import the related font object where you need it. This is done using a font definitions file. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/font
What are the best practices for Using a font definitions file in Next.js?
```typescript import { Inter, Lora, Source_Sans_3 } from 'next/font/google' import localFont from 'next/font/local' // define your variable fonts const inter = Inter() const lora = Lora() // define 2 weights of a non-variable font const sourceCodePro400 = Source_Sans_3({ weight: '400' }) const sourceCodePro700 = Source_Sans_3({ weight: '700' }) // define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' }) export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes } ``` ```jsx import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts' export default function Page() { return ( <div> <p className={inter.className}>Hello world using Inter font</p> <p style={lora.style}>Hello world using Lora font</p> <p className={sourceCodePro700.className}> Hello world using Source_Sans_3 font with weight 700 </p> <p className={greatVibes.className}>My title in Great Vibes font</p> </div> ) } ``` ```json { "compilerOptions": { "paths": { "@/fonts": ["./styles/fonts"] } } } ``` ```javascript import { greatVibes, sourceCodePro400 } from '@/fonts' ``` ## Best Practices - Every time you call the localFont or Google font function, that font will be hosted as one instance in your application. Therefore, if you need to use the same font in multiple places, you should load it in one place and import the related font object where you need it. This is done using a font definitions file. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/font
How do I implement Form in Next.js?
It's useful for forms that update URL search params as it reduces the boilerplate code needed to achieve the above. Basic usage: ```javascript import Form from 'next/form' export default function Search() { return ( <Form action="/search"> {/* On submission, the input value will be appended to the URL, e.g. /search?query=abc */} <input name="query" /> <button type="submit">Submit</button> </Form> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/form
How do I implement Search form that leads to a search result page in Next.js?
You can create a search form that navigates to a search results page by passing the path as an action: When the user updates the query input field and submits the form, the form data will be encoded into the URL as search params, e.g. /search?query=abc. Good to know: If you pass an empty string "" to action, the form will navigate to the same route with updated search params. On the results page, you can access the query using the searchParams page.js prop and use it to fetch data from an external source. When the <Form> becomes visible in the user's viewport, shared UI (such as layout.js and loading.js) on the /search page will be prefetched. On submission, the form will immediately navigate to the new route and show loading UI while the results are being fetched. You can design the fallback UI using loading.js: To cover cases when shared UI hasn't yet loaded, you can show instant feedback to the user using useFormStatus. First, create a component that displays a loading state when the form is pending: Then, update the search form page to use the SearchButton component: ```javascript import Form from 'next/form' export default function Page() { return ( <Form action="/search"> <input name="query" /> <button type="submit">Submit</button> </Form> ) } ``` ```jsx import { getSearchResults } from '@/lib/search' export default async function SearchPage({ searchParams }) { const results = await getSearchResults((await searchParams).query) return <div>...</div> } ``` ```html export default function Loading() { return <div>Loading...</div> } ``` ```jsx 'use client' import { useFormStatus } from 'react-dom' export default function SearchButton() { const status = useFormStatus() return ( <button type="submit">{status.pending ? 'Searching...' : 'Search'}</button> ) } ``` ```jsx import Form from 'next/form' import { SearchButton } from '@/ui/search-button' export default function Page() { return ( <Form action="/search"> <input name="query" /> <SearchButton /> </Form> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/form
How do I implement Mutations with Server Actions in Next.js?
You can perform mutations by passing a function to the action prop. Good to know: Since the "destination" of the form submission is not known until the action is executed, <Form> cannot automatically prefetch shared UI. Then, in the new page, you can fetch data using the params prop: See the Server Actions docs for more examples. Was this helpful? ```jsx import Form from 'next/form' import { createPost } from '@/posts/actions' export default function Page() { return ( <Form action={createPost}> <input name="title" /> {/* ... */} <button type="submit">Create Post</button> </Form> ) } ``` ```jsx 'use server' import { redirect } from 'next/navigation' export async function createPost(formData) { // Create a new post // ... // Redirect to the new post redirect(`/posts/${data.id}`) } ``` ```jsx import { getPost } from '@/posts/data' export default async function PostPage({ params }) { const { id } = await params const data = await getPost(id) return ( <div> <h1>{data.title}</h1> {/* ... */} </div> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/form
How do I implement Image in Next.js?
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. ```javascript import Image from 'next/image' export default function Page() { return ( <Image src="/profile.png" width={500} height={500} alt="Picture of the author" /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Required Props in Next.js?
The Image Component requires the following properties: src, alt, width and height (or fill). ```javascript 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> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement loader in Next.js?
A custom function used to resolve image URLs. A loader is a function returning a URL string for the image, given the following parameters: Here is an example of using a custom loader: Good to know: Using props like loader, which accept a function, requires using Client Components to serialize the provided function. ```jsx '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} height={500} /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement fill in Next.js?
A boolean that causes the image to fill the parent element, which is useful when the width and height are unknown. 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. If no styles are applied to the image, the image will stretch 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 more information, see also: ```jsx fill={true} // {true} | {false} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement sizes in Next.js?
A string, similar to a media query, 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: 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: 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: ```jsx import Image from 'next/image' export default function Page() { return ( <div className="grid-element"> <Image fill src="/example.png" sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" /> </div> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement quality in Next.js?
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. Good to know: If the original source image was already low quality, setting the quality prop too high could cause the resulting optimized image to be larger than the original source image. ```jsx quality={75} // {number 1-100} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement priority in Next.js?
Should only be used when the image is visible above the fold. Defaults to false. ```jsx priority={false} // {false} | {true} ``` ## Best Practices - 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. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
What are the best practices for priority in Next.js?
```jsx priority={false} // {false} | {true} ``` ## Best Practices - 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. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement style in Next.js?
Allows passing CSS styles to the underlying image element. 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. ```javascript const imageStyle = { borderRadius: '50%', border: '1px solid #fff', } export default function ProfileImage() { return <Image src="..." style={imageStyle} /> } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement onLoadingComplete in Next.js?
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, requires using Client Components to serialize the provided function. ```jsx 'use client' <Image onLoadingComplete={(img) => console.log(img.naturalWidth)} /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement onLoad in Next.js?
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, the Event which has a target that references the underlying <img> element. Good to know: Using props like onLoad, which accept a function, requires using Client Components to serialize the provided function. ```jsx <Image onLoad={(e) => console.log(e.target.naturalWidth)} /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement loading in Next.js?
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. ```jsx loading = 'lazy' // {lazy} | {eager} ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
What are the best practices for blurDataURL in Next.js?
## Best Practices - 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. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement unoptimized in Next.js?
When true, the source image will be served as-is from the src instead of changing quality, size, or format. Defaults to false. This is useful for images that do not benefit from optimization such as small images (less than 1KB), vector images (SVG), or animated images (GIF). ```jsx unoptimized = {false} // {false} | {true} ``` ```jsx import Image from 'next/image' const UnoptimizedImage = (props) => { return <Image {...props} unoptimized /> } ``` ```javascript module.exports = { images: { unoptimized: true, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement overrideSrc in Next.js?
When providing the src prop to the <Image> component, both the srcset and src attributes are generated automatically for the resulting <img>. In some cases, it is not desirable to have the src attribute generated and you may wish to override it using the overrideSrc prop. For example, when upgrading an existing website from <img> to <Image>, you may wish to maintain the same src attribute for SEO purposes such as image ranking or avoiding recrawl. ```javascript <Image src="/me.jpg" /> ``` ```html <img srcset=" /_next/image?url=%2Fme.jpg&w=640&q=75 1x, /_next/image?url=%2Fme.jpg&w=828&q=75 2x " src="/_next/image?url=%2Fme.jpg&w=828&q=75" /> ``` ```javascript <Image src="/me.jpg" overrideSrc="/override.jpg" /> ``` ```html <img srcset=" /_next/image?url=%2Fme.jpg&w=640&q=75 1x, /_next/image?url=%2Fme.jpg&w=828&q=75 2x " src="/override.jpg" /> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement remotePatterns in Next.js?
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. ```javascript module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'example.com', port: '', pathname: '/account123/**', search: '', }, ], }, } ``` ```javascript module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: '**.example.com', port: '', search: '', }, ], }, } ``` ```javascript module.exports = { images: { remotePatterns: [ { protocol: 'https', hostname: 'assets.example.com', search: '?v=1727111025337', }, ], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement domains in Next.js?
Similar to remotePatterns, the domains configuration can be used to provide a list of allowed hostnames for external images. ```javascript module.exports = { images: { domains: ['assets.acme.com'], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement loaderFile in Next.js?
Examples: Custom Image Loader Configuration Good to know: Customizing the image loader file, which accepts a function, requires using Client Components to serialize the provided function. ```javascript module.exports = { images: { loader: 'custom', loaderFile: './my/image/loader.js', }, } ``` ```javascript 'use client' export default function myImageLoader({ src, width, quality }) { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement deviceSizes in Next.js?
If no configuration is provided, the default below is used. ```javascript module.exports = { images: { deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement imageSizes in Next.js?
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. ```javascript module.exports = { images: { imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement formats in Next.js?
The default Image Optimization API will automatically detect the browser's supported image formats via the request's Accept header in order to determine the best output format. If the Accept header 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. You can enable AVIF support, which will fallback to the original format of the src image if the browser does not support AVIF: Good to know: ```javascript module.exports = { images: { formats: ['image/webp'], }, } ``` ```javascript module.exports = { images: { formats: ['image/avif'], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
What are the best practices for Caching Behavior in Next.js?
## Best Practices - 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. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement minimumCacheTTL in Next.js?
You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a Static Image Import which will automatically hash the file contents and cache the image forever with a Cache-Control header of immutable. If no configuration is provided, the default below is used. You can increase the TTL to reduce the number of revalidations and potentionally lower cost: The expiration (or rather Max Age) of the optimized image is defined by either the minimumCacheTTL or the upstream image Cache-Control header, whichever is larger. There is no mechanism to invalidate the cache at this time, so its best to keep minimumCacheTTL low. Otherwise you may need to manually change the src prop or delete <distDir>/cache/images. ```javascript module.exports = { images: { minimumCacheTTL: 60, // 1 minute }, } ``` ```javascript module.exports = { images: { minimumCacheTTL: 2678400, // 31 days }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement disableStaticImages in Next.js?
The default behavior allows you to import static files such as import icon from './icon.png' and then pass that to the src property. In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently. ```javascript module.exports = { images: { disableStaticImages: true, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement dangerouslyAllowSVG in Next.js?
The default loader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper Content Security Policy (CSP) headers. ```javascript module.exports = { images: { dangerouslyAllowSVG: true, contentDispositionType: 'attachment', contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", }, } ``` ## Best Practices - Therefore, we recommended using the unoptimized prop when the src prop is known to be SVG. This happens automatically when src ends with ".svg". - In addition, it is strongly recommended to also set contentDispositionType to force the browser to download the image, as well as contentSecurityPolicy to prevent scripts embedded in the image from executing. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
What are the best practices for dangerouslyAllowSVG in Next.js?
```javascript module.exports = { images: { dangerouslyAllowSVG: true, contentDispositionType: 'attachment', contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", }, } ``` ## Best Practices - Therefore, we recommended using the unoptimized prop when the src prop is known to be SVG. This happens automatically when src ends with ".svg". - In addition, it is strongly recommended to also set contentDispositionType to force the browser to download the image, as well as contentSecurityPolicy to prevent scripts embedded in the image from executing. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement contentDispositionType in Next.js?
The default loader sets the Content-Disposition header to attachment for added protection since the API can serve arbitrary remote images. The default value is attachment which forces the browser to download the image when visiting directly. This is particularly important when dangerouslyAllowSVG is true. You can optionally configure inline to allow the browser to render the image when visiting directly, without downloading it. ```javascript module.exports = { images: { contentDispositionType: 'inline', }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Responsive image using a static import in Next.js?
If the source image is not dynamic, you can statically import to create a responsive image: Try it out: Demo the image responsive to viewport ```javascript import Image from 'next/image' import me from '../photos/me.jpg' export default function Author() { return ( <Image src={me} alt="Picture of the author" sizes="100vw" style={{ width: '100%', height: 'auto', }} /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Responsive image with aspect ratio in Next.js?
If the source image is a dynamic or a remote url, you will also need to provide width and height to set the correct aspect ratio of the responsive image: Try it out: Demo the image responsive to viewport ```javascript import Image from 'next/image' export default function Page({ photoUrl }) { return ( <Image src={photoUrl} alt="Picture of the author" sizes="100vw" style={{ width: '100%', height: 'auto', }} width={500} height={300} /> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Responsive image with fill in Next.js?
If you don't know the aspect ratio, you will need to set the fill prop and set position: relative on the parent. Optionally, you can set object-fit style depending on the desired stretch vs crop behavior: Try it out: ```javascript import Image from 'next/image' export default function Page({ photoUrl }) { return ( <div style={{ position: 'relative', width: '300px', height: '500px' }}> <Image src={photoUrl} alt="Picture of the author" sizes="300px" fill style={{ objectFit: 'contain', }} /> </div> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Theme Detection CSS in Next.js?
If you want to display a different image for light and dark mode, you can create a new component that wraps two <Image> components and reveals the correct one based on a CSS media query. Good to know: The default behavior of loading="lazy" ensures that only the correct image is loaded. You cannot use priority or loading="eager" because that would cause both images to load. Instead, you can use fetchPriority="high". Try it out: Demo light/dark mode theme detection ```css .imgDark { display: none; } @media (prefers-color-scheme: dark) { .imgLight { display: none; } .imgDark { display: unset; } } ``` ```jsx import styles from './theme-image.module.css' import Image from 'next/image' const ThemeImage = (props) => { const { srcLight, srcDark, ...rest } = props return ( <> <Image {...rest} src={srcLight} className={styles.imgLight} /> <Image {...rest} src={srcDark} className={styles.imgDark} /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Theme Detection Picture in Next.js?
If you want to display a different image for light and dark mode, you can use the <picture> element to display a different image based on the user's preferred color scheme. ```javascript import { getImageProps } from 'next/image' export default function Page() { const common = { alt: 'Theme Example', width: 800, height: 400 } const { props: { srcSet: dark }, } = getImageProps({ ...common, src: '/dark.png' }) const { props: { srcSet: light, ...rest }, } = getImageProps({ ...common, src: '/light.png' }) return ( <picture> <source media="(prefers-color-scheme: dark)" srcSet={dark} /> <source media="(prefers-color-scheme: light)" srcSet={light} /> <img {...rest} /> </picture> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Art Direction in Next.js?
If you want to display a different image for mobile and desktop, sometimes called Art Direction, you can provide different src, width, height, and quality props to getImageProps(). ```javascript import { getImageProps } from 'next/image' export default function Home() { const common = { alt: 'Art Direction Example', sizes: '100vw' } const { props: { srcSet: desktop }, } = getImageProps({ ...common, width: 1440, height: 875, quality: 80, src: '/desktop.jpg', }) const { props: { srcSet: mobile, ...rest }, } = getImageProps({ ...common, width: 750, height: 1334, quality: 70, src: '/mobile.jpg', }) return ( <picture> <source media="(min-width: 1000px)" srcSet={desktop} /> <source media="(min-width: 500px)" srcSet={mobile} /> <img {...rest} style={{ width: '100%', height: 'auto' }} /> </picture> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement Background CSS in Next.js?
You can even convert the srcSet string to the image-set() CSS function to optimize a background image. ```javascript import { getImageProps } from 'next/image' function getBackgroundImage(srcSet = '') { const imageSet = srcSet .split(', ') .map((str) => { const [url, dpi] = str.split(' ') return `url("${url}") ${dpi}` }) .join(', ') return `image-set(${imageSet})` } export default function Home() { const { props: { srcSet }, } = getImageProps({ alt: '', width: 128, height: 128, src: '/img.png' }) const backgroundImage = getBackgroundImage(srcSet) const style = { height: '100vh', width: '100vw', backgroundImage } return ( <main style={style}> <h1>Hello World</h1> </main> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/image
How do I implement S in Next.js?
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. ```javascript import Script from 'next/script' export default function Dashboard() { return ( <> <Script src="https://example.com/script.js" /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement beforeInteractive in Next.js?
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. 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: ```jsx import Script from 'next/script' export default function RootLayout({ children }) { return ( <html lang="en"> <body> {children} <Script src="https://example.com/script.js" strategy="beforeInteractive" /> </body> </html> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement afterInteractive in Next.js?
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. Some examples of scripts that are good candidates for afterInteractive include: ```javascript import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" strategy="afterInteractive" /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement lazyOnload in Next.js?
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. Examples of scripts that do not need to load immediately and can be fetched with lazyOnload include: ```javascript import Script from 'next/script' export default function Page() { return ( <> <Script src="https://example.com/script.js" strategy="lazyOnload" /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement worker in Next.js?
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. worker scripts can only currently be used in the pages/ directory: ```javascript module.exports = { experimental: { nextScriptWorkers: true, }, } ``` ```javascript import Script from 'next/script' export default function Home() { return ( <> <Script src="https://example.com/script.js" strategy="worker" /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement onLoad in Next.js?
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. Here's an example of executing a lodash method only after the library has been loaded. ```javascript '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])) }} /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement onReady in Next.js?
Here's an example of how to re-instantiate a Google Maps JS embed every time the component is mounted: ```jsx '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, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }) }} /> </> ) } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/components/script
How do I implement Specifying a root directory within a monorepo in Next.js?
rootDir can be a path (relative or absolute), a glob (i.e. "packages/*/"), or an array of paths and/or globs. ```jsx import { FlatCompat } from '@eslint/eslintrc' const compat = new FlatCompat({ // import.meta.dirname is available after Node.js v20.11.0 baseDirectory: import.meta.dirname, }) const eslintConfig = [ ...compat.config({ extends: ['next'], settings: { next: { rootDir: 'packages/my-app/', }, }, }), ] export default eslintConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/eslint
What are the best practices for With TypeScript in Next.js?
```jsx import { FlatCompat } from '@eslint/eslintrc' const compat = new FlatCompat({ // import.meta.dirname is available after Node.js v20.11.0 baseDirectory: import.meta.dirname, }) const eslintConfig = [ ...compat.config({ extends: ['next/core-web-vitals', 'next/typescript'], }), ] export default eslintConfig ``` ## Best Practices - Those rules are based on plugin:@typescript-eslint/recommended. See typescript-eslint > Configs for more details. Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/eslint
How do I implement With Prettier in Next.js?
ESLint also contains code formatting rules, which can conflict with your existing Prettier setup. We recommend including eslint-config-prettier in your ESLint config to make ESLint and Prettier work together. First, install the dependency: Then, add prettier to your existing ESLint config: ```bash npm install --save-dev eslint-config-prettier yarn add --dev eslint-config-prettier pnpm add --save-dev eslint-config-prettier bun add --dev eslint-config-prettier ``` ```jsx import { FlatCompat } from '@eslint/eslintrc' const compat = new FlatCompat({ // import.meta.dirname is available after Node.js v20.11.0 baseDirectory: import.meta.dirname, }) const eslintConfig = [ ...compat.config({ extends: ['next', 'prettier'], }), ] export default eslintConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/eslint
How do I implement TypeScript in Next.js?
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. This page documents all the available configuration options: ```jsx import type { NextConfig } from 'next' const nextConfig: NextConfig = { /* config options here */ } export default nextConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js
How do I implement Set up a CDN in Next.js?
Would instead become: Files in the public folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself Was this helpful? ```jsx // @ts-check import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' export default (phase) => { const isDev = phase === PHASE_DEVELOPMENT_SERVER /** * @type {import('next').NextConfig} */ const nextConfig = { assetPrefix: isDev ? undefined : 'https://cdn.mydomain.com', } return nextConfig } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix
How do I implement in Next.js?
Good to know: This value must be set at build time and cannot be changed without re-building as the value is inlined in the client-side bundles. ```javascript module.exports = { basePath: '/docs', } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath
How do I implement Links in Next.js?
For example, using /about will automatically become /docs/about when basePath is set to /docs. Output html: This makes sure that you don't have to change all links in your application when changing the basePath value. ```javascript export default function HomePage() { return ( <> <Link href="/about">About Page</Link> </> ) } ``` ```html <a href="/docs/about">About Page</a> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath
How do I implement Images in Next.js?
For example, using /docs/me.png will properly serve your image when basePath is set to /docs. Was this helpful? ```jsx import Image from 'next/image' function Home() { return ( <> <h1>My Homepage</h1> <Image src="/docs/me.png" alt="Picture of the author" width={500} height={500} /> <p>Welcome to my homepage!</p> </> ) } export default Home ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath
How do I implement Usage in Next.js?
You can now use this custom blog configuration in your component or function as follows: ```css module.exports = { experimental: { dynamicIO: true, cacheLife: { blog: { stale: 3600, // 1 hour revalidate: 900, // 15 minutes expire: 86400, // 1 day }, }, }, } ``` ```javascript import { unstable_cacheLife as cacheLife } from 'next/cache' export async function getCachedData() { 'use cache' cacheLife('blog') const data = await fetch('/api/data') return data } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheLife
How do I implement Disabling compression in Next.js?
To disable compression, set the compress config option to false: We do not recommend disabling compression unless you have compression configured on your server, as compression reduces bandwidth usage and improves the performance of your application. ```javascript module.exports = { compress: false, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/compress
How do I implement in Next.js?
CSS Chunking is a strategy used to improve the performance of your web application by splitting and re-ordering CSS files into chunks. This allows you to load only the CSS that is needed for a specific route, instead of loading all the application's CSS at once. ```typescript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { cssChunking: true, // default }, } module.exports = nextConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/cssChunking
How do I implement in Next.js?
distDir should not leave your project directory. For example, ../build is an invalid directory. Was this helpful? ```javascript module.exports = { distDir: 'build', } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/distDir
How do I implement Usage in Next.js?
When dynamicIO is enabled, you can use the following cache functions and configurations: The use cache directive The cacheLife function with use cache The cacheTag function ```jsx import type { NextConfig } from 'next' const nextConfig: NextConfig = { experimental: { dynamicIO: true, }, } export default nextConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/dynamicIO
How do I implement env in Next.js?
Now you can access process.env.customKey in your code. For example: For example, the following line: Will end up being: Was this helpful? ```javascript module.exports = { env: { customKey: 'my-value', }, } ``` ```jsx function Page() { return <h1>The value of customKey is: {process.env.customKey}</h1> } export default Page ``` ```jsx return <h1>The value of customKey is: {process.env.customKey}</h1> ``` ```jsx return <h1>The value of customKey is: {'my-value'}</h1> ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/env
How do I implement in Next.js?
You can specify a custom stale-while-revalidate expire time for CDNs to consume in the Cache-Control header for ISR enabled pages. Now when sending the Cache-Control header the expire time will be calculated depending on the specific revalidate period. For example, if you have a revalidate of 15 minutes on a path and the expire time is one hour the generated Cache-Control header will be s-maxage=900, stale-while-revalidate=2700 so that it can stay stale for 15 minutes less than the configured expire time. Was this helpful? ```javascript module.exports = { // one hour in seconds expireTime: 3600, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/expireTime
How do I implement in Next.js?
Let's start with an example, to create a custom exportPathMap for an app with the following pages: The pages will then be exported as HTML files, for example, /about will become /about.html. 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 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. ```javascript module.exports = { exportPathMap: async function ( defaultPathMap, { dev, dir, outDir, distDir, buildId } ) { return { '/': { page: '/' }, '/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' } }, } }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/exportPathMap
How do I implement in Next.js?
Headers allow you to set custom HTTP headers on the response to an incoming request on a given path. 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. 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. ```javascript 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', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Header Overriding Behavior in Next.js?
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. ```javascript module.exports = { async headers() { return [ { source: '/:path*', headers: [ { key: 'x-hello', value: 'there', }, ], }, { source: '/hello', headers: [ { key: 'x-hello', value: 'world', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Path Matching in Next.js?
Path matches are allowed, for example /blog/:slug will match /blog/hello-world (no nested paths): ```javascript 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', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Wildcard Path Matching in Next.js?
To match a wildcard path you can use * after a parameter, for example /blog/:slug* will match /blog/a/b/c/d/hello-world: ```javascript 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', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Regex Path Matching in Next.js?
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: 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: ```javascript module.exports = { async headers() { return [ { source: '/blog/:post(\\d{1,})', headers: [ { key: 'x-post', value: ':post', }, ], }, ] }, } ``` ```javascript module.exports = { async headers() { return [ { // this will match `/english(default)/something` being requested source: '/english\\(default\\)/:slug', headers: [ { key: 'x-header', value: 'value', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Header, Cookie, and Query Matching in Next.js?
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. 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. ```javascript 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', }, ], }, // 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 // 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', 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', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Headers with basePath support in Next.js?
When leveraging basePath support with headers each source is automatically prefixed with the basePath unless you add basePath: false to the header: ```javascript 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, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement Headers with i18n support in Next.js?
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. ```javascript 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', 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', }, ], }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/headers
How do I implement in Next.js?
Good to know: Customizing the image loader file, which accepts a function, requires using Client Components to serialize the provided function. To learn more about configuring the behavior of the built-in Image Optimization API and the Image Component, see Image Configuration Options for available options. ```javascript module.exports = { images: { loader: 'custom', loaderFile: './my/image/loader.js', }, } ``` ```javascript 'use client' export default function myImageLoader({ src, width, quality }) { return `https://example.com/${src}?w=${width}&q=${quality || 75}` } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/images
How do I implement in Next.js?
Caching and revalidating pages (with Incremental Static Regeneration) use the same shared cache. When deploying to Vercel, the ISR cache is automatically persisted to durable storage. View an example of a custom cache handler and learn more about implementation. ```javascript module.exports = { cacheHandler: require.resolve('./cache-handler.js'), cacheMaxMemorySize: 0, // disable default in-memory caching } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/incrementalCacheHandlerPath
How do I implement Usage in Next.js?
Experimental support for inlining CSS in the <head>. When this flag is enabled, all places where we normally generate a <link> tag will instead have a generated <style> tag. ```typescript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { inlineCss: true, }, } module.exports = nextConfig ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/inlineCss
How do I implement Fetching in Next.js?
Any fetch requests that are restored from the Server Components HMR cache are not logged by default. However, this can be enabled by setting logging.fetches.hmrRefreshes to true. ```javascript module.exports = { logging: { fetches: { fullUrl: true, }, }, } ``` ```javascript module.exports = { logging: { fetches: { hmrRefreshes: true, }, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
How do I implement Incoming Requests in Next.js?
By default all the incoming requests will be logged in the console during development. You can use the incomingRequests option to decide which requests to ignore. Since this is only logged in development, this option doesn't affect production builds. Or you can disable incoming request logging by setting incomingRequests to false. ```javascript module.exports = { logging: { incomingRequests: { ignore: [/\api\/v1\/health/], }, }, } ``` ```javascript module.exports = { logging: { incomingRequests: false, }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
How do I implement Disabling Logging in Next.js?
In addition, you can disable the development logging by setting logging to false. Was this helpful? ```javascript module.exports = { logging: false, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/logging
How do I implement in Next.js?
Adding a package to experimental.optimizePackageImports will only load the modules you are actually using, while still giving you the convenience of writing import statements with many named exports. The following libraries are optimized by default: Was this helpful? ```javascript module.exports = { experimental: { optimizePackageImports: ['package-name'], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/optimizePackageImports
How do I implement Automatically Copying Traced Files in Next.js?
To start your minimal server.js file locally, run the following command: Good to know: If your project needs to listen to a specific port or hostname, you can define PORT or HOSTNAME environment variables before running server.js. For example, run PORT=8080 HOSTNAME=0.0.0.0 node server.js to start the server on http://0.0.0.0:8080. ```javascript module.exports = { output: 'standalone', } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/output
How do I implement Caveats in Next.js?
Note: The key of outputFileTracingIncludes/outputFileTracingExcludes is a glob, so special characters need to be escaped. ```javascript module.exports = { // this includes files from the monorepo base two directories up outputFileTracingRoot: path.join(__dirname, '../../'), } ``` ```javascript module.exports = { outputFileTracingExcludes: { '/api/hello': ['./un-necessary-folder/**/*'], }, outputFileTracingIncludes: { '/api/another': ['./necessary-folder/**/*'], '/api/login/\\[\\[\\.\\.\\.slug\\]\\]': [ './node_modules/aws-crt/dist/bin/**/*', ], }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/output
How do I implement Incremental Adoption (Version 15) in Next.js?
Good to know: Routes that don't have experimental_ppr will default to false and will not be prerendered using PPR. You need to explicitly opt-in to PPR for each route. experimental_ppr will apply to all children of the route segment, including nested layouts and pages. You don't have to add it to every file, only the top segment of a route. To disable PPR for children segments, you can set experimental_ppr to false in the child segment. ```typescript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { ppr: 'incremental', }, } module.exports = nextConfig ``` ```jsx import { Suspense } from "react" import { StaticComponent, DynamicComponent, Fallback } from "@/app/ui" export const experimental_ppr = true export default function Page() { return { <> <StaticComponent /> <Suspense fallback={<Fallback />}> <DynamicComponent /> </Suspense> </> }; } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/ppr
How do I implement in Next.js?
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. Was this helpful? ```javascript module.exports = { productionBrowserSourceMaps: true, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/productionBrowserSourceMaps
How do I implement Annotations in Next.js?
You can configure the compiler to run in "opt-in" mode as follows: Then, you can annotate specific components or hooks with the "use memo" directive from React to opt-in: Note: You can also use the "use no memo" directive from React for the opposite effect, to opt-out a component or hook. Was this helpful? ```typescript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { reactCompiler: { compilationMode: 'annotation', }, }, } module.exports = nextConfig ``` ```javascript export default function Page() { 'use memo' // ... } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler
How do I implement in Next.js?
Good to know: This option is only available in App Router. Depending on the type of proxy between the browser and the server, the headers can be truncated. For example, if you are using a reverse proxy that doesn't support long headers, you should set a lower value to ensure that the headers are not truncated. Was this helpful? ```javascript module.exports = { reactMaxHeadersLength: 1000, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/reactMaxHeadersLength
How do I implement in Next.js?
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>. Was this helpful? ```javascript module.exports = { reactStrictMode: true, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/reactStrictMode
How do I implement in Next.js?
Redirects allow you to redirect an incoming request path to a different destination path. redirects is an async function that expects an array to be returned holding objects with source, destination, and permanent properties: source is the incoming request path pattern. destination is the path you want to route to. permanent true or false - if true will use the 308 status code which instructs clients/search engines to cache the redirect forever, if false will use the 307 status code which is temporary and is not cached. basePath: false or undefined - if false the basePath won't be included when matching, can be used for external redirects 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. Redirects are checked before the filesystem which includes pages and /public files. When using the Pages Router, redirects are not applied to client-side routing (Link, router.push) unless Middleware is present and matches the path. When a redirect is applied, any query values provided in the request will be passed through to the redirect destination. For example, see the following redirect configuration: Good to know: Remember to include the forward slash / before the colon : in path parameters of the source and destination paths, otherwise the path will be treated as a literal string and you run the risk of causing infinite redirects. When /old-blog/post-1?hello=world is requested, the client will be redirected to /blog/post-1?hello=world. ```javascript module.exports = { async redirects() { return [ { source: '/about', destination: '/', permanent: true, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement Path Matching in Next.js?
Path matches are allowed, for example /old-blog/:slug will match /old-blog/hello-world (no nested paths): ```javascript module.exports = { async redirects() { return [ { source: '/old-blog/:slug', destination: '/news/:slug', // Matched parameters can be used in the destination permanent: true, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement Regex Path Matching in Next.js?
To match a regex path you can wrap the regex in parentheses after a parameter, for example /post/:slug(\\d{1,}) will match /post/123 but not /post/abc: 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: ```javascript module.exports = { async redirects() { return [ { source: '/post/:slug(\\d{1,})', destination: '/news/:slug', // Matched parameters can be used in the destination permanent: false, }, ] }, } ``` ```javascript module.exports = { async redirects() { return [ { // this will match `/english(default)/something` being requested source: '/english\\(default\\)/:slug', destination: '/en-us/:slug', permanent: false, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement Header, Cookie, and Query Matching in Next.js?
To only match a redirect 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 redirect 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. 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. ```javascript module.exports = { async redirects() { return [ // if the header `x-redirect-me` is present, // this redirect will be applied { source: '/:path((?!another-page$).*)', has: [ { type: 'header', key: 'x-redirect-me', }, ], permanent: false, destination: '/another-page', }, // if the header `x-dont-redirect` is present, // this redirect will NOT be applied { source: '/:path((?!another-page$).*)', missing: [ { type: 'header', key: 'x-do-not-redirect', }, ], permanent: false, destination: '/another-page', }, // if the source, query, and cookie are matched, // this redirect will be applied { source: '/specific/:path*', has: [ { type: 'query', key: 'page', // the page value will not be available in the // destination since value is provided and doesn't // use a named capture group e.g. (?<page>home) value: 'home', }, { type: 'cookie', key: 'authorized', value: 'true', }, ], permanent: false, destination: '/another/:path*', }, // if the header `x-authorized` is present and // contains a matching value, this redirect will be applied { source: '/', has: [ { type: 'header', key: 'x-authorized', value: '(?<authorized>yes|true)', }, ], permanent: false, destination: '/home?authorized=:authorized', }, // if the host is `example.com`, // this redirect will be applied { source: '/:path((?!another-page$).*)', has: [ { type: 'host', value: 'example.com', }, ], permanent: false, destination: '/another-page', }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement Redirects with basePath support in Next.js?
When leveraging basePath support with redirects each source and destination is automatically prefixed with the basePath unless you add basePath: false to the redirect: ```javascript module.exports = { basePath: '/docs', async redirects() { return [ { source: '/with-basePath', // automatically becomes /docs/with-basePath destination: '/another', // automatically becomes /docs/another permanent: false, }, { // does not add /docs since basePath: false is set source: '/without-basePath', destination: 'https://example.com', basePath: false, permanent: false, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement Redirects with i18n support in Next.js?
When leveraging i18n support with redirects each source and destination is automatically prefixed to handle the configured locales unless you add locale: false to the redirect. If locale: false is used you must prefix the source and destination with a locale for it to be matched correctly. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the statusCode property instead of the permanent property, but not both. To to ensure IE11 compatibility, a Refresh header is automatically added for the 308 status code. ```javascript module.exports = { i18n: { locales: ['en', 'fr', 'de'], defaultLocale: 'en', }, async redirects() { return [ { source: '/with-locale', // automatically handles all locales destination: '/another', // automatically passes the locale on permanent: false, }, { // does not handle locales automatically since locale: false is set source: '/nl/with-locale-manual', destination: '/nl/another', locale: false, permanent: false, }, { // this matches '/' since `en` is the defaultLocale source: '/en', destination: '/en/another', locale: false, permanent: false, }, // it's possible to match all locales even when locale: false is set { source: '/:locale/page', destination: '/en/newpage', permanent: false, locale: false, }, { // this gets converted to /(en|fr|de)/(.*) so will not match the top-level // `/` or `/fr` routes like /:path* would source: '/(.*)', destination: '/another', permanent: false, }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects
How do I implement in Next.js?
Rewrites allow you to map an incoming request path to a different destination path. Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, redirects will reroute to a new page and show the URL changes. Rewrites are applied to client-side routing, a <Link href="/about"> will have the rewrite applied in the above example. rewrites is an async function that expects to return either an array or an object of arrays (see below) holding objects with source and destination properties: source: String - is the incoming request path pattern. destination: String is the path you want to route to. 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. Good to know: rewrites in beforeFiles do not check the filesystem/dynamic routes immediately after matching a source, they continue until all beforeFiles have been checked. ```javascript module.exports = { async rewrites() { return [ { source: '/about', destination: '/', }, ] }, } ``` ```javascript module.exports = { async rewrites() { return { beforeFiles: [ // These rewrites are checked after headers/redirects // and before all files including _next/public files which // allows overriding page files { source: '/some-page', destination: '/somewhere-else', has: [{ type: 'query', key: 'overrideMe' }], }, ], afterFiles: [ // These rewrites are checked after pages/public files // are checked but before dynamic routes { source: '/non-existent', destination: '/somewhere-else', }, ], fallback: [ // These rewrites are checked after both pages/public files // and dynamic routes are checked { source: '/:path*', destination: `https://my-old-site.com/:path*`, }, ], } }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
How do I implement Rewrite parameters in Next.js?
When using parameters in a rewrite the parameters will be passed in the query by default when none of the parameters are used in the destination. If a parameter is used in the destination none of the parameters will be automatically passed in the query. You can still pass the parameters manually in the query if one is already used in the destination by specifying the query in the destination. Good to know: Static pages from Automatic Static Optimization or prerendering params from rewrites will be parsed on the client after hydration and provided in the query. ```javascript module.exports = { async rewrites() { return [ { source: '/old-about/:path*', destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query }, ] }, } ``` ```javascript module.exports = { async rewrites() { return [ { source: '/docs/:path*', destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query }, ] }, } ``` ```javascript module.exports = { async rewrites() { return [ { source: '/:first/:second', destination: '/:first?second=:second', // Since the :first parameter is used in the destination the :second parameter // will not automatically be added in the query although we can manually add it // as shown above }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
How do I implement Regex Path Matching in Next.js?
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: 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: ```javascript module.exports = { async rewrites() { return [ { source: '/old-blog/:post(\\d{1,})', destination: '/blog/:post', // Matched parameters can be used in the destination }, ] }, } ``` ```javascript module.exports = { async rewrites() { return [ { // this will match `/english(default)/something` being requested source: '/english\\(default\\)/:slug', destination: '/en-us/:slug', }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
How do I implement Header, Cookie, and Query Matching in Next.js?
To only match a rewrite 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 rewrite 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. 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. ```javascript module.exports = { async rewrites() { return [ // if the header `x-rewrite-me` is present, // this rewrite will be applied { source: '/:path*', has: [ { type: 'header', key: 'x-rewrite-me', }, ], destination: '/another-page', }, // if the header `x-rewrite-me` is not present, // this rewrite will be applied { source: '/:path*', missing: [ { type: 'header', key: 'x-rewrite-me', }, ], destination: '/another-page', }, // if the source, query, and cookie are matched, // this rewrite will be applied { source: '/specific/:path*', has: [ { type: 'query', key: 'page', // the page value will not be available in the // destination since value is provided and doesn't // use a named capture group e.g. (?<page>home) value: 'home', }, { type: 'cookie', key: 'authorized', value: 'true', }, ], destination: '/:path*/home', }, // if the header `x-authorized` is present and // contains a matching value, this rewrite will be applied { source: '/:path*', has: [ { type: 'header', key: 'x-authorized', value: '(?<authorized>yes|true)', }, ], destination: '/home?authorized=:authorized', }, // if the host is `example.com`, // this rewrite will be applied { source: '/:path*', has: [ { type: 'host', value: 'example.com', }, ], destination: '/another-page', }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites
How do I implement Rewriting to an external URL in Next.js?
If you're using trailingSlash: true, you also need to insert a trailing slash in the source parameter. If the destination server is also expecting a trailing slash it should be included in the destination parameter as well. ```javascript module.exports = { async rewrites() { return [ { source: '/blog', destination: 'https://example.com/blog', }, { source: '/blog/:slug', destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination }, ] }, } ``` ```javascript module.exports = { trailingSlash: true, async rewrites() { return [ { source: '/blog/', destination: 'https://example.com/blog/', }, { source: '/blog/:path*/', destination: 'https://example.com/blog/:path*/', }, ] }, } ``` Version info: 15.2.1
https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites