id
stringlengths
14
15
text
stringlengths
49
1.09k
source
stringlengths
46
101
092d651651e2-3
Dynamic Data Fetching Dynamic data fetches are fetch() requests that specifically opt out of caching behavior by setting the cache option to 'no-store' or revalidate to 0. The caching options for all fetch requests in a layout or page can also be set using the segment config object. To learn more about Dynamic Data Fet...
https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering
d0539c74aec9-0
Edge and Node.js Runtimes In the context of Next.js, "runtime" refers to the set of libraries, APIs, and general functionality available to your code during execution. Next.js has two server runtimes where you can render parts of your application code: Node.js Runtime Edge Runtime Each runtime has its own set of APIs. ...
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-1
NodeServerlessEdgeCold Boot/~250msInstantHTTP StreamingYesYesYesIOAllAllfetchScalability/HighHighestSecurityNormalHighHighLatencyNormalLowLowestnpm PackagesAllAllA smaller subset Edge Runtime In Next.js, the lightweight Edge Runtime is a subset of available Node.js APIs. The Edge Runtime is ideal if you need to deliver...
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-2
Deploying your Next.js application to a Node.js server will require managing, scaling, and configuring your infrastructure. Alternatively, you can consider deploying your Next.js application to a serverless platform like Vercel, which will handle this for you. Serverless Node.js Serverless is ideal if you need a scalab...
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
d0539c74aec9-3
Examples Segment Runtime Option You can specify a runtime for individual route segments in your Next.js application. To do so, declare a variable called runtime and export it. The variable must be a string, and must have a value of either 'nodejs' or 'edge' runtime.The following example demonstrates a page route segmen...
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
175f38087dac-0
Data FetchingThe Next.js App Router allows you to fetch data directly in your React components by marking the function as async and using await for the Promise. Data fetching is built on top of the fetch() Web API and React Server Components. When using fetch(), requests are automatically deduped by default. Next.js ex...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-1
throw new Error('Failed to fetch data') } return res.json() } export default async function Page() { const data = await getData() return <main></main> } Good to know: To use an async Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher. Server...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-2
Wrapping fetch in use is currently not recommended in Client Components and may trigger multiple re-renders. For now, if you need to fetch data in a Client Component, we recommend using a third-party library such as SWR or React Query. Good to know: We'll be adding more examples once fetch and use work in Client Compon...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-3
See Revalidating Data for more information. Good to know: Caching at the fetch level with revalidate or cache: 'force-cache' stores the data across requests in a shared cache. You should avoid using it for user-specific data (i.e. requests that derive data from cookies() or headers()) Dynamic Data Fetching To fetch fre...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-4
return res.json() } async function getArtistAlbums(username: string) { const res = await fetch(`https://api.example.com/artist/${username}/albums`) return res.json() } export default async function Page({ params: { username }, }: { params: { username: string } }) { // Initiate both requests in parallel ...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-5
</> ) } By starting the fetch prior to calling await in the Server Component, each request can eagerly start to fetch requests at the same time. This sets the components up so you can avoid waterfalls. We can save time by initiating both requests in parallel, however, the user won't see the rendered result until both...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-6
const albumData = getArtistAlbums(username) // Wait for the artist's promise to resolve first const artist = await artistData return ( <> <h1>{artist.name}</h1> {/* Send the artist information first, and wrap albums in a suspense boundary */} <Suspense fallback={<div>Loading......
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-7
))} </ul> ) } Take a look at the preloading pattern for more information on improving components structure. Sequential Data Fetching To fetch data sequentially, you can fetch directly inside the component that needs it, or you can await the result of fetch inside the component that needs it: app/artist/page.tsx /...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-8
}: { params: { username: string } }) { // Wait for the artist const artist = await getArtist(username) return ( <> <h1>{artist.name}</h1> <Suspense fallback={<div>Loading...</div>}> <Playlists artistID={artist.id} /> </Suspense> </> ) } By fetching data inside the component...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-9
In the pages directory, pages using server-rendering would show the browser loading spinner until getServerSideProps had finished, then render the React component for that page. This can be described as "all or nothing" data fetching. Either you had the entire data for your page, or none. In the app directory, you have...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-10
Data Fetching without fetch() You might not always have the ability to use and configure fetch requests directly if you're using a third-party library such as an ORM or database client. In cases where you cannot use fetch but still want to control the caching or revalidating behavior of a layout or page, you can rely o...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
175f38087dac-11
Good to know: Dynamic functions like cookies() and headers() will make the route segment dynamic. Segment Cache Configuration As a temporary solution, until the caching behavior of third-party queries can be configured, you can use segment configuration to customize the cache behavior of the entire segment. app/page.ts...
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching
2a4a233cbb5c-0
Caching DataNext.js has built-in support for caching data, both on a per-request basis (recommended) or for an entire route segment. Per-request Caching fetch() By default, all fetch() requests are cached and deduplicated automatically. This means that if you make the same request twice, the second request will reuse t...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-1
const comments = await getComments() // cache HIT Requests are not cached if: Dynamic methods (next/headers, export const POST, or similar) are used and the fetch is a POST request (or uses Authorization or cookie headers) fetchCache is configured to skip cache by default revalidate: 0 or cache: 'no-store' is configure...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-2
const data = res.json() // ... } React cache() React allows you to cache() and deduplicate requests, memoizing the result of the wrapped function call. The same function called with the same arguments will reuse a cached value instead of re-running the function. utils/getUser.ts import { cache } from 'react' export...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-3
export default async function Page({ params: { id }, }: { params: { id: string } }) { const user = await getUser(id) // ... } Although the getUser() function is called twice in the example above, only one query will be made to the database. This is because getUser() is wrapped in cache(), so the second request ...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-4
POST requests and cache() POST requests are automatically deduplicated when using fetch – unless they are inside of POST Route Handler or come after reading headers()/cookies(). For example, if you are using GraphQL and POST requests in the above cases, you can use cache to deduplicate requests. The cache arguments mus...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-5
export const preload = (id: string) => { // void evaluates the given expression and returns undefined // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void void getUser(id) } export default async function User({ id }: { id: string }) { const result = await getUser(id) // ... } By...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-6
} Good to know: The preload() function can have any name. It's a pattern, not an API. This pattern is completely optional and something you can use to optimize on a case-by-case basis. This pattern is a further optimization on top of parallel data fetching. Now you don't have to pass promises down as props and can inst...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-7
export const getUser = cache(async (id: string) => { // ... }) With this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching only happens on the server. The getUser.ts exports can be used by layouts, pages, or components to give them control over when a user's data is fetched....
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
2a4a233cbb5c-8
Good to know: If a page, layout, and fetch request inside components all specify a revalidate frequency, the lowest value of the three will be used. Advanced: You can set fetchCache to 'only-cache' or 'force-cache' to ensure that all fetch requests opt into caching but the revalidation frequency might still be lowered ...
https://nextjs.org/docs/app/building-your-application/data-fetching/caching
66d202fb49eb-0
Revalidating DataNext.js allows you to update specific static routes without needing to rebuild your entire site. Revalidation (also known as Incremental Static Regeneration) allows you to retain the benefits of static while scaling to millions of pages. There are two types of revalidation in Next.js: Background: Reval...
https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
66d202fb49eb-1
app/page.tsx export const revalidate = 60 // revalidate this page every 60 seconds In addition to fetch, you can also revalidate data using cache. How it works When a request is made to the route that was statically rendered at build time, it will initially show the cached data. Any requests to the route after the init...
https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
66d202fb49eb-2
Good to know: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. useCdn: false), otherwise a revalidation won't be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the Cache-Control header. ISR...
https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
66d202fb49eb-3
Content from your headless CMS is created or updated. Ecommerce metadata changes (price, description, category, reviews, etc). Using On-Demand Revalidation Data can be revalidated on-demand by path (revalidatePath) or by cache tag (revalidateTag). For example, the following fetch adds the cache tag collection: app/page...
https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
66d202fb49eb-4
export async function GET(request: NextRequest) { const tag = request.nextUrl.searchParams.get('tag') revalidateTag(tag) return NextResponse.json({ revalidated: true, now: Date.now() }) } Error Handling and Revalidation If an error is thrown while attempting to revalidate data, the last successfully generated dat...
https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
46ac516751e2-0
Server ActionsServer Actions are an alpha feature in Next.js, built on top of React Actions. They enable server-side data mutations, reduced client-side JavaScript, and progressively enhanced forms. They can be defined inside Server Components and/or called from Client Components: With Server Components: app/add-to-car...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-1
app/actions.js 'use server' export async function addItem(data) { const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } app/add-to-cart.js 'use client' import { addItem } from './actions.js' // Server Action being called inside a Client Component export default function AddToCart({ ...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-2
Next.js integrates React Actions into the Next.js router, bundler, and caching system, including adding data mutation APIs like revalidateTag and revalidatePath. Convention You can enable Server Actions in your Next.js project by enabling the experimental serverActions flag. next.config.js module.exports = { experime...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-3
app/server-component.js export default function ServerComponent() { async function myAction() { 'use server' // ... } } With Client Components If you're using a Server Action inside a Client Component, create your action in a separate file with the "use server" directive at the top of the file. Then, import...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-4
</form> ) } Good to know: When using a top-level "use server" directive, all exports below will be considered Server Actions. You can have multiple Server Actions in a single file. Invocation You can invoke Server Actions using the following methods: Using action: React's action prop allows invoking a Server Action o...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-5
app/add-to-cart.js import { cookies } from 'next/headers' export default function AddToCart({ productId }) { async function addItem(data) { 'use server' const cartId = cookies().get('cartId')?.value await saveToDb({ cartId, data }) } return ( <form action={addItem}> <button type="submi...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-6
async function handleSubmit() { 'use server' // ... } async function submitImage() { 'use server' // ... } return ( <form action={handleSubmit}> <input type="text" name="name" /> <input type="image" formAction={submitImage} /> <button type="submit">Submit</button> <...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-7
Good to know: Using startTransition disables the out-of-the-box Progressive Enhancement. app/components/example-client-component.js 'use client' import { useTransition } from 'react' import { addItem } from '../actions' function ExampleClientComponent({ id }) { let [isPending, startTransition] = useTransition() ...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-8
app/posts/[id]/page.tsx import kv from '@vercel/kv' import LikeButton from './like-button' export default function Page({ params }: { params: { id: string } }) { async function increment() { 'use server' await kv.incr(`post:id:${params.id}`) } return <LikeButton increment={increment} /> } app/post/[id...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-9
</button> ) } Enhancements Experimental useOptimistic The experimental useOptimistic hook provides a way to implement optimistic updates in your application. Optimistic updates are a technique that enhances user experience by making the app appear more responsive. When a Server Action is invoked, the UI is updated im...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-10
) const formRef = useRef() return ( <div> {optimisticMessages.map((m) => ( <div> {m.message} {m.sending ? 'Sending...' : ''} </div> ))} <form action={async (formData) => { const message = formData.get('message') formRef.current....
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-11
app/form.js 'use client' import { experimental_useFormStatus as useFormStatus } from 'react-dom' function Submit() { const { pending } = useFormStatus() return ( <input type="submit" className={pending ? 'button-pending' : 'button-normal'} disabled={pending} > Submit </inpu...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-12
If a Client Action is passed to a <form>, the form is still interactive, but the action will be placed in a queue until the form has hydrated. The <form> is prioritized with Selective Hydration, so it happens quickly. app/components/example-client-component.js 'use client' import { useState } from 'react' import { ha...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-13
Size Limitation By default, the maximum size of the request body sent to a Server Action is 1MB. This prevents large amounts of data being sent to the server, which consumes a lot of server resource to parse. However, you can configure this limit using the experimental serverActionsBodySizeLimit option. It can take the...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-14
app/actions.js 'use server' export async function addItem() { // ... } app/components/example-client-component.js 'use client' import { useTransition } from 'react' import { addItem } from '../actions' function ExampleClientComponent({ id }) { let [isPending, startTransition] = useTransition() return ( ...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-15
app/components/example-server-component.js import { ExampleClientComponent } from './components/example-client-component.js' function ExampleServerComponent({ id }) { async function updateItem(data) { 'use server' modifyItem({ id, data }) } return <ExampleClientComponent updateItem={updateItem} /> } a...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-16
</form> ) } On-demand Revalidation Server Actions can be used to revalidate data on-demand by path (revalidatePath) or by cache tag (revalidateTag). import { revalidateTag } from 'next/cache' async function revalidate() { 'use server' revalidateTag('blog-posts') } Validation The data passed to a Server Action ...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-17
return async (formData) => { 'use server' const isValidData = verifyData(formData) if (!isValidData) { throw new Error('Invalid input.') } const data = process(formData) return action(data) } } Using headers You can read incoming request headers such as cookies and headers within a...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-18
'use server'; const cart = await createCart(): cookies().set('cartId', cart.id) // or cookies().set({ name: 'cartId', value: cart.id, httpOnly: true, path: '/' }) } Glossary Actions Actions are an experimental feature in React, allowing you to run async code in response to a user interaction...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
46ac516751e2-19
React also provides built-in solutions for optimistic updates with Actions. It's important to note new patterns are still being developed and new APIs may still be added. Form Actions Actions integrated into the web standard <form> API, and enable out-of-the-box progressive enhancement and loading states. Similar to th...
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
64d4e2b4532d-0
CSS Modules Next.js has built-in support for CSS Modules using the .module.css extension. CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same class name in different files without worrying about collisions. This behavior makes CSS Modules the ideal way to include...
https://nextjs.org/docs/app/building-your-application/styling/css-modules
64d4e2b4532d-1
Regular <link> stylesheets and global CSS files are still supported. In production, all CSS Module files will be automatically concatenated into many minified and code-split .css files. These .css files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application ...
https://nextjs.org/docs/app/building-your-application/styling/css-modules
64d4e2b4532d-2
import './global.css' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> ) } External Stylesheets Stylesheets published by external packages can be imported anywhere in the app directory, including colocate...
https://nextjs.org/docs/app/building-your-application/styling/css-modules
64d4e2b4532d-3
Additional Features Next.js includes additional features to improve the authoring experience of adding styles: When running locally with next dev, local stylesheets (either global or CSS modules) will take advantage of Fast Refresh to instantly reflect changes as edits are saved. When building for production with next ...
https://nextjs.org/docs/app/building-your-application/styling/css-modules
64e8c07c73bb-0
Tailwind CSS Tailwind CSS is a utility-first CSS framework that works exceptionally well with Next.js. Installing Tailwind Install the Tailwind CSS packages and run the init command to generate both the tailwind.config.js and postcss.config.js files: Terminal npm install -D tailwindcss postcss autoprefixer npx tailwind...
https://nextjs.org/docs/app/building-your-application/styling/tailwind-css
64e8c07c73bb-1
'./components/**/*.{js,ts,jsx,tsx,mdx}', // Or if using `src` directory: './src/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: {}, }, plugins: [], } You do not need to modify postcss.config.js. Importing Styles Add the Tailwind CSS directives that Tailwind will use to inject its generated styles t...
https://nextjs.org/docs/app/building-your-application/styling/tailwind-css
64e8c07c73bb-2
// These styles apply to every route in the application import './globals.css' export const metadata: Metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> ...
https://nextjs.org/docs/app/building-your-application/styling/tailwind-css
8945e7d1627d-0
CSS-in-JS Warning: CSS-in-JS libraries which require runtime JavaScript are not currently supported in Server Components. Using CSS-in-JS with newer React features like Server Components and Streaming requires library authors to support the latest version of React, including concurrent rendering. We're working with the...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-1
If you want to style Server Components, we recommend using CSS Modules or other solutions that output CSS files, like PostCSS or Tailwind CSS.Configuring CSS-in-JS in app Configuring CSS-in-JS is a three-step opt-in process that involves: A style registry to collect all CSS rules in a render. The new useServerInsertedH...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-2
export default function StyledJsxRegistry({ children, }: { children: React.ReactNode }) { // Only create stylesheet once with lazy initial state // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [jsxStyleRegistry] = useState(() => createStyleRegistry()) useServerInsertedHTML...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-3
}) { return ( <html> <body> <StyledJsxRegistry>{children}</StyledJsxRegistry> </body> </html> ) }View an example here.Styled Components Below is an example of how to configure styled-components@v6.0.0-rc.1 or greater:First, use the styled-components API to create a global registry compon...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-4
export default function StyledComponentsRegistry({ children, }: { children: React.ReactNode }) { // Only create stylesheet once with lazy initial state // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet()) use...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-5
export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html> <body> <StyledComponentsRegistry>{children}</StyledComponentsRegistry> </body> </html> ) }View an example here. Good to know: During server rendering, styles will be extracted to a glob...
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
8945e7d1627d-6
We specifically use a Client Component at the top level of the tree for the style registry because it's more efficient to extract CSS rules this way. It avoids re-generating styles on subsequent server renders, and prevents them from being sent in the Server Component payload.
https://nextjs.org/docs/app/building-your-application/styling/css-in-js
af7a2f69c782-0
Sass Next.js has built-in support for Sass using both the .scss and .sass extensions. You can use component-level Sass via CSS Modules and the .module.scssor .module.sass extension. First, install sass: Terminal npm install --save-dev sass Good to know: Sass supports two different syntax, each with their own extension....
https://nextjs.org/docs/app/building-your-application/styling/sass
af7a2f69c782-1
module.exports = { sassOptions: { includePaths: [path.join(__dirname, 'styles')], }, } Sass Variables Next.js supports Sass variables exported from CSS Module files. For example, using the exported primaryColor Sass variable: app/variables.module.scss $primary-color: #64ff00; :export { primaryColor: $primar...
https://nextjs.org/docs/app/building-your-application/styling/sass
f6dc9a7dd197-0
Image Optimization Examples Image Component According to Web Almanac, images account for a huge portion of the typical website’s page weight and can have a sizable impact on your website's LCP performance. The Next.js Image component extends the HTML <img> element with features for automatic image optimization: Size Op...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-1
You can then define the src for your image (either local or remote). Local Images To use a local image, import your .jpg, .png, or .webp image files. Next.js will automatically determine the width and height of your image based on the imported file. These values are used to prevent Cumulative Layout Shift while your im...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-2
/> ) } Warning: Dynamic await import() or require() are not supported. The import must be static so it can be analyzed at build time. Remote Images To use a remote image, the src property should be a URL string. Since Next.js does not have access to remote files during the build process, you'll need to provide the wi...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-3
width={500} height={500} /> ) } To safely allow optimizing images, define a list of supported URL patterns in next.config.js. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket: next.config.js module.exports = ...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-4
Domains Sometimes you may want to optimize a remote image, but still use the built-in Next.js Image Optimization API. To do this, leave the loader at its default setting and enter an absolute URL for the Image src prop. To protect your application from malicious users, you must define a list of remote hostnames you int...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-5
The default loader for Next.js applications uses the built-in Image Optimization API, which optimizes images from anywhere on the web, and then serves them directly from the Next.js web server. If you would like to serve your images directly from a CDN or image server, you can write your own loader function with a few ...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-6
The LCP element is typically the largest image or text block visible within the viewport of the page. When you run next dev, you'll see a console warning if the LCP element is an <Image> without the priority property. Once you've identified the LCP image, you can add the property like this: app/page.js import Image fro...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-7
} See more about priority in the next/image component documentation. Image Sizing One of the ways that images most commonly hurt performance is through layout shift, where the image pushes other elements around on the page as it loads in. This performance problem is so annoying to users that it has its own Core Web Vit...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-8
What if I don't know the size of my images? If you are accessing images from a source without knowledge of the images' sizes, there are several things you can do: Use fill The fill prop allows your image to be sized by its parent element. Consider using CSS to give the image's parent element space on the page along siz...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-9
If none of the suggested methods works for sizing your images, the next/image component is designed to work well on a page alongside standard <img> elements. Styling Styling the Image component is similar to styling a normal <img> element, but there are a few guidelines to keep in mind: Use className or style, not styl...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-10
This is the default for <div> elements but should be specified otherwise. Examples Responsive import Image from 'next/image' import mountains from '../public/mountains.jpg' export default function Responsive() { return ( <div style={{ display: 'flex', flexDirection: 'column' }}> <Image alt="Mount...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-11
export default function Fill() { return ( <div style={{ display: 'grid', gridGap: '8px', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))', }} > <div style={{ position: 'relative', height: '400px' }}> <Image alt="Mountains" src={...
https://nextjs.org/docs/app/building-your-application/optimizing/images
f6dc9a7dd197-12
import mountains from '../public/mountains.jpg' export default function Background() { return ( <Image alt="Mountains" src={mountains} placeholder="blur" quality={100} fill sizes="100vw" style={{ objectFit: 'cover', }} /> ) } For examples of the Imag...
https://nextjs.org/docs/app/building-your-application/optimizing/images
43a365f70a81-0
Font Optimization next/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance. 🎥 Watch: Learn more about how to use next/font → YouTube (6 minutes). next/font includes built-in automatic self-hosting for any font file. This means y...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-1
Get started by importing the font you would like to use from next/font/google as a function. We recommend using variable fonts for the best performance and flexibility. app/layout.tsx import { Inter } from 'next/font/google' // If loading a variable font, you don't need to specify the font weight const inter = Inter(...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-2
const roboto = Roboto({ weight: '400', subsets: ['latin'], display: 'swap', }) export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en" className={roboto.className}> <body>{children}</body> </html> ) } You can specify multiple weights and/...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-3
Specifying a subset Google Fonts are automatically subset. This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while preload is true will result in a warning. This can be done by adding it to the function call:...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-4
subsets: ['latin'], display: 'swap', }) export const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', }) app/layout.tsx import { inter } from './fonts' export default function Layout({ children }: { children: React.ReactNode }) { return ( <html lang="en" className={inter.className}> ...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-5
</> ) } In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed. Alternatively, you can create a CSS variable and use it with your preferred CSS solution: app/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google' import styles from './global.css' const ...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-6
children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body> <h1>My App</h1> <div>{children}</div> </body> </html> ) } app/global.css html { font-family: var(--font-inter); } h1 { font-family: var(-...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-7
Local Fonts Import next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility. app/layout.tsx import localFont from 'next/font/local' // Font files can be colocated inside of `app` const myFont = localFont({ src: './my-font.woff2', displ...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-8
src: [ { path: './Roboto-Regular.woff2', weight: '400', style: 'normal', }, { path: './Roboto-Italic.woff2', weight: '400', style: 'italic', }, { path: './Roboto-Bold.woff2', weight: '700', style: 'normal', }, { path: './Roboto-Bold...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-9
With Tailwind CSS next/font can be used with Tailwind CSS through a CSS variable. In the example below, we use the font Inter from next/font/google (you can use any font from Google or Local Fonts). Load your font with the variable option to define your CSS variable name and assign it to inter. Then, use inter.variable...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-10
children, }: { children: React.ReactNode }) { return ( <html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}> <body>{children}</body> </html> ) } Finally, add the CSS variable to your Tailwind CSS config: tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-11
}, }, }, plugins: [], } You can now use the font-sans and font-mono utility classes to apply the font to your elements. Preloading When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on th...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
43a365f70a81-12
If it's the root layout, it is preloaded on all routes. Reusing fonts Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it...
https://nextjs.org/docs/app/building-your-application/optimizing/fonts
995394ed8592-0
Script Optimization Layout Scripts To load a third-party script for multiple routes, import next/script and include the script directly in your layout component:app/dashboard/layout.tsx import Script from 'next/script' export default function DashboardLayout({ children, }: { children: React.ReactNode }) { retur...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-1
Application Scripts To load a third-party script for all routes, import next/script and include the script directly in your root layout:app/layout.tsx import Script from 'next/script' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{ch...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-2
Strategy Although the default behavior of next/script allows you load third-party scripts in any page or layout, you can fine-tune its loading behavior by using the strategy property: beforeInteractive: Load the script before any Next.js code and before any page hydration occurs. afterInteractive: (default) Load the sc...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-3
This strategy is still experimental and can only be used if the nextScriptWorkers flag is enabled in next.config.js: next.config.js module.exports = { experimental: { nextScriptWorkers: true, }, } Then, run next (normally npm run dev or yarn dev) and Next.js will guide you through the installation of the requir...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-4
</> ) } There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's tradeoffs documentation for more information. Inline Scripts Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can b...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-5
Executing Additional Code Event handlers can be used with the Script component to execute additional code after a certain event occurs: onLoad: Execute code after the script has finished loading. onReady: Execute code after the script has finished loading and every time the component is mounted. onError: Execute code i...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts
995394ed8592-6
}Refer to the next/script API reference to learn more about each event handler and view examples. Additional Attributes There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will autom...
https://nextjs.org/docs/app/building-your-application/optimizing/scripts