{"id": "47cb3dfffc9e-0", "text": "Defining Routes\nWe recommend reading the Routing Fundamentals page before continuing.\nThis page will guide you through how to define and organize routes in your Next.js application.\nCreating Routes\nNext.js uses a file-system based router where folders are used to define routes.\nEach folder represents a route segment that maps to a URL segment. To create a nested route, you can nest folders inside each other.\nA special page.js file is used to make route segments publicly accessible.\nIn this example, the /dashboard/analytics URL path is not publicly accessible because it does not have a corresponding page.js file. This folder could be used to store components, stylesheets, images, or other colocated files.\nGood to know: .js, .jsx, or .tsx file extensions can be used for special files.\nCreating UI", "source": "https://nextjs.org/docs/app/building-your-application/routing/defining-routes"} {"id": "47cb3dfffc9e-1", "text": "Creating UI\nSpecial file conventions are used to create UI for each route segment. The most common are pages to show UI unique to a route, and layouts to show UI that is shared across multiple routes.\nFor example, to create your first page, add a page.js file inside the app directory and export a React component:\napp/page.tsx export default function Page() {\n return

Hello, Next.js!

\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/defining-routes"} {"id": "53efeaec8ff7-0", "text": "Pages and Layouts\nWe recommend reading the Routing Fundamentals and Defining Routes pages before continuing.\nThe App Router inside Next.js 13 introduced new file conventions to easily create pages, shared layouts, and templates. This page will guide you through how to use these special files in your Next.js application.\nPages\nA page is UI that is unique to a route. You can define pages by exporting a component from a page.js file. Use nested folders to define a route and a page.js file to make the route publicly accessible.\nCreate your first page by adding a page.js file inside the app directory:\napp/page.tsx // `app/page.tsx` is the UI for the `/` URL\nexport default function Page() {\n return

Hello, Home page!

\n}\napp/dashboard/page.tsx // `app/dashboard/page.tsx` is the UI for the `/dashboard` URL\nexport default function Page() {", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-1", "text": "export default function Page() {\n return

Hello, Dashboard Page!

\n}\nGood to know:\nA page is always the leaf of the route subtree.\n.js, .jsx, or .tsx file extensions can be used for Pages.\nA page.js file is required to make a route segment publicly accessible.\nPages are Server Components by default but can be set to a Client Component.\nPages can fetch data. View the Data Fetching section for more information.\nLayouts\nA layout is UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.\nYou can define a layout by default exporting a React component from a layout.js file. The component should accept a children prop that will be populated with a child layout (if it exists) or a child page during rendering.\napp/dashboard/layout.tsx export default function DashboardLayout({", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-2", "text": "app/dashboard/layout.tsx export default function DashboardLayout({\n children, // will be a page or nested layout\n}: {\n children: React.ReactNode\n}) {\n return (\n
\n {/* Include shared UI here e.g. a header or sidebar */}\n \n \n {children}\n
\n )\n}\nGood to know:\nThe top-most layout is called the Root Layout. This required layout is shared across all pages in an application. Root layouts must contain html and body tags.\nAny route segment can optionally define its own Layout. These layouts will be shared across all pages in that segment.\nLayouts in a route are nested by default. Each parent layout wraps child layouts below it using the React children prop.\nYou can use Route Groups to opt specific route segments in and out of shared layouts.", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-3", "text": "You can use Route Groups to opt specific route segments in and out of shared layouts.\nLayouts are Server Components by default but can be set to a Client Component.\nLayouts can fetch data. View the Data Fetching section for more information.\nPassing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will automatically dedupe the requests without affecting performance.\nLayouts do not have access to the current route segment(s). To access route segments, you can use useSelectedLayoutSegment or useSelectedLayoutSegments in a Client Component.\n.js, .jsx, or .tsx file extensions can be used for Layouts.\nA layout.js and page.js file can be defined in the same folder. The layout will wrap the page.\nRoot Layout (Required)", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-4", "text": "Root Layout (Required)\nThe root layout is defined at the top level of the app directory and applies to all routes. This layout enables you to modify the initial HTML returned from the server.\napp/layout.tsx export default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nGood to know:\nThe app directory must include a root layout.\nThe root layout must define and tags since Next.js does not automatically create them.\nYou can use the built-in SEO support to manage HTML elements, for example, the element.\nYou can use route groups to create multiple root layouts. See an example here.\nThe root layout is a Server Component by default and can not be set to a Client Component.", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-5", "text": "The root layout is a Server Component by default and can not be set to a Client Component.\nMigrating from the pages directory: The root layout replaces the _app.js and _document.js files. View the migration guide.\nNesting Layouts\nLayouts defined inside a folder (e.g. app/dashboard/layout.js) apply to specific route segments (e.g. acme.com/dashboard) and render when those segments are active. By default, layouts in the file hierarchy are nested, which means they wrap child layouts via their children prop.\napp/dashboard/layout.tsx export default function DashboardLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return <section>{children}</section>\n}\nGood to know:\nOnly the root layout can contain <html> and <body> tags.", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-6", "text": "Only the root layout can contain <html> and <body> tags.\nIf you were to combine the two layouts above, the root layout (app/layout.js) would wrap the dashboard layout (app/dashboard/layout.js), which would wrap route segments inside app/dashboard/*.\nThe two layouts would be nested as such:\nYou can use Route Groups to opt specific route segments in and out of shared layouts.\nTemplates\nTemplates are similar to layouts in that they wrap each child layout or page. Unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is not preserved, and effects are re-synchronized.\nThere may be cases where you need those specific behaviors, and templates would be a more suitable option than layouts. For example:", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-7", "text": "Enter/exit animations using CSS or animation libraries.\nFeatures that rely on useEffect (e.g logging page views) and useState (e.g a per-page feedback form).\nTo change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.\nRecommendation: We recommend using Layouts unless you have a specific reason to use Template.\nA template can be defined by exporting a default React component from a template.js file. The component should accept a children prop which will be nested segments.\napp/template.tsx export default function Template({ children }: { children: React.ReactNode }) {\n return <div>{children}</div>\n}\nThe rendered output of a route segment with a layout and a template will be as such:\nOutput <Layout>\n {/* Note that the template is given a unique key. */}", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-8", "text": "Output <Layout>\n {/* Note that the template is given a unique key. */}\n <Template key={routeParam}>{children}</Template>\n</Layout>\nModifying <head>\nIn the app directory, you can modify the <head> HTML elements such as title and meta using the built-in SEO support.\nMetadata can be defined by exporting a metadata object or generateMetadata function in a layout.js or page.js file.\napp/page.tsx import { Metadata } from 'next'\n \nexport const metadata: Metadata = {\n title: 'Next.js',\n}\n \nexport default function Page() {\n return '...'\n}\nGood to know: You should not manually add <head> tags such as <title> and <meta> to root layouts. Instead, you should use the Metadata API which automatically handles advanced requirements such as streaming and de-duplicating <head> elements.", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "53efeaec8ff7-9", "text": "Learn more about available metadata options in the API reference.", "source": "https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts"} {"id": "7259cc670011-0", "text": "Linking and NavigatingThe Next.js router uses server-centric routing with client-side navigation. It supports instant loading states and concurrent rendering. This means navigation maintains client-side state, avoids expensive re-renders, is interruptible, and doesn't cause race conditions.\nThere are two ways to navigate between routes:\n<Link> Component\nuseRouter Hook\nThis page will go through how to use <Link>, useRouter(), and dive deeper into how navigation works.\n<Link> Component\n<Link> is a React component that extends the HTML <a> element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.\nTo use <Link>, import it from next/link, and pass a href prop to the component:\napp/page.tsx import Link from 'next/link'\n \nexport default function Page() {\n return <Link href=\"/dashboard\">Dashboard</Link>\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-1", "text": "return <Link href=\"/dashboard\">Dashboard</Link>\n}\nThere are optional props you can pass to <Link>. See the API reference for more information.\nExamples\nLinking to Dynamic Segments\nWhen linking to dynamic segments, you can use template literals and interpolation to generate a list of links. For example, to generate a list of blog posts:\napp/blog/PostList.js import Link from 'next/link'\n \nexport default function PostList({ posts }) {\n return (\n <ul>\n {posts.map((post) => (\n <li key={post.id}>\n <Link href={`/blog/${post.slug}`}>{post.title}</Link>\n </li>\n ))}\n </ul>\n )\n}\nChecking Active Links", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-2", "text": "))}\n </ul>\n )\n}\nChecking Active Links\nYou can use usePathname() to determine if a link is active. For example, to add a class to the active link, you can check if the current pathname matches the href of the link:\napp/ui/Navigation.js 'use client'\n \nimport { usePathname } from 'next/navigation'\nimport Link from 'next/link'\n \nexport function Navigation({ navLinks }) {\n const pathname = usePathname()\n \n return (\n <>\n {navLinks.map((link) => {\n const isActive = pathname.startsWith(link.href)\n \n return (\n <Link\n className={isActive ? 'text-blue' : 'text-black'}\n href={link.href}\n key={link.name}\n >\n {link.name}\n </Link>\n )", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-3", "text": ">\n {link.name}\n </Link>\n )\n })}\n </>\n )\n}\nScrolling to an id\nThe default behavior of <Link> is to scroll to the top of the route segment that has changed. When there is an id defined in href, it will scroll to the specific id, similarly to a normal <a> tag.\nuseRouter() Hook\nThe useRouter hook allows you to programmatically change routes inside Client Components.\nTo use useRouter, import it from next/navigation, and call the hook inside your Client Component:\napp/page.js 'use client'\n \nimport { useRouter } from 'next/navigation'\n \nexport default function Page() {\n const router = useRouter()\n \n return (\n <button type=\"button\" onClick={() => router.push('/dashboard')}>\n Dashboard\n </button>\n )\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-4", "text": "Dashboard\n </button>\n )\n}\nThe useRouter provides methods such as push(), refresh(), and more. See the API reference for more information.\nRecommendation: Use the <Link> component to navigate between routes unless you have a specific requirement for using useRouter.\nHow Navigation Works\nA route transition is initiated using <Link> or calling router.push().\nThe router updates the URL in the browser's address bar.\nThe router avoids unnecessary work by re-using segments that haven't changed (e.g. shared layouts) from the client-side cache. This is also referred to as partial rendering.\nIf the conditions of soft navigation are met, the router fetches the new segment from the cache rather than the server. If not, the router performs a hard navigation and fetches the Server Component payload from the server.\nIf created, loading UI is shown from the server while the payload is being fetched.", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-5", "text": "If created, loading UI is shown from the server while the payload is being fetched.\nThe router uses the cached or fresh payload to render the new segments on the client.\nClient-side Caching of Rendered Server Components\nGood to know: This client-side cache is different from the server-side Next.js HTTP cache.\nThe new router has an in-memory client-side cache that stores the rendered result of Server Components (payload). The cache is split by route segments which allows invalidation at any level and ensures consistency across concurrent renders.\nAs users navigate around the app, the router will store the payload of previously fetched segments and prefetched segments in the cache.\nThis means, for certain cases, the router can re-use the cache instead of making a new request to the server. This improves performance by avoiding re-fetching data and re-rendering components unnecessarily.\nInvalidating the Cache", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-6", "text": "Invalidating the Cache\nServer Actions can be used to revalidate data on-demand by path (revalidatePath) or by cache tag (revalidateTag).\nPrefetching\nPrefetching is a way to preload a route in the background before it's visited. The rendered result of prefetched routes is added to the router's client-side cache. This makes navigating to a prefetched route near-instant.\nBy default, routes are prefetched as they become visible in the viewport when using the <Link> component. This can happen when the page first loads or through scrolling. Routes can also be programmatically prefetched using the prefetch method of the useRouter() hook.\nStatic and Dynamic Routes:\nIf the route is static, all the Server Component payloads for the route segments will be prefetched.", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-7", "text": "If the route is dynamic, the payload from the first shared layout down until the first loading.js file is prefetched. This reduces the cost of prefetching the whole route dynamically and allows instant loading states for dynamic routes.\nGood to know:\nPrefetching is only enabled in production.\nPrefetching can be disabled by passing prefetch={false} to <Link>.\nSoft Navigation\nOn navigation, the cache for changed segments is reused (if it exists), and no new requests are made to the server for data.\nConditions for Soft Navigation\nOn navigation, Next.js will use soft navigation if the route you are navigating to has been prefetched, and either doesn't include dynamic segments or has the same dynamic parameters as the current route.\nFor example, consider the following route that includes a dynamic [team] segment: /dashboard/[team]/*. The cached segments below /dashboard/[team]/* will only be invalidated when the [team] parameter changes.", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "7259cc670011-8", "text": "Navigating from /dashboard/team-red/* to /dashboard/team-red/* will be a soft navigation.\nNavigating from /dashboard/team-red/* to /dashboard/team-blue/* will be a hard navigation.\nHard Navigation\nOn navigation, the cache is invalidated and the server refetches data and re-renders the changed segments.\nBack/Forward Navigation\nBack and forward navigation (popstate event) has a soft navigation behavior. This means, the client-side cache is re-used and navigation is near-instant.\nFocus and Scroll Management\nBy default, Next.js will set focus and scroll into view the segment that's changed on navigation.", "source": "https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating"} {"id": "34bf98e60183-0", "text": "Route GroupsIn the app directory, nested folders are normally mapped to URL paths. However, you can mark a folder as a Route Group to prevent the folder from being included in the route's URL path.\nThis allows you to organize your route segments and project files into logical groups without affecting the URL path structure.\nRoute groups are useful for:\nOrganizing routes into groups e.g. by site section, intent, or team.\nEnabling nested layouts in the same route segment level:\nCreating multiple nested layouts in the same segment, including multiple root layouts\nAdding a layout to a subset of routes in a common segment\nConvention\nA route group can be created by wrapping a folder's name in parenthesis: (folderName)\nExamples\nOrganize routes without affecting the URL path\nTo organize routes without affecting the URL, create a group to keep related routes together. The folders in parenthesis will be omitted from the URL (e.g. (marketing) or (shop)).", "source": "https://nextjs.org/docs/app/building-your-application/routing/route-groups"} {"id": "34bf98e60183-1", "text": "Even though routes inside (marketing) and (shop) share the same URL hierarchy, you can create a different layout for each group by adding a layout.js file inside their folders.\nOpting specific segments into a layout\nTo opt specific routes into a layout, create a new route group (e.g. (shop)) and move the routes that share the same layout into the group (e.g. account and cart). The routes outside of the group will not share the layout (e.g. checkout).\nCreating multiple root layouts\nTo create multiple root layouts, remove the top-level layout.js file, and add a layout.js file inside each route groups. This is useful for partitioning an application into sections that have a completely different UI or experience. The <html> and <body> tags need to be added to each root layout.\nIn the example above, both (marketing) and (shop) have their own root layout.\nGood to know:", "source": "https://nextjs.org/docs/app/building-your-application/routing/route-groups"} {"id": "34bf98e60183-2", "text": "Good to know:\nThe naming of route groups has no special significance other than for organization. They do not affect the URL path.\nRoutes that include a route group should not resolve to the same URL path as other routes. For example, since route groups don't affect URL structure, (marketing)/about/page.js and (shop)/about/page.js would both resolve to /about and cause an error.\nIf you use multiple root layouts without a top-level layout.js file, your home page.js file should be defined in one of the route groups, For example: app/(marketing)/page.js.\nNavigating across multiple root layouts will cause a full page load (as opposed to a client-side navigation). For example, navigating from /cart that uses app/(shop)/layout.js to /blog that uses app/(marketing)/layout.js will cause a full page load. This only applies to multiple root layouts.", "source": "https://nextjs.org/docs/app/building-your-application/routing/route-groups"} {"id": "45cae5895537-0", "text": "Dynamic RoutesWhen you don't know the exact segment names ahead of time and want to create routes from dynamic data, you can use Dynamic Segments that are filled in at request time or prerendered at build time.\nConvention\nA Dynamic Segment can be created by wrapping a folder's name in square brackets: [folderName]. For example, [id] or [slug].\nDynamic Segments are passed as the params prop to layout, page, route, and generateMetadata functions.\nExample\nFor example, a blog could include the following route app/blog/[slug]/page.js where [slug] is the Dynamic Segment for blog posts.\napp/blog/[slug]/page.tsx export default function Page({ params }: { params: { slug: string } }) {\n return <div>My Post: {params.slug}</div>\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "45cae5895537-1", "text": "return <div>My Post: {params.slug}</div>\n}\nRouteExample URLparamsapp/blog/[slug]/page.js/blog/a{ slug: 'a' }app/blog/[slug]/page.js/blog/b{ slug: 'b' }app/blog/[slug]/page.js/blog/c{ slug: 'c' }\nSee the generateStaticParams() page to learn how to generate the params for the segment.\nGood to know: Dynamic Segments are equivalent to Dynamic Routes in the pages directory.\nGenerating Static Params\nThe generateStaticParams function can be used in combination with dynamic route segments to statically generate routes at build time instead of on-demand at request time.\napp/blog/[slug]/page.tsx export async function generateStaticParams() {\n const posts = await fetch('https://.../posts').then((res) => res.json())\n \n return posts.map((post) => ({\n slug: post.slug,", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "45cae5895537-2", "text": "return posts.map((post) => ({\n slug: post.slug,\n }))\n}\nThe primary benefit of the generateStaticParams function is its smart retrieval of data. If content is fetched within the generateStaticParams function using a fetch request, the requests are automatically deduplicated. This means a fetch request with the same arguments across multiple generateStaticParams, Layouts, and Pages will only be made once, which decreases build times.\nUse the migration guide if you are migrating from the pages directory.\nSee generateStaticParams server function documentation for more information and advanced use cases.\nCatch-all Segments\nDynamic Segments can be extended to catch-all subsequent segments by adding an ellipsis inside the brackets [...folderName].\nFor example, app/shop/[...slug]/page.js will match /shop/clothes, but also /shop/clothes/tops, /shop/clothes/tops/t-shirts, and so on.", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "45cae5895537-3", "text": "RouteExample URLparamsapp/shop/[...slug]/page.js/shop/a{ slug: ['a'] }app/shop/[...slug]/page.js/shop/a/b{ slug: ['a', 'b'] }app/shop/[...slug]/page.js/shop/a/b/c{ slug: ['a', 'b', 'c'] }\nOptional Catch-all Segments\nCatch-all Segments can be made optional by including the parameter in double square brackets: [[...folderName]].\nFor example, app/shop/[[...slug]]/page.js will also match /shop, in addition to /shop/clothes, /shop/clothes/tops, /shop/clothes/tops/t-shirts.\nThe difference between catch-all and optional catch-all segments is that with optional, the route without the parameter is also matched (/shop in the example above).", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "45cae5895537-4", "text": "RouteExample URLparamsapp/shop/[[...slug]]/page.js/shop{}app/shop/[[...slug]]/page.js/shop/a{ slug: ['a'] }app/shop/[[...slug]]/page.js/shop/a/b{ slug: ['a', 'b'] }app/shop/[[...slug]]/page.js/shop/a/b/c{ slug: ['a', 'b', 'c'] }\nTypeScript\nWhen using TypeScript, you can add types for params depending on your configured route segment.\napp/blog/[slug]/page.tsx export default function Page({ params }: { params: { slug: string } }) {\n return <h1>My Page</h1>\n}\nRouteparams Type Definitionapp/blog/[slug]/page.js{ slug: string }app/shop/[...slug]/page.js{ slug: string[] }app/[categoryId]/[itemId]/page.js{ categoryId: string, itemId: string }", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "45cae5895537-5", "text": "Good to know: This may be done automatically by the TypeScript plugin in the future.", "source": "https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes"} {"id": "4cb9ccf64b03-0", "text": "Loading UI and StreamingThe special file loading.js helps you create meaningful Loading UI with React Suspense. With this convention, you can show an instant loading state from the server while the content of a route segment loads. The new content is automatically swapped in once rendering is complete.\nInstant Loading States\nAn instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience.\nCreate a loading state by adding a loading.js file inside a folder.\napp/dashboard/loading.tsx export default function Loading() {\n // You can add any UI inside Loading, including a Skeleton.\n return <LoadingSkeleton />\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "4cb9ccf64b03-1", "text": "return <LoadingSkeleton />\n}\nIn the same folder, loading.js will be nested inside layout.js. It will automatically wrap the page.js file and any children below in a <Suspense> boundary.\nGood to know:\nNavigation is immediate, even with server-centric routing.\nNavigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route.\nShared layouts remain interactive while new route segments load.\nRecommendation: Use the loading.js convention for route segments (layouts and pages) as Next.js optimizes this functionality.\nStreaming with Suspense\nIn addition to loading.js, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with Suspense for both Node.js and Edge runtimes.\nWhat is Streaming?", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "4cb9ccf64b03-2", "text": "What is Streaming?\nTo learn how Streaming works in React and Next.js, it's helpful to understand Server-Side Rendering (SSR) and its limitations.\nWith SSR, there's a series of steps that need to be completed before a user can see and interact with a page:\nFirst, all data for a given page is fetched on the server.\nThe server then renders the HTML for the page.\nThe HTML, CSS, and JavaScript for the page are sent to the client.\nA non-interactive user interface is shown using the generated HTML, and CSS.\nFinally, React hydrates the user interface to make it interactive.\nThese steps are sequential and blocking, meaning the server can only render the HTML for a page once all the data has been fetched. And, on the client, React can only hydrate the UI once the code for all components in the page has been downloaded.", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "4cb9ccf64b03-3", "text": "SSR with React and Next.js helps improve the perceived loading performance by showing a non-interactive page to the user as soon as possible.\nHowever, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user.\nStreaming allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client.\nThis enables parts of the page to be displayed sooner, without waiting for all the data to load before any UI can be rendered.\nStreaming works well with React's component model because each component can be considered a chunk. Components that have higher priority (e.g. product information) or that don't rely on data can be sent first (e.g. layout), and React can start hydration earlier. Components that have lower priority (e.g. reviews, related products) can be sent in the same server request after their data has been fetched.", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "4cb9ccf64b03-4", "text": "Streaming is particularly beneficial when you want to prevent long data requests from blocking the page from rendering as it can reduce the Time To First Byte (TTFB) and First Contentful Paint (FCP). It also helps improve Time to Interactive (TTI), especially on slower devices.\nExample\n<Suspense> works by wrapping a component that performs an asynchronous action (e.g. fetch data), showing fallback UI (e.g. skeleton, spinner) while it's happening, and then swapping in your component once the action completes.\napp/dashboard/page.tsx import { Suspense } from 'react'\nimport { PostFeed, Weather } from './Components'\n \nexport default function Posts() {\n return (\n <section>\n <Suspense fallback={<p>Loading feed...</p>}>\n <PostFeed />\n </Suspense>\n <Suspense fallback={<p>Loading weather...</p>}>\n <Weather />", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "4cb9ccf64b03-5", "text": "<Suspense fallback={<p>Loading weather...</p>}>\n <Weather />\n </Suspense>\n </section>\n )\n}\nBy using Suspense, you get the benefits of:\nStreaming Server Rendering - Progressively rendering HTML from the server to the client.\nSelective Hydration - React prioritizes what components to make interactive first based on user interaction.\nFor more Suspense examples and use cases, please see the React Documentation.\nSEO\nNext.js will wait for data fetching inside generateMetadata to complete before streaming UI to the client. This guarantees the first part of a streamed response includes <head> tags.\nSince streaming is server-rendered, it does not impact SEO. You can use the Mobile Friendly Test tool from Google to see how your page appears to Google's web crawlers and view the serialized HTML (source).", "source": "https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"} {"id": "5829a47ac78e-0", "text": "Error HandlingThe error.js file convention allows you to gracefully handle unexpected runtime errors in nested routes.\nAutomatically wrap a route segment and its nested children in a React Error Boundary.\nCreate error UI tailored to specific segments using the file-system hierarchy to adjust granularity.\nIsolate errors to affected segments while keeping the rest of the application functional.\nAdd functionality to attempt to recover from an error without a full page reload.\nCreate error UI by adding an error.js file inside a route segment and exporting a React component:\napp/dashboard/error.tsx 'use client' // Error components must be Client Components\n \nimport { useEffect } from 'react'\n \nexport default function Error({\n error,\n reset,\n}: {\n error: Error\n reset: () => void\n}) {\n useEffect(() => {\n // Log the error to an error reporting service\n console.error(error)\n }, [error])", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-1", "text": "console.error(error)\n }, [error])\n \n return (\n <div>\n <h2>Something went wrong!</h2>\n <button\n onClick={\n // Attempt to recover by trying to re-render the segment\n () => reset()\n }\n >\n Try again\n </button>\n </div>\n )\n}\nHow error.js Works\nerror.js automatically creates an React Error Boundary that wraps a nested child segment or page.js component.\nThe React component exported from the error.js file is used as the fallback component.\nIf an error is thrown within the error boundary, the error is contained, and the fallback component is rendered.\nWhen the fallback error component is active, layouts above the error boundary maintain their state and remain interactive, and the error component can display functionality to recover from the error.\nRecovering From Errors", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-2", "text": "Recovering From Errors\nThe cause of an error can sometimes be temporary. In these cases, simply trying again might resolve the issue.\nAn error component can use the reset() function to prompt the user to attempt to recover from the error. When executed, the function will try to re-render the Error boundary's contents. If successful, the fallback error component is replaced with the result of the re-render.\napp/dashboard/error.tsx 'use client'\n \nexport default function Error({\n error,\n reset,\n}: {\n error: Error\n reset: () => void\n}) {\n return (\n <div>\n <h2>Something went wrong!</h2>\n <button onClick={() => reset()}>Try again</button>\n </div>\n )\n}\nNested Routes\nReact components created through special files are rendered in a specific nested hierarchy.", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-3", "text": "}\nNested Routes\nReact components created through special files are rendered in a specific nested hierarchy.\nFor example, a nested route with two segments that both include layout.js and error.js files are rendered in the following simplified component hierarchy:\nThe nested component hierarchy has implications for the behavior of error.js files across a nested route:\nErrors bubble up to the nearest parent error boundary. This means an error.js file will handle errors for all its nested child segments. More or less granular error UI can be achieved by placing error.js files at different levels in the nested folders of a route.\nAn error.js boundary will not handle errors thrown in a layout.js component in the same segment because the error boundary is nested inside that layouts component.\nHandling Errors in Layouts", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-4", "text": "Handling Errors in Layouts\nerror.js boundaries do not catch errors thrown in layout.js or template.js components of the same segment. This intentional hierarchy keeps important UI that is shared between sibling routes (such as navigation) visible and functional when an error occurs.\nTo handle errors within a specific layout or template, place an error.js file in the layouts parent segment.\nTo handle errors within the root layout or template, use a variation of error.js called global-error.js.\nHandling Errors in Root Layouts\nThe root app/error.js boundary does not catch errors thrown in the root app/layout.js or app/template.js component.\nTo specifically handle errors in these root components, use a variation of error.js called app/global-error.js located in the root app directory.", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-5", "text": "Unlike the root error.js, the global-error.js error boundary wraps the entire application, and its fallback component replaces the root layout when active. Because of this, it is important to note that global-error.js must define its own <html> and <body> tags.\nglobal-error.js is the least granular error UI and can be considered \"catch-all\" error handling for the whole application. It is unlikely to be triggered often as root components are typically less dynamic, and other error.js boundaries will catch most errors.\nEven if a global-error.js is defined, it is still recommended to define a root error.js whose fallback component will be rendered within the root layout, which includes globally shared UI and branding.\napp/global-error.tsx 'use client'\n \nexport default function GlobalError({\n error,\n reset,\n}: {\n error: Error\n reset: () => void\n}) {\n return (\n <html>", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-6", "text": "reset: () => void\n}) {\n return (\n <html>\n <body>\n <h2>Something went wrong!</h2>\n <button onClick={() => reset()}>Try again</button>\n </body>\n </html>\n )\n}\nHandling Server Errors\nIf an error is thrown inside a Server Component, Next.js will forward an Error object (stripped of sensitive error information in production) to the nearest error.js file as the error prop.\nSecuring Sensitive Error Information\nDuring production, the Error object forwarded to the client only includes a generic message and digest property.\nThis is a security precaution to avoid leaking potentially sensitive details included in the error to the client.\nThe message property contains a generic message about the error and the digest property contains an automatically generated hash of the error that can be used to match the corresponding error in server-side logs.", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "5829a47ac78e-7", "text": "During development, the Error object forwarded to the client will be serialized and include the message of the original error for easier debugging.", "source": "https://nextjs.org/docs/app/building-your-application/routing/error-handling"} {"id": "04c394e53e49-0", "text": "Parallel RoutesParallel Routing allows you to simultaneously or conditionally render one or more pages in the same layout. For highly dynamic sections of an app, such as dashboards and feeds on social sites, Parallel Routing can be used to implement complex routing patterns.\nFor example, you can simultaneously render the team and analytics pages.\nParallel Routing allows you to define independent error and loading states for each route as they're being streamed in independently.\nParallel Routing also allows you to conditionally render a slot based on certain conditions, such as authentication state. This enables fully separated code on the same URL.\nConvention\nParallel routes are created using named slots. Slots are defined with the @folder convention, and are passed to the same-level layout as props.\nSlots are not route segments and do not affect the URL structure. The file path /@team/members would be accessible at /members.\nFor example, the following file structure defines two explicit slots: @analytics and @team.", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-1", "text": "For example, the following file structure defines two explicit slots: @analytics and @team.\nThe folder structure above means that the component in app/layout.js now accepts the @analytics and @team slots props, and can render them in parallel alongside the children prop:\napp/layout.tsx export default function Layout(props: {\n children: React.ReactNode\n analytics: React.ReactNode\n team: React.ReactNode\n}) {\n return (\n <>\n {props.children}\n {props.team}\n {props.analytics}\n </>\n )\n}\nGood to know: The children prop is an implicit slot that does not need to be mapped to a folder. This means app/page.js is equivalent to app/@children/page.js.\nUnmatched Routes\nBy default, the content rendered within a slot will match the current URL.", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-2", "text": "Unmatched Routes\nBy default, the content rendered within a slot will match the current URL.\nIn the case of an unmatched slot, the content that Next.js renders differs based on the routing technique and folder structure.\ndefault.js\nYou can define a default.js file to render as a fallback when Next.js cannot recover a slot's active state based on the current URL.\nConsider the following folder structure. The @team slot has a settings directory, but @analytics does not.\nIf you were to navigate from the root / to /settings, the content that gets rendered is different based on the type of navigation and the availability of the default.js file.\nWith @analytics/default.jsWithout @analytics/default.jsSoft Navigation@team/settings/page.js and @analytics/page.js@team/settings/page.js and @analytics/page.jsHard Navigation@team/settings/page.js and @analytics/default.js404\nSoft Navigation", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-3", "text": "Soft Navigation\nOn a soft navigation - Next.js will render the slot's previously active state, even if it doesn't match the current URL.\nHard Navigation\nOn a hard navigation - a navigation that requires a full page reload - Next.js will first try to render the unmatched slot's default.js file. If that's not available, a 404 gets rendered.\nThe 404 for unmatched routes helps ensure that you don't accidentally render a route that shouldn't be parallel rendered.\nuseSelectedLayoutSegment(s)\nBoth useSelectedLayoutSegment and useSelectedLayoutSegments accept a parallelRoutesKey, which allows you read the active route segment within that slot.\napp/layout.tsx 'use client'\n \nimport { useSelectedLayoutSegment } from 'next/navigation'\n \nexport default async function Layout(props: {\n //...\n authModal: React.ReactNode\n}) {\n const loginSegments = useSelectedLayoutSegment('authModal')", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-4", "text": "}) {\n const loginSegments = useSelectedLayoutSegment('authModal')\n // ...\n}\nWhen a user navigates to @authModal/login, or /login in the URL bar, loginSegments will be equal to the string \"login\".\nExamples\nModals\nParallel Routing can be used to render modals.\nThe @authModal slot renders a <Modal> component that can be shown by navigating to a matching route, for example /login.\napp/layout.tsx export default async function Layout(props: {\n // ...\n authModal: React.ReactNode\n}) {\n return (\n <>\n {/* ... */}\n {props.authModal}\n </>\n )\n}\napp/@authModal/login/page.tsx import { Modal } from 'components/modal'\n \nexport default function Login() {\n return (\n <Modal>\n <h1>Login</h1>", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-5", "text": "return (\n <Modal>\n <h1>Login</h1>\n {/* ... */}\n </Modal>\n )\n}\nTo ensure that the contents of the modal don't get rendered when it's not active, you can create a default.js file that returns null.\napp/@authModal/default.tsx export default function Default() {\n return null\n}\nDismissing a modal\nIf a modal was initiated through client navigation, e.g. by using <Link href=\"/login\">, you can dismiss the modal by calling router.back() or by using a Link component.\napp/@authModal/login/page.tsx 'use client'\nimport { useRouter } from 'next/navigation'\nimport { Modal } from 'components/modal'\n \nexport default async function Login() {\n const router = useRouter()\n return (\n <Modal>", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-6", "text": "const router = useRouter()\n return (\n <Modal>\n <span onClick={() => router.back()}>Close modal</span>\n <h1>Login</h1>\n ...\n </Modal>\n )\n}\nMore information on modals is covered in the Intercepting Routes section.\nIf you want to navigate elsewhere and dismiss a modal, you can also use a catch-all route.\napp/@authModal/[...catchAll]/page.tsx export default function CatchAll() {\n return null\n}\nCatch-all routes take precedence over default.js.\nConditional Routes\nParallel Routes can be used to implement conditional routing. For example, you can render a @dashboard or @login route depending on the authentication state.\napp/layout.tsx import { getUser } from '@/lib/auth'\n \nexport default function Layout({\n dashboard,\n login,\n}: {\n dashboard: React.ReactNode", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "04c394e53e49-7", "text": "dashboard,\n login,\n}: {\n dashboard: React.ReactNode\n login: React.ReactNode\n}) {\n const isLoggedIn = getUser()\n return isLoggedIn ? dashboard : login\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/parallel-routes"} {"id": "01dc1cccd23e-0", "text": "Intercepting RoutesIntercepting routes allows you to load a route within the current layout while keeping the context for the current page. This routing paradigm can be useful when you want to \"intercept\" a certain route to show a different route.\nFor example, when clicking on a photo from within a feed, a modal overlaying the feed should show up with the photo. In this case, Next.js intercepts the /feed route and \"masks\" this URL to show /photo/123 instead.\nHowever, when navigating to the photo directly by for example when clicking a shareable URL or by refreshing the page, the entire photo page should render instead of the modal. No route interception should occur.\nConvention\nIntercepting routes can be defined with the (..) convention, which is similar to relative path convention ../ but for segments.\nYou can use:\n(.) to match segments on the same level\n(..) to match segments one level above", "source": "https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes"} {"id": "01dc1cccd23e-1", "text": "(.) to match segments on the same level\n(..) to match segments one level above\n(..)(..) to match segments two levels above\n(...) to match segments from the root app directory\nFor example, you can intercept the photo segment from within the feed segment by creating a (..)photo directory.\nNote that the (..) convention is based on route segments, not the file-system.\nExamples\nModals\nIntercepting Routes can be used together with Parallel Routes to create modals.\nUsing this pattern to create modals overcomes some common challenges when working with modals, by allowing you to:\nMake the modal content shareable through a URL\nPreserve context when the page is refreshed, instead of closing the modal\nClose the modal on backwards navigation rather than going to the previous route\nReopen the modal on forwards navigation", "source": "https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes"} {"id": "01dc1cccd23e-2", "text": "Reopen the modal on forwards navigation\nIn the above example, the path to the photo segment can use the (..) matcher since @modal is a slot and not a segment. This means that the photo route is only one segment level higher, despite being two file-system levels higher.\nOther examples could include opening a login modal in a top navbar while also having a dedicated /login page, or opening a shopping cart in a side modal.\nView an example of modals with Intercepted and Parallel Routes.", "source": "https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes"} {"id": "e771e7a1daa6-0", "text": "Route HandlersRoute Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.\nGood to know: Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Route Handlers together.\nConvention\nRoute Handlers are defined in a route.js|ts file inside the app directory:\napp/api/route.ts export async function GET(request: Request) {}\nRoute Handlers can be nested inside the app directory, similar to page.js and layout.js. But there cannot be a route.js file at the same route segment level as page.js.\nSupported HTTP Methods\nThe following HTTP methods are supported: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS. If an unsupported method is called, Next.js will return a 405 Method Not Allowed response.\nExtended NextRequest and NextResponse APIs", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-1", "text": "Extended NextRequest and NextResponse APIs\nIn addition to supporting native Request and Response. Next.js extends them with\nNextRequest and NextResponse to provide convenient helpers for advanced use cases.\nBehavior\nStatic Route Handlers\nRoute Handlers are statically evaluated by default when using the GET method with the Response object.\napp/items/route.ts import { NextResponse } from 'next/server'\n \nexport async function GET() {\n const res = await fetch('https://data.mongodb-api.com/...', {\n headers: {\n 'Content-Type': 'application/json',\n 'API-Key': process.env.DATA_API_KEY,\n },\n })\n const data = await res.json()\n \n return NextResponse.json({ data })\n}\nTypeScript Warning: Although Response.json() is valid, native TypeScript types currently shows an error, you can use NextResponse.json() for typed responses instead.\nDynamic Route Handlers", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-2", "text": "Dynamic Route Handlers\nRoute handlers are evaluated dynamically when:\nUsing the Request object with the GET method.\nUsing any of the other HTTP methods.\nUsing Dynamic Functions like cookies and headers.\nThe Segment Config Options manually specifies dynamic mode.\nFor example:\napp/products/api/route.ts import { NextResponse } from 'next/server'\n \nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url)\n const id = searchParams.get('id')\n const res = await fetch(`https://data.mongodb-api.com/product/${id}`, {\n headers: {\n 'Content-Type': 'application/json',\n 'API-Key': process.env.DATA_API_KEY,\n },\n })\n const product = await res.json()\n \n return NextResponse.json({ product })\n}\nSimilarly, the POST method will cause the Route Handler to be evaluated dynamically.", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-3", "text": "}\nSimilarly, the POST method will cause the Route Handler to be evaluated dynamically.\napp/items/route.ts import { NextResponse } from 'next/server'\n \nexport async function POST() {\n const res = await fetch('https://data.mongodb-api.com/...', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'API-Key': process.env.DATA_API_KEY,\n },\n body: JSON.stringify({ time: new Date().toISOString() }),\n })\n \n const data = await res.json()\n \n return NextResponse.json(data)\n}\nGood to know: Like API Routes, Route Handlers can be used for cases like handling form submissions. A new abstraction for handling forms and mutations that integrates deeply with React is being worked on.\nRoute Resolution\nYou can consider a route the lowest level routing primitive.", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-4", "text": "Route Resolution\nYou can consider a route the lowest level routing primitive.\nThey do not participate in layouts or client-side navigations like page.\nThere cannot be a route.js file at the same route as page.js.\nPageRouteResultapp/page.jsapp/route.js Conflictapp/page.jsapp/api/route.js Validapp/[user]/page.jsapp/api/route.js Valid\nEach route.js or page.js file takes over all HTTP verbs for that route.\napp/page.js export default function Page() {\n return <h1>Hello, Next.js!</h1>\n}\n \n// \u274c Conflict\n// `app/route.js`\nexport async function POST(request) {}\nExamples\nThe following examples show how to combine Route Handlers with other Next.js APIs and features.\nRevalidating Static Data\nYou can revalidate static data fetches using the next.revalidate option:", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-5", "text": "You can revalidate static data fetches using the next.revalidate option:\napp/items/route.ts import { NextResponse } from 'next/server'\n \nexport async function GET() {\n const res = await fetch('https://data.mongodb-api.com/...', {\n next: { revalidate: 60 }, // Revalidate every 60 seconds\n })\n const data = await res.json()\n \n return NextResponse.json(data)\n}\nAlternatively, you can use the revalidate segment config option:\n export const revalidate = 60\nDynamic Functions\nRoute Handlers can be used with dynamic functions from Next.js, like cookies and headers.\nCookies\nYou can read cookies with cookies from next/headers. This server function can be called directly in a Route Handler, or nested inside of another function.", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-6", "text": "This cookies instance is read-only. To set cookies, you need to return a new Response using the Set-Cookie header.\napp/api/route.ts import { cookies } from 'next/headers'\n \nexport async function GET(request: Request) {\n const cookieStore = cookies()\n const token = cookieStore.get('token')\n \n return new Response('Hello, Next.js!', {\n status: 200,\n headers: { 'Set-Cookie': `token=${token.value}` },\n })\n}\nAlternatively, you can use abstractions on top of the underlying Web APIs to read cookies (NextRequest):\napp/api/route.ts import { type NextRequest } from 'next/server'\n \nexport async function GET(request: NextRequest) {\n const token = request.cookies.get('token')\n}\nHeaders", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-7", "text": "const token = request.cookies.get('token')\n}\nHeaders\nYou can read headers with headers from next/headers. This server function can be called directly in a Route Handler, or nested inside of another function.\nThis headers instance is read-only. To set headers, you need to return a new Response with new headers.\napp/api/route.ts import { headers } from 'next/headers'\n \nexport async function GET(request: Request) {\n const headersList = headers()\n const referer = headersList.get('referer')\n \n return new Response('Hello, Next.js!', {\n status: 200,\n headers: { referer: referer },\n })\n}\nAlternatively, you can use abstractions on top of the underlying Web APIs to read headers (NextRequest):\napp/api/route.ts import { type NextRequest } from 'next/server'", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-8", "text": "app/api/route.ts import { type NextRequest } from 'next/server'\n \nexport async function GET(request: NextRequest) {\n const requestHeaders = new Headers(request.headers)\n}\nRedirects\napp/api/route.ts import { redirect } from 'next/navigation'\n \nexport async function GET(request: Request) {\n redirect('https://nextjs.org/')\n}\nDynamic Route Segments\nWe recommend reading the Defining Routes page before continuing.\nRoute Handlers can use Dynamic Segments to create request handlers from dynamic data.\napp/items/[slug]/route.ts export async function GET(\n request: Request,\n { params }: { params: { slug: string } }\n) {\n const slug = params.slug // 'a', 'b', or 'c'\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-9", "text": "const slug = params.slug // 'a', 'b', or 'c'\n}\nRouteExample URLparamsapp/items/[slug]/route.js/items/a{ slug: 'a' }app/items/[slug]/route.js/items/b{ slug: 'b' }app/items/[slug]/route.js/items/c{ slug: 'c' }\nStreaming\nStreaming is commonly used in combination with Large Language Models (LLMs), such an OpenAI, for AI-generated content. Learn more about the AI SDK.\napp/api/completion/route.ts import { Configuration, OpenAIApi } from 'openai-edge'\nimport { OpenAIStream, StreamingTextResponse } from 'ai'\n \nconst config = new Configuration({\n apiKey: process.env.OPENAI_API_KEY,\n})\nconst openai = new OpenAIApi(config)\n \nexport const runtime = 'edge'", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-10", "text": "export const runtime = 'edge'\n \nexport async function POST(req: Request) {\n const { prompt } = await req.json()\n const response = await openai.createCompletion({\n model: 'text-davinci-003',\n stream: true,\n temperature: 0.6,\n prompt: 'What is Next.js?',\n })\n \n const stream = OpenAIStream(response)\n return new StreamingTextResponse(stream)\n}\nThese abstractions use the Web APIs to create a stream. You can also use the underlying Web APIs directly.\napp/api/route.ts // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#convert_async_iterator_to_stream\nfunction iteratorToStream(iterator: any) {\n return new ReadableStream({\n async pull(controller) {\n const { value, done } = await iterator.next()", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-11", "text": "const { value, done } = await iterator.next()\n \n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n },\n })\n}\n \nfunction sleep(time: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, time)\n })\n}\n \nconst encoder = new TextEncoder()\n \nasync function* makeIterator() {\n yield encoder.encode('<p>One</p>')\n await sleep(200)\n yield encoder.encode('<p>Two</p>')\n await sleep(200)\n yield encoder.encode('<p>Three</p>')\n}\n \nexport async function GET() {\n const iterator = makeIterator()\n const stream = iteratorToStream(iterator)\n \n return new Response(stream)\n}\nRequest Body", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-12", "text": "return new Response(stream)\n}\nRequest Body\nYou can read the Request body using the standard Web API methods:\napp/items/route.ts import { NextResponse } from 'next/server'\n \nexport async function POST(request: Request) {\n const res = await request.json()\n return NextResponse.json({ res })\n}\nRequest Body FormData\nYou can read the FormData using the the request.formData() function:\napp/items/route.ts import { NextResponse } from 'next/server'\n \nexport async function POST(request: Request) {\n const formData = await request.formData()\n const name = formData.get('name')\n const email = formData.get('email')\n return NextResponse.json({ name, email })\n}\nSince formData data are all strings, you may want to use zod-form-data to validate the request and retrieve data in the format you prefer (e.g. number).", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-13", "text": "CORS\nYou can set CORS headers on a Response using the standard Web API methods:\napp/api/route.ts export async function GET(request: Request) {\n return new Response('Hello, Next.js!', {\n status: 200,\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Authorization',\n },\n })\n}\nEdge and Node.js Runtimes\nRoute Handlers have an isomorphic Web API to support both Edge and Node.js runtimes seamlessly, including support for streaming. Since Route Handlers use the same route segment configuration as Pages and Layouts, they support long-awaited features like general-purpose statically regenerated Route Handlers.\nYou can use the runtime segment config option to specify the runtime:\n export const runtime = 'edge' // 'nodejs' is the default", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-14", "text": "export const runtime = 'edge' // 'nodejs' is the default\nNon-UI Responses\nYou can use Route Handlers to return non-UI content. Note that sitemap.xml, robots.txt, app icons, and open graph images all have built-in support.\napp/rss.xml/route.ts export async function GET() {\n return new Response(`<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<rss version=\"2.0\">\n \n<channel>\n <title>Next.js Documentation\n https://nextjs.org/docs\n The React Framework for the Web\n\n \n`)\n}\nSegment Config Options\nRoute Handlers use the same route segment configuration as pages and layouts.\napp/items/route.ts export const dynamic = 'auto'\nexport const dynamicParams = true", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "e771e7a1daa6-15", "text": "app/items/route.ts export const dynamic = 'auto'\nexport const dynamicParams = true\nexport const revalidate = false\nexport const fetchCache = 'auto'\nexport const runtime = 'nodejs'\nexport const preferredRegion = 'auto'\nSee the API reference for more details.", "source": "https://nextjs.org/docs/app/building-your-application/routing/router-handlers"} {"id": "baccacb331d2-0", "text": "Middleware\nMiddleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.\nMiddleware runs before cached content and routes are matched. See Matching Paths for more details.\nConvention\nUse the file middleware.ts (or .js) in the root of your project to define Middleware. For example, at the same level as pages or app, or inside src if applicable.\nExample\nmiddleware.ts import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n \n// This function can be marked `async` if using `await` inside\nexport function middleware(request: NextRequest) {\n return NextResponse.redirect(new URL('/home', request.url))\n}\n \n// See \"Matching Paths\" below to learn more\nexport const config = {", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-1", "text": "// See \"Matching Paths\" below to learn more\nexport const config = {\n matcher: '/about/:path*',\n}\nMatching Paths\nMiddleware will be invoked for every route in your project. The following is the execution order:\nheaders from next.config.js\nredirects from next.config.js\nMiddleware (rewrites, redirects, etc.)\nbeforeFiles (rewrites) from next.config.js\nFilesystem routes (public/, _next/static/, pages/, app/, etc.)\nafterFiles (rewrites) from next.config.js\nDynamic Routes (/blog/[slug])\nfallback (rewrites) from next.config.js\nThere are two ways to define which paths Middleware will run on:\nCustom matcher config\nConditional statements\nMatcher\nmatcher allows you to filter Middleware to run on specific paths.\nmiddleware.js export const config = {\n matcher: '/about/:path*',\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-2", "text": "middleware.js export const config = {\n matcher: '/about/:path*',\n}\nYou can match a single path or multiple paths with an array syntax:\nmiddleware.js export const config = {\n matcher: ['/about/:path*', '/dashboard/:path*'],\n}\nThe matcher config allows full regex so matching like negative lookaheads or character matching is supported. An example of a negative lookahead to match all except specific paths can be seen here:\nmiddleware.js export const config = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - favicon.ico (favicon file)\n */\n '/((?!api|_next/static|_next/image|favicon.ico).*)',\n ],\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-3", "text": "],\n}\nGood to know: The matcher values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored.\nConfigured matchers:\nMUST start with /\nCan include named parameters: /about/:path matches /about/a and /about/b but not /about/a/c\nCan have modifiers on named parameters (starting with :): /about/:path* matches /about/a/b/c because * is zero or more. ? is zero or one and + one or more\nCan use regular expression enclosed in parenthesis: /about/(.*) is the same as /about/:path*\nRead more details on path-to-regexp documentation.\nGood to know: For backward compatibility, Next.js always considers /public as /public/index. Therefore, a matcher of /public/:path will match.\nConditional Statements\nmiddleware.ts import { NextResponse } from 'next/server'", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-4", "text": "Conditional Statements\nmiddleware.ts import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n \nexport function middleware(request: NextRequest) {\n if (request.nextUrl.pathname.startsWith('/about')) {\n return NextResponse.rewrite(new URL('/about-2', request.url))\n }\n \n if (request.nextUrl.pathname.startsWith('/dashboard')) {\n return NextResponse.rewrite(new URL('/dashboard/user', request.url))\n }\n}\nNextResponse\nThe NextResponse API allows you to:\nredirect the incoming request to a different URL\nrewrite the response by displaying a given URL\nSet request headers for API Routes, getServerSideProps, and rewrite destinations\nSet response cookies\nSet response headers\nTo produce a response from Middleware, you can:\nrewrite to a route (Page or Route Handler) that produces a response", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-5", "text": "rewrite to a route (Page or Route Handler) that produces a response\nreturn a NextResponse directly. See Producing a Response\nUsing Cookies\nCookies are regular headers. On a Request, they are stored in the Cookie header. On a Response they are in the Set-Cookie header. Next.js provides a convenient way to access and manipulate these cookies through the cookies extension on NextRequest and NextResponse.\nFor incoming requests, cookies comes with the following methods: get, getAll, set, and delete cookies. You can check for the existence of a cookie with has or remove all cookies with clear.\nFor outgoing responses, cookies have the following methods get, getAll, set, and delete.\nmiddleware.ts import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n \nexport function middleware(request: NextRequest) {\n // Assume a \"Cookie:nextjs=fast\" header to be present on the incoming request", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-6", "text": "// Getting cookies from the request using the `RequestCookies` API\n let cookie = request.cookies.get('nextjs')\n console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }\n const allCookies = request.cookies.getAll()\n console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]\n \n request.cookies.has('nextjs') // => true\n request.cookies.delete('nextjs')\n request.cookies.has('nextjs') // => false\n \n // Setting cookies on the response using the `ResponseCookies` API\n const response = NextResponse.next()\n response.cookies.set('vercel', 'fast')\n response.cookies.set({\n name: 'vercel',\n value: 'fast',\n path: '/',\n })\n cookie = response.cookies.get('vercel')", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-7", "text": "path: '/',\n })\n cookie = response.cookies.get('vercel')\n console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }\n // The outgoing response will have a `Set-Cookie:vercel=fast;path=/test` header.\n \n return response\n}\nSetting Headers\nYou can set request and response headers using the NextResponse API (setting request headers is available since Next.js v13.0.0).\nmiddleware.ts import { NextResponse } from 'next/server'\nimport type { NextRequest } from 'next/server'\n \nexport function middleware(request: NextRequest) {\n // Clone the request headers and set a new header `x-hello-from-middleware1`\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set('x-hello-from-middleware1', 'hello')", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-8", "text": "requestHeaders.set('x-hello-from-middleware1', 'hello')\n \n // You can also set request headers in NextResponse.rewrite\n const response = NextResponse.next({\n request: {\n // New request headers\n headers: requestHeaders,\n },\n })\n \n // Set a new response header `x-hello-from-middleware2`\n response.headers.set('x-hello-from-middleware2', 'hello')\n return response\n}\nGood to know: Avoid setting large headers as it might cause 431 Request Header Fields Too Large error depending on your backend web server configuration.\nProducing a Response\nYou can respond from Middleware directly by returning a Response or NextResponse instance. (This is available since Next.js v13.1.0)\nmiddleware.ts import { NextRequest, NextResponse } from 'next/server'\nimport { isAuthenticated } from '@lib/auth'", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-9", "text": "import { isAuthenticated } from '@lib/auth'\n \n// Limit the middleware to paths starting with `/api/`\nexport const config = {\n matcher: '/api/:function*',\n}\n \nexport function middleware(request: NextRequest) {\n // Call our authentication function to check the request\n if (!isAuthenticated(request)) {\n // Respond with JSON indicating an error message\n return new NextResponse(\n JSON.stringify({ success: false, message: 'authentication failed' }),\n { status: 401, headers: { 'content-type': 'application/json' } }\n )\n }\n}\nAdvanced Middleware Flags\nIn v13.1 of Next.js two additional flags were introduced for middleware, skipMiddlewareUrlNormalize and skipTrailingSlashRedirect to handle advanced use cases.", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-10", "text": "skipTrailingSlashRedirect allows disabling Next.js default redirects for adding or removing trailing slashes allowing custom handling inside middleware which can allow maintaining the trailing slash for some paths but not others allowing easier incremental migrations.\nnext.config.js module.exports = {\n skipTrailingSlashRedirect: true,\n}\nmiddleware.js const legacyPrefixes = ['/docs', '/blog']\n \nexport default async function middleware(req) {\n const { pathname } = req.nextUrl\n \n if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {\n return NextResponse.next()\n }\n \n // apply trailing slash handling\n if (\n !pathname.endsWith('/') &&\n !pathname.match(/((?!\\.well-known(?:\\/.*)?)(?:[^/]+\\/)*[^/]+\\.\\w+)/)\n ) {\n req.nextUrl.pathname += '/'\n return NextResponse.redirect(req.nextUrl)\n }", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-11", "text": "return NextResponse.redirect(req.nextUrl)\n }\n}\nskipMiddlewareUrlNormalize allows disabling the URL normalizing Next.js does to make handling direct visits and client-transitions the same. There are some advanced cases where you need full control using the original URL which this unlocks.\nnext.config.js module.exports = {\n skipMiddlewareUrlNormalize: true,\n}\nmiddleware.js export default async function middleware(req) {\n const { pathname } = req.nextUrl\n \n // GET /_next/data/build-id/hello.json\n \n console.log(pathname)\n // with the flag this now /_next/data/build-id/hello.json\n // without the flag this would be normalized to /hello\n}\nVersion History", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "baccacb331d2-12", "text": "// without the flag this would be normalized to /hello\n}\nVersion History\nVersionChangesv13.1.0Advanced Middleware flags addedv13.0.0Middleware can modify request headers, response headers, and send responsesv12.2.0Middleware is stable, please see the upgrade guidev12.0.9Enforce absolute URLs in Edge Runtime (PR)v12.0.0Middleware (Beta) added", "source": "https://nextjs.org/docs/app/building-your-application/routing/middleware"} {"id": "51e8ce814bef-0", "text": "Project Organization and File ColocationApart from routing folder and file conventions, Next.js is unopinionated about how you organize and colocate your project files.\nThis page shares default behavior and features you can use to organize your project.\nSafe colocation by default\nProject organization features\nProject organization strategies\nSafe colocation by default\nIn the app directory, nested folder hierarchy defines route structure.\nEach folder represents a route segment that is mapped to a corresponding segment in a URL path.\nHowever, even though route structure is defined through folders, a route is not publicly accessible until a page.js or route.js file is added to a route segment.\nAnd, even when a route is made publicly accessible, only the content returned by page.js or route.js is sent to the client.\nThis means that project files can be safely colocated inside route segments in the app directory without accidentally being routable.\nGood to know:", "source": "https://nextjs.org/docs/app/building-your-application/routing/colocation"} {"id": "51e8ce814bef-1", "text": "Good to know:\nThis is different from the pages directory, where any file in pages is considered a route.\nWhile you can colocate your project files in app you don't have to. If you prefer, you can keep them outside the app directory.\nProject organization features\nNext.js provides several features to help you organize your project.\nPrivate Folders\nPrivate folders can be created by prefixing a folder with an underscore: _folderName\nThis indicates the folder is a private implementation detail and should not be considered by the routing system, thereby opting the folder and all its subfolders out of routing.\nSince files in the app directory can be safely colocated by default, private folders are not required for colocation. However, they can be useful for:\nSeparating UI logic from routing logic.\nConsistently organizing internal files across a project and the Next.js ecosystem.\nSorting and grouping files in code editors.", "source": "https://nextjs.org/docs/app/building-your-application/routing/colocation"} {"id": "51e8ce814bef-2", "text": "Sorting and grouping files in code editors.\nAvoiding potential naming conflicts with future Next.js file conventions.\nGood to know\nWhile not a framework convention, you might also consider marking files outside private folders as \"private\" using the same underscore pattern.\nYou can create URL segments that start with an underscore by prefixing the folder name with %5F (the URL-encoded form of an underscore): %5FfolderName.\nIf you don't use private folders, it would be helpful to know Next.js special file conventions to prevent unexpected naming conflicts.\nRoute Groups\nRoute groups can be created by wrapping a folder in parenthesis: (folderName)\nThis indicates the folder is for organizational purposes and should not be included in the route's URL path.\nRoute groups are useful for:\nOrganizing routes into groups e.g. by site section, intent, or team.\nEnabling nested layouts in the same route segment level:", "source": "https://nextjs.org/docs/app/building-your-application/routing/colocation"} {"id": "51e8ce814bef-3", "text": "Enabling nested layouts in the same route segment level:\nCreating multiple nested layouts in the same segment, including multiple root layouts\nAdding a layout to a subset of routes in a common segment\nsrc Directory\nNext.js supports storing application code (including app) inside an optional src directory. This separates application code from project configuration files which mostly live in the root of a project.\nModule Path Aliases\nNext.js supports Module Path Aliases which make it easier to read and maintain imports across deeply nested project files.\napp/dashboard/settings/analytics/page.js // before\nimport { Button } from '../../../components/button'\n \n// after\nimport { Button } from '@/components/button'\nProject organization strategies\nThere is no \"right\" or \"wrong\" way when it comes to organizing your own files and folders in a Next.js project.", "source": "https://nextjs.org/docs/app/building-your-application/routing/colocation"} {"id": "51e8ce814bef-4", "text": "The following section lists a very high-level overview of common strategies. The simplest takeaway is to choose a strategy that works for you and your team and be consistent across the project.\nGood to know: In our examples below, we're using components and lib folders as generalized placeholders, their naming has no special framework significance and your projects might use other folders like ui, utils, hooks, styles, etc.\nStore project files outside of app\nThis strategy stores all application code in shared folders in the root of your project and keeps the app directory purely for routing purposes.\nStore project files in top-level folders inside of app\nThis strategy stores all application code in shared folders in the root of the app directory.\nSplit project files by feature or route\nThis strategy stores globally shared application code in the root app directory and splits more specific application code into the route segments that use them.", "source": "https://nextjs.org/docs/app/building-your-application/routing/colocation"} {"id": "7159bd219a09-0", "text": "InternationalizationNext.js enables you to configure the routing and rendering of content to support multiple languages. Making your site adaptive to different locales includes translated content (localization) and internationalized routes.\nTerminology\nLocale: An identifier for a set of language and formatting preferences. This usually includes the preferred language of the user and possibly their geographic region.\nen-US: English as spoken in the United States\nnl-NL: Dutch as spoken in the Netherlands\nnl: Dutch, no specific region\nRouting Overview\nIt\u2019s recommended to use the user\u2019s language preferences in the browser to select which locale to use. Changing your preferred language will modify the incoming Accept-Language header to your application.\nFor example, using the following libraries, you can look at an incoming Request to determine which locale to select, based on the Headers, locales you plan to support, and the default locale.\nmiddleware.js import { match } from '@formatjs/intl-localematcher'", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-1", "text": "middleware.js import { match } from '@formatjs/intl-localematcher'\nimport Negotiator from 'negotiator'\n \nlet headers = { 'accept-language': 'en-US,en;q=0.5' }\nlet languages = new Negotiator({ headers }).languages()\nlet locales = ['en-US', 'nl-NL', 'nl']\nlet defaultLocale = 'en-US'\n \nmatch(languages, locales, defaultLocale) // -> 'en-US'\nRouting can be internationalized by either the sub-path (/fr/products) or domain (my-site.fr/products). With this information, you can now redirect the user based on the locale inside Middleware.\nmiddleware.js import { NextResponse } from 'next/server'\n \nlet locales = ['en-US', 'nl-NL', 'nl']\n \n// Get the preferred locale, similar to above or using a library\nfunction getLocale(request) { ... }", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-2", "text": "function getLocale(request) { ... }\n \nexport function middleware(request) {\n // Check if there is any supported locale in the pathname\n const pathname = request.nextUrl.pathname\n const pathnameIsMissingLocale = locales.every(\n (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`\n )\n \n // Redirect if there is no locale\n if (pathnameIsMissingLocale) {\n const locale = getLocale(request)\n \n // e.g. incoming request is /products\n // The new URL is now /en-US/products\n return NextResponse.redirect(\n new URL(`/${locale}/${pathname}`, request.url)\n )\n }\n}\n \nexport const config = {\n matcher: [\n // Skip all internal paths (_next)\n '/((?!_next).*)',", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-3", "text": "// Skip all internal paths (_next)\n '/((?!_next).*)',\n // Optional: only run on root (/) URL\n // '/'\n ],\n}\nFinally, ensure all special files inside app/ are nested under app/[lang]. This enables the Next.js router to dynamically handle different locales in the route, and forward the lang parameter to every layout and page. For example:\napp/[lang]/page.js // You now have access to the current locale\n// e.g. /en-US/products -> `lang` is \"en-US\"\nexport default async function Page({ params: { lang } }) {\n return ...\n}\nThe root layout can also be nested in the new folder (e.g. app/[lang]/layout.js).\nLocalization", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-4", "text": "Localization\nChanging displayed content based on the user\u2019s preferred locale, or localization, is not something specific to Next.js. The patterns described below would work the same with any web application.\nLet\u2019s assume we want to support both English and Dutch content inside our application. We might maintain two different \u201cdictionaries\u201d, which are objects that give us a mapping from some key to a localized string. For example:\ndictionaries/en.json {\n \"products\": {\n \"cart\": \"Add to Cart\"\n }\n}\ndictionaries/nl.json {\n \"products\": {\n \"cart\": \"Toevoegen aan Winkelwagen\"\n }\n}\nWe can then create a getDictionary function to load the translations for the requested locale:\napp/[lang]/dictionaries.js import 'server-only'\n \nconst dictionaries = {", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-5", "text": "app/[lang]/dictionaries.js import 'server-only'\n \nconst dictionaries = {\n en: () => import('./dictionaries/en.json').then((module) => module.default),\n nl: () => import('./dictionaries/nl.json').then((module) => module.default),\n}\n \nexport const getDictionary = async (locale) => dictionaries[locale]()\nGiven the currently selected language, we can fetch the dictionary inside of a layout or page.\napp/[lang]/page.js import { getDictionary } from './dictionaries'\n \nexport default async function Page({ params: { lang } }) {\n const dict = await getDictionary(lang) // en\n return // Add to Cart\n}", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-6", "text": "return // Add to Cart\n}\nBecause all layouts and pages in the app/ directory default to Server Components, we do not need to worry about the size of the translation files affecting our client-side JavaScript bundle size. This code will only run on the server, and only the resulting HTML will be sent to the browser.\nStatic Generation\nTo generate static routes for a given set of locales, we can use generateStaticParams with any page or layout. This can be global, for example, in the root layout:\napp/[lang]/layout.js export async function generateStaticParams() {\n return [{ lang: 'en-US' }, { lang: 'de' }]\n}\n \nexport default function Root({ children, params }) {\n return (\n \n {children}\n \n )\n}\nExamples", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "7159bd219a09-7", "text": "\n )\n}\nExamples\nMinimal i18n routing and translations\nnext-intl", "source": "https://nextjs.org/docs/app/building-your-application/routing/internationalization"} {"id": "092d651651e2-0", "text": "Static and Dynamic RenderingIn Next.js, a route can be statically or dynamically rendered.\nIn a static route, components are rendered on the server at build time. The result of the work is cached and reused on subsequent requests.\nIn a dynamic route, components are rendered on the server at request time.\nStatic Rendering (Default)\nBy default, Next.js statically renders routes to improve performance. This means all the rendering work is done ahead of time and can be served from a Content Delivery Network (CDN) geographically closer to the user.\nStatic Data Fetching (Default)\nBy default, Next.js will cache the result of fetch() requests that do not specifically opt out of caching behavior. This means that fetch requests that do not set a cache option will use the force-cache option.\nIf any fetch requests in the route use the revalidate option, the route will be re-rendered statically during revalidation.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering"} {"id": "092d651651e2-1", "text": "To learn more about caching data fetching requests, see the Caching and Revalidating page.\nDynamic Rendering\nDuring static rendering, if a dynamic function or a dynamic fetch() request (no caching) is discovered, Next.js will switch to dynamically rendering the whole route at request time. Any cached data requests can still be re-used during dynamic rendering.\nThis table summarizes how dynamic functions and caching affect the rendering behavior of a route:\nData FetchingDynamic FunctionsRenderingStatic (Cached)NoStaticStatic (Cached)YesDynamicNot CachedNoDynamicNot CachedYesDynamic\nNote how dynamic functions always opt the route into dynamic rendering, regardless of whether the data fetching is cached or not. In other words, static rendering is dependent not only on the data fetching behavior, but also on the dynamic functions used in the route.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering"} {"id": "092d651651e2-2", "text": "Good to know: In the future, Next.js will introduce hybrid server-side rendering where layouts and pages in a route can be independently statically or dynamically rendered, instead of the whole route.\nDynamic Functions\nDynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are:\nUsing cookies() or headers() in a Server Component will opt the whole route into dynamic rendering at request time.\nUsing useSearchParams() in Client Components will skip static rendering and instead render all Client Components up to the nearest parent Suspense boundary on the client.\nWe recommend wrapping the Client Component that uses useSearchParams() in a boundary. This will allow any Client Components above it to be statically rendered. Example.\nUsing the searchParams Pages prop will opt the page into dynamic rendering at request time.\nDynamic Data Fetching", "source": "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering"} {"id": "092d651651e2-3", "text": "Dynamic Data Fetching\nDynamic data fetches are fetch() requests that specifically opt out of caching behavior by setting the cache option to 'no-store' or revalidate to 0.\nThe caching options for all fetch requests in a layout or page can also be set using the segment config object.\nTo learn more about Dynamic Data Fetching, see the Data Fetching page.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering"} {"id": "d0539c74aec9-0", "text": "Edge and Node.js Runtimes\nIn the context of Next.js, \"runtime\" refers to the set of libraries, APIs, and general functionality available to your code during execution.\nNext.js has two server runtimes where you can render parts of your application code:\nNode.js Runtime\nEdge Runtime\nEach runtime has its own set of APIs. Please refer to the Node.js Docs and Edge Docs for the full list of available APIs. Both runtimes can also support streaming depending on your deployment infrastructure.\nBy default, the app directory uses the Node.js runtime. However, you can opt into different runtimes (e.g. Edge) on a per-route basis.\nRuntime Differences\nThere are many considerations to make when choosing a runtime. This table shows the major differences at a glance. If you want a more in-depth analysis of the differences, check out the sections below.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes"} {"id": "d0539c74aec9-1", "text": "NodeServerlessEdgeCold Boot/~250msInstantHTTP StreamingYesYesYesIOAllAllfetchScalability/HighHighestSecurityNormalHighHighLatencyNormalLowLowestnpm PackagesAllAllA smaller subset\nEdge Runtime\nIn Next.js, the lightweight Edge Runtime is a subset of available Node.js APIs.\nThe Edge Runtime is ideal if you need to deliver dynamic, personalized content at low latency with small, simple functions. The Edge Runtime's speed comes from its minimal use of resources, but that can be limiting in many scenarios.\nFor example, code executed in the Edge Runtime on Vercel cannot exceed between 1 MB and 4 MB, this limit includes imported packages, fonts and files, and will vary depending on your deployment infrastructure.\nNode.js Runtime\nUsing the Node.js runtime gives you access to all Node.js APIs, and all npm packages that rely on them. However, it's not as fast to start up as routes using the Edge runtime.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes"} {"id": "d0539c74aec9-2", "text": "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.\nServerless Node.js\nServerless is ideal if you need a scalable solution that can handle more complex computational loads than the Edge Runtime. With Serverless Functions on Vercel, for example, your overall code size is 50MB including imported packages, fonts, and files.\nThe downside compared to routes using the Edge is that it can take hundreds of milliseconds for Serverless Functions to boot up before they begin processing requests. Depending on the amount of traffic your site receives, this could be a frequent occurrence as the functions are not frequently \"warm\".\nExamples\nSegment Runtime Option", "source": "https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes"} {"id": "d0539c74aec9-3", "text": "Examples\nSegment Runtime Option\nYou 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 segment that exports a runtime with a value of 'edge':app/page.tsx export const runtime = 'edge' // 'nodejs' (default) | 'edge'You can also define runtime on a layout level, which will make all routes under the layout run on the edge runtime:app/layout.tsx export const runtime = 'edge' // 'nodejs' (default) | 'edge'If the segment runtime is not set, the default nodejs runtime will be used. You do not need to use the runtime option if you do not plan to change from the Node.js runtime.", "source": "https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes"} {"id": "175f38087dac-0", "text": "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.\nData fetching is built on top of the fetch() Web API and React Server Components. When using fetch(), requests are automatically deduped by default.\nNext.js extends the fetch options object to allow each request to set its own caching and revalidating.\nasync and await in Server Components\nYou can use async and await to fetch data in Server Components.\napp/page.tsx async function getData() {\n const res = await fetch('https://api.example.com/...')\n // The return value is *not* serialized\n // You can return Date, Map, Set, etc.\n \n // Recommendation: handle errors\n if (!res.ok) {\n // This will activate the closest `error.js` Error Boundary\n throw new Error('Failed to fetch data')", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-1", "text": "throw new Error('Failed to fetch data')\n }\n \n return res.json()\n}\n \nexport default async function Page() {\n const data = await getData()\n \n return
\n}\nGood to know:\nTo 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.\nServer Component Functions\nNext.js provides helpful server functions you may need when fetching data in Server Components:\ncookies()\nheaders()\nuse in Client Components\nuse is a new React function that accepts a promise conceptually similar to await. use handles the promise returned by a function in a way that is compatible with components, hooks, and Suspense. Learn more about use in the React RFC.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-2", "text": "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.\nGood to know: We'll be adding more examples once fetch and use work in Client Components.\nStatic Data Fetching\nBy default, fetch will automatically fetch and cache data indefinitely.\n fetch('https://...') // cache: 'force-cache' is the default\nRevalidating Data\nTo revalidate cached data at a timed interval, you can use the next.revalidate option in fetch() to set the cache lifetime of a resource (in seconds).\n fetch('https://...', { next: { revalidate: 10 } })\nSee Revalidating Data for more information.\nGood to know:", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-3", "text": "See Revalidating Data for more information.\nGood to know:\nCaching 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())\nDynamic Data Fetching\nTo fetch fresh data on every fetch request, use the cache: 'no-store' option.\n fetch('https://...', { cache: 'no-store' })\nData Fetching Patterns\nParallel Data Fetching\nTo minimize client-server waterfalls, we recommend this pattern to fetch data in parallel:\napp/artist/[username]/page.tsx import Albums from './albums'\n \nasync function getArtist(username: string) {\n const res = await fetch(`https://api.example.com/artist/${username}`)\n return res.json()\n}", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-4", "text": "return res.json()\n}\n \nasync function getArtistAlbums(username: string) {\n const res = await fetch(`https://api.example.com/artist/${username}/albums`)\n return res.json()\n}\n \nexport default async function Page({\n params: { username },\n}: {\n params: { username: string }\n}) {\n // Initiate both requests in parallel\n const artistData = getArtist(username)\n const albumsData = getArtistAlbums(username)\n \n // Wait for the promises to resolve\n const [artist, albums] = await Promise.all([artistData, albumsData])\n \n return (\n <>\n

{artist.name}

\n \n \n )\n}", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-5", "text": "\n )\n}\nBy 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.\nWe can save time by initiating both requests in parallel, however, the user won't see the rendered result until both promises are resolved.\nTo improve the user experience, you can add a suspense boundary to break up the rendering work and show part of the result as soon as possible:\nartist/[username]/page.tsx import { getArtist, getArtistAlbums, type Album } from './api'\n \nexport default async function Page({\n params: { username },\n}: {\n params: { username: string }\n}) {\n // Initiate both requests in parallel\n const artistData = getArtist(username)\n const albumData = getArtistAlbums(username)", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-6", "text": "const albumData = getArtistAlbums(username)\n \n // Wait for the artist's promise to resolve first\n const artist = await artistData\n \n return (\n <>\n

{artist.name}

\n {/* Send the artist information first,\n and wrap albums in a suspense boundary */}\n Loading...}>\n \n \n \n )\n}\n \n// Albums Component\nasync function Albums({ promise }: { promise: Promise }) {\n // Wait for the albums promise to resolve\n const albums = await promise\n \n return (\n \n )", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-7", "text": "))}\n \n )\n}\nTake a look at the preloading pattern for more information on improving components structure.\nSequential Data Fetching\nTo 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:\napp/artist/page.tsx // ...\n \nasync function Playlists({ artistID }: { artistID: string }) {\n // Wait for the playlists\n const playlists = await getArtistPlaylists(artistID)\n \n return (\n \n )\n}\n \nexport default async function Page({\n params: { username },\n}: {\n params: { username: string }\n}) {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-8", "text": "}: {\n params: { username: string }\n}) {\n // Wait for the artist\n const artist = await getArtist(username)\n \n return (\n <>\n

{artist.name}

\n Loading...}>\n \n \n \n )\n}\nBy fetching data inside the component, each fetch request and nested segment in the route cannot start fetching data and rendering until the previous request or segment has completed.\nBlocking Rendering in a Route\nBy fetching data in a layout, rendering for all route segments beneath it can only start once the data has finished loading.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-9", "text": "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.\nIn the app directory, you have additional options to explore:\nFirst, you can use loading.js to show an instant loading state from the server while streaming in the result from your data fetching function.\nSecond, you can move data fetching lower in the component tree to only block rendering for the parts of the page that need it. For example, moving data fetching to a specific component rather than fetching it at the root layout.\nWhenever possible, it's best to fetch data in the segment that uses it. This also allows you to show a loading state for only the part of the page that is loading, and not the entire page.\nData Fetching without fetch()", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-10", "text": "Data Fetching without fetch()\nYou 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.\nIn cases where you cannot use fetch but still want to control the caching or revalidating behavior of a layout or page, you can rely on the default caching behavior of the segment or use the segment cache configuration.\nDefault Caching Behavior\nAny data fetching libraries that do not use fetch directly will not affect caching of a route, and will be static or dynamic depending on the route segment.\nIf the segment is static (default), the output of the request will be cached and revalidated (if configured) alongside the rest of the segment. If the segment is dynamic, the output of the request will not be cached and will be re-fetched on every request when the segment is rendered.\nGood to know: Dynamic functions like cookies() and headers() will make the route segment dynamic.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "175f38087dac-11", "text": "Good to know: Dynamic functions like cookies() and headers() will make the route segment dynamic.\nSegment Cache Configuration\nAs 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.\napp/page.tsx import prisma from './lib/prisma'\n \nexport const revalidate = 3600 // revalidate every hour\n \nasync function getPosts() {\n const posts = await prisma.post.findMany()\n return posts\n}\n \nexport default async function Page() {\n const posts = await getPosts()\n // ...\n}", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/fetching"} {"id": "2a4a233cbb5c-0", "text": "Caching DataNext.js has built-in support for caching data, both on a per-request basis (recommended) or for an entire route segment.\nPer-request Caching\nfetch()\nBy default, all fetch() requests are cached and deduplicated automatically. This means that if you make the same request twice, the second request will reuse the result from the first request.\napp/page.tsx async function getComments() {\n const res = await fetch('https://...') // The result is cached\n return res.json()\n}\n \n// This function is called twice, but the result is only fetched once\nconst comments = await getComments() // cache MISS\n \n// The second call could be anywhere in your application\nconst comments = await getComments() // cache HIT\nRequests are not cached if:", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-1", "text": "const comments = await getComments() // cache HIT\nRequests are not cached if:\nDynamic methods (next/headers, export const POST, or similar) are used and the fetch is a POST request (or uses Authorization or cookie headers)\nfetchCache is configured to skip cache by default\nrevalidate: 0 or cache: 'no-store' is configured on individual fetch\nRequests made using fetch can specify a revalidate option to control the revalidation frequency of the request.\napp/page.tsx export default async function Page() {\n // revalidate this data every 10 seconds at most\n const res = await fetch('https://...', { next: { revalidate: 10 } })\n const data = res.json()\n // ...\n}\nReact cache()", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-2", "text": "const data = res.json()\n // ...\n}\nReact cache()\nReact 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.\nutils/getUser.ts import { cache } from 'react'\n \nexport const getUser = cache(async (id: string) => {\n const user = await db.user.findUnique({ id })\n return user\n})\napp/user/[id]/layout.tsx import { getUser } from '@utils/getUser'\n \nexport default async function UserLayout({\n params: { id },\n}: {\n params: { id: string }\n}) {\n const user = await getUser(id)\n // ...\n}\napp/user/[id]/page.tsx import { getUser } from '@utils/getUser'", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-3", "text": "export default async function Page({\n params: { id },\n}: {\n params: { id: string }\n}) {\n const user = await getUser(id)\n // ...\n}\nAlthough 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 can reuse the result from the first request.\nGood to know:\nfetch() caches requests automatically, so you don't need to wrap functions that use fetch() with cache(). See automatic request deduping for more information.\nIn this new model, we recommend fetching data directly in the component that needs it, even if you're requesting the same data in multiple components, rather than passing the data between components as props.\nWe recommend using the server-only package to make sure server data fetching functions are never used on the client.\nPOST requests and cache()", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-4", "text": "POST requests and cache()\nPOST requests are automatically deduplicated when using fetch \u2013 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 must be flat and only include primitives. Deep objects won't match for deduplication.\nutils/getUser.ts import { cache } from 'react'\n \nexport const getUser = cache(async (id: string) => {\n const res = await fetch('...', { method: 'POST', body: '...' })\n // ...\n})\nPreload pattern with cache()\nAs a pattern, we suggest optionally exposing a preload() export in utilities or components that do data fetching.\ncomponents/User.tsx import { getUser } from '@utils/getUser'\n \nexport const preload = (id: string) => {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-5", "text": "export const preload = (id: string) => {\n // void evaluates the given expression and returns undefined\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\n void getUser(id)\n}\nexport default async function User({ id }: { id: string }) {\n const result = await getUser(id)\n // ...\n}\nBy calling preload, you can eagerly start fetching data you're likely going to need.\napp/user/[id]/page.tsx import User, { preload } from '@components/User'\n \nexport default async function Page({\n params: { id },\n}: {\n params: { id: string }\n}) {\n preload(id) // starting loading the user data now\n const condition = await fetchCondition()\n return condition ? : null\n}\nGood to know:", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-6", "text": "}\nGood to know:\nThe preload() function can have any name. It's a pattern, not an API.\nThis pattern is completely optional and something you can use to optimize on a case-by-case basis.\nThis pattern is a further optimization on top of parallel data fetching. Now you don't have to pass promises down as props and can instead rely on the preload pattern.\nCombining cache, preload, and server-only\nYou can combine the cache function, the preload pattern, and the server-only package to create a data fetching utility that can be used throughout your app.\nutils/getUser.ts import { cache } from 'react'\nimport 'server-only'\n \nexport const preload = (id: string) => {\n void getUser(id)\n}\n \nexport const getUser = cache(async (id: string) => {\n // ...\n})", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-7", "text": "export const getUser = cache(async (id: string) => {\n // ...\n})\nWith this approach, you can eagerly fetch data, cache responses, and guarantee that this data fetching only happens on the server.\nThe getUser.ts exports can be used by layouts, pages, or components to give them control over when a user's data is fetched.\nSegment-level Caching\nGood to know: We recommend using per-request caching for improved granularity and control over caching.\nSegment-level caching allows you to cache and revalidate data used in route segments.\nThis mechanism allows different segments of a path to control the cache lifetime of the entire route. Each page.tsx and layout.tsx in the route hierarchy can export a revalidate value that sets the revalidation time for the route.\napp/page.tsx export const revalidate = 60 // revalidate this segment every 60 seconds\nGood to know:", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "2a4a233cbb5c-8", "text": "Good to know:\nIf a page, layout, and fetch request inside components all specify a revalidate frequency, the lowest value of the three will be used.\nAdvanced: 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 by individual fetch requests. See fetchCache for more information.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/caching"} {"id": "66d202fb49eb-0", "text": "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.\nThere are two types of revalidation in Next.js:\nBackground: Revalidates the data at a specific time interval.\nOn-demand: Revalidates the data based on an event such as an update.\nBackground Revalidation\nTo revalidate cached data at a specific interval, you can use the next.revalidate option in fetch() to set the cache lifetime of a resource (in seconds).\n fetch('https://...', { next: { revalidate: 60 } })\nIf you want to revalidate data that does not use fetch (i.e. using an external package or query builder), you can use the route segment config.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating"} {"id": "66d202fb49eb-1", "text": "app/page.tsx export const revalidate = 60 // revalidate this page every 60 seconds\nIn addition to fetch, you can also revalidate data using cache.\nHow it works\nWhen a request is made to the route that was statically rendered at build time, it will initially show the cached data.\nAny requests to the route after the initial request and before 60 seconds are also cached and instantaneous.\nAfter the 60-second window, the next request will still show the cached (stale) data.\nNext.js will trigger a regeneration of the data in the background.\nOnce the route generates successfully, Next.js will invalidate the cache and show the updated route. If the background regeneration fails, the old data would still be unaltered.\nWhen a request is made to a route segment that hasn\u2019t been generated, Next.js will dynamically render the route on the first request. Future requests will serve the static route segments from the cache.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating"} {"id": "66d202fb49eb-2", "text": "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 on Vercel persists the cache globally and handles rollbacks.\nOn-demand Revalidation\nIf you set a revalidate time of 60, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is if someone visits the page after the minute has passed.\nThe Next.js App Router supports revalidating content on-demand based on a route or cache tag. This allows you to manually purge the Next.js cache for specific fetches, making it easier to update your site when:\nContent from your headless CMS is created or updated.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating"} {"id": "66d202fb49eb-3", "text": "Content from your headless CMS is created or updated.\nEcommerce metadata changes (price, description, category, reviews, etc).\nUsing On-Demand Revalidation\nData can be revalidated on-demand by path (revalidatePath) or by cache tag (revalidateTag).\nFor example, the following fetch adds the cache tag collection:\napp/page.tsx export default async function Page() {\n const res = await fetch('https://...', { next: { tags: ['collection'] } })\n const data = await res.json()\n // ...\n}\nThis cached data can then be revalidated on-demand by calling revalidateTag in a Route Handler.\napp/api/revalidate/route.ts import { NextRequest, NextResponse } from 'next/server'\nimport { revalidateTag } from 'next/cache'\n \nexport async function GET(request: NextRequest) {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating"} {"id": "66d202fb49eb-4", "text": "export async function GET(request: NextRequest) {\n const tag = request.nextUrl.searchParams.get('tag')\n revalidateTag(tag)\n return NextResponse.json({ revalidated: true, now: Date.now() })\n}\nError Handling and Revalidation\nIf an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating"} {"id": "46ac516751e2-0", "text": "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:\nWith Server Components:\napp/add-to-cart.js import { cookies } from 'next/headers'\n \n// Server action defined inside a Server Component\nexport default function AddToCart({ productId }) {\n async function addItem(data) {\n 'use server'\n \n const cartId = cookies().get('cartId')?.value\n await saveToDb({ cartId, data })\n }\n \n return (\n
\n \n
\n )\n}\nWith Client Components:\napp/actions.js 'use server'\n \nexport async function addItem(data) {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-1", "text": "app/actions.js 'use server'\n \nexport async function addItem(data) {\n const cartId = cookies().get('cartId')?.value\n await saveToDb({ cartId, data })\n}\napp/add-to-cart.js 'use client'\n \nimport { addItem } from './actions.js'\n \n// Server Action being called inside a Client Component\nexport default function AddToCart({ productId }) {\n return (\n
\n \n
\n )\n}\nGood to know:\nUsing Server Actions will opt into running the React experimental channel.\nReact Actions, useOptimistic, and useFormStatus are not a Next.js or React Server Components specific features.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-2", "text": "Next.js integrates React Actions into the Next.js router, bundler, and caching system, including adding data mutation APIs like revalidateTag and revalidatePath.\nConvention\nYou can enable Server Actions in your Next.js project by enabling the experimental serverActions flag.\nnext.config.js module.exports = {\n experimental: {\n serverActions: true,\n },\n}\nCreation\nServer Actions can be defined in two places:\nInside the component that uses it (Server Components only)\nIn a separate file (Client and Server Components), for reusability. You can define multiple Server Actions in a single file.\nWith Server Components\nCreate a Server Action by defining an asynchronous function with the \"use server\" directive at the top of the function body. This function should have serializable arguments and a serializable return value based on the React Server Components protocol.\napp/server-component.js export default function ServerComponent() {\n async function myAction() {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-3", "text": "app/server-component.js export default function ServerComponent() {\n async function myAction() {\n 'use server'\n // ...\n }\n}\nWith Client Components\nIf 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 the Server Action into your Client Component:\napp/actions.js 'use server'\n \nexport async function myAction() {\n // ...\n}\napp/client-component.js 'use client'\n \nimport { myAction } from './actions'\n \nexport default function ClientComponent() {\n return (\n
\n \n
\n )\n}", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-4", "text": "\n )\n}\nGood 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.\nInvocation\nYou can invoke Server Actions using the following methods:\nUsing action: React's action prop allows invoking a Server Action on a
element.\nUsing formAction: React's formAction prop allows handling \n
\n )\n}\nGood to know: An action is similar to the HTML primitive action\nformAction\nYou can use formAction prop to handle Form Actions on elements such as button, input type=\"submit\", and input type=\"image\". The formAction prop takes precedence over the form's action.\napp/form.js export default function Form() {\n async function handleSubmit() {\n 'use server'\n // ...\n }", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-6", "text": "async function handleSubmit() {\n 'use server'\n // ...\n }\n \n async function submitImage() {\n 'use server'\n // ...\n }\n \n return (\n
\n \n \n \n
\n )\n}\nGood to know: A formAction is the HTML primitive formaction. React now allows you to pass functions to this attribute.\nCustom invocation using startTransition\nYou can also invoke Server Actions without using action or formAction. You can achieve this by using startTransition provided by the useTransition hook, which can be useful if you want to use Server Actions outside of forms, buttons, or inputs.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-7", "text": "Good to know: Using startTransition disables the out-of-the-box Progressive Enhancement.\napp/components/example-client-component.js 'use client'\n \nimport { useTransition } from 'react'\nimport { addItem } from '../actions'\n \nfunction ExampleClientComponent({ id }) {\n let [isPending, startTransition] = useTransition()\n \n return (\n \n )\n}\napp/actions.js 'use server'\n \nexport async function addItem(id) {\n await addItemToDb(id)\n // Marks all product pages for revalidating\n revalidatePath('/product/[id]')\n}\nCustom invocation without startTransition\nIf you aren't doing Server Mutations, you can directly pass the function as a prop like any other function.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-8", "text": "app/posts/[id]/page.tsx import kv from '@vercel/kv'\nimport LikeButton from './like-button'\n \nexport default function Page({ params }: { params: { id: string } }) {\n async function increment() {\n 'use server'\n await kv.incr(`post:id:${params.id}`)\n }\n \n return \n}\napp/post/[id]/like-button.tsx 'use client'\n \nexport default function LikeButton({\n increment,\n}: {\n increment: () => Promise\n}) {\n return (\n {\n await increment()\n }}\n >\n Like\n \n )\n}\nEnhancements\nExperimental useOptimistic", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-9", "text": "\n )\n}\nEnhancements\nExperimental useOptimistic\nThe 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.\nWhen a Server Action is invoked, the UI is updated immediately to reflect the expected outcome, instead of waiting for the Server Action's response.\napp/thread.js 'use client'\n \nimport { experimental_useOptimistic as useOptimistic, useRef } from 'react'\nimport { send } from './actions.js'\n \nexport function Thread({ messages }) {\n const [optimisticMessages, addOptimisticMessage] = useOptimistic(\n messages,\n (state, newMessage) => [...state, { message: newMessage, sending: true }]\n )\n const formRef = useRef()\n \n return (", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-10", "text": ")\n const formRef = useRef()\n \n return (\n
\n {optimisticMessages.map((m) => (\n
\n {m.message}\n {m.sending ? 'Sending...' : ''}\n
\n ))}\n {\n const message = formData.get('message')\n formRef.current.reset()\n addOptimisticMessage(message)\n await send(message)\n }}\n ref={formRef}\n >\n \n \n
\n )\n}\nExperimental useFormStatus\nThe experimental useFormStatus hook can be used within Form Actions, and provides the pending property.\napp/form.js 'use client'", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-11", "text": "app/form.js 'use client'\n \nimport { experimental_useFormStatus as useFormStatus } from 'react-dom'\n \nfunction Submit() {\n const { pending } = useFormStatus()\n \n return (\n \n Submit\n \n )\n}\nProgressive Enhancement\nProgressive Enhancement allows a
to function properly without JavaScript, or with JavaScript disabled. This allows users to interact with the form and submit data even if the JavaScript for the form hasn't been loaded yet or if it fails to load.\nBoth Server Form Actions and Client Form Actions support Progressive Enhancement, using one of two strategies:\nIf a Server Action is passed directly to a , the form is interactive even if JavaScript is disabled.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-12", "text": "If a Client Action is passed to a , the form is still interactive, but the action will be placed in a queue until the form has hydrated. The is prioritized with Selective Hydration, so it happens quickly.\napp/components/example-client-component.js 'use client'\n \nimport { useState } from 'react'\nimport { handleSubmit } from './actions.js'\n \nexport default function ExampleClientComponent({ myAction }) {\n const [input, setInput] = useState()\n \n return (\n setInput(e.target.value)}>\n {/* ... */}\n
\n )\n}\nIn both cases, the form is interactive before hydration occurs. Although Server Actions have the additional benefit of not relying on client JavaScript, you can still compose additional behavior with Client Actions where desired without sacrificing interactivity.\nSize Limitation", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-13", "text": "Size Limitation\nBy 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.\nHowever, you can configure this limit using the experimental serverActionsBodySizeLimit option. It can take the number of bytes or any string format supported by bytes, for example 1000, '500kb' or '3mb'.\nnext.config.js module.exports = {\n experimental: {\n serverActions: true,\n serverActionsBodySizeLimit: '2mb',\n },\n}\nExamples\nUsage with Client Components\nImport\nServer Actions cannot be defined within Client Components, but they can be imported. To use Server Actions in Client Components, you can import the action from a file containing a top-level \"use server\" directive.\napp/actions.js 'use server'\n \nexport async function addItem() {", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-14", "text": "app/actions.js 'use server'\n \nexport async function addItem() {\n // ...\n}\napp/components/example-client-component.js 'use client'\n \nimport { useTransition } from 'react'\nimport { addItem } from '../actions'\n \nfunction ExampleClientComponent({ id }) {\n let [isPending, startTransition] = useTransition()\n \n return (\n \n )\n}\nProps\nAlthough importing Server Actions is recommended, in some cases you might want to pass down a Server Action to a Client Component as a prop.\nFor example, you might want to use a dynamically generated value within the action. In that case, passing a Server Action down as a prop might be a viable solution.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-15", "text": "app/components/example-server-component.js import { ExampleClientComponent } from './components/example-client-component.js'\n \nfunction ExampleServerComponent({ id }) {\n async function updateItem(data) {\n 'use server'\n modifyItem({ id, data })\n }\n \n return \n}\napp/components/example-client-component.js 'use client'\n \nfunction ExampleClientComponent({ updateItem }) {\n async function action(formData) {\n await updateItem(formData)\n }\n \n return (\n
\n \n \n
\n )\n}\nOn-demand Revalidation", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-16", "text": "\n )\n}\nOn-demand Revalidation\nServer Actions can be used to revalidate data on-demand by path (revalidatePath) or by cache tag (revalidateTag).\n import { revalidateTag } from 'next/cache'\n \nasync function revalidate() {\n 'use server'\n revalidateTag('blog-posts')\n}\nValidation\nThe data passed to a Server Action can be validated or sanitized before invoking the action. For example, you can create a wrapper function that receives the action as its argument, and returns a function that invokes the action if it's valid.\napp/actions.js 'use server'\n \nimport { withValidate } from 'lib/form-validation'\n \nexport const action = withValidate((data) => {\n // ...\n})\nlib/form-validation.js export function withValidate(action) {\n return async (formData) => {\n 'use server'", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-17", "text": "return async (formData) => {\n 'use server'\n \n const isValidData = verifyData(formData)\n \n if (!isValidData) {\n throw new Error('Invalid input.')\n }\n \n const data = process(formData)\n return action(data)\n }\n}\nUsing headers\nYou can read incoming request headers such as cookies and headers within a Server Action.\n import { cookies } from 'next/headers'\n \nasync function addItem(data) {\n 'use server'\n \n const cartId = cookies().get('cartId')?.value\n \n await saveToDb({ cartId, data })\n}\nAdditionally, you can modify cookies within a Server Action.\n import { cookies } from 'next/headers';\n \nasync function create(data) {\n 'use server';\n \n const cart = await createCart():", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-18", "text": "'use server';\n \n const cart = await createCart():\n cookies().set('cartId', cart.id)\n // or\n cookies().set({\n name: 'cartId',\n value: cart.id,\n httpOnly: true,\n path: '/'\n })\n}\nGlossary\nActions\nActions are an experimental feature in React, allowing you to run async code in response to a user interaction.\nActions are not Next.js or React Server Components specific, however, they are not yet available in the stable version of React. When using Actions through Next.js, you are opting into using the React experimental channel.\nActions are defined through the action prop on an element. Typically when building HTML forms, you pass a URL to the action prop. With Actions, React now allows you to pass a function directly.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "46ac516751e2-19", "text": "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.\nForm Actions\nActions integrated into the web standard
API, and enable out-of-the-box progressive enhancement and loading states. Similar to the HTML primitive formaction.\nServer Functions\nFunctions that run on the server, but can be called on the client.\nServer Actions\nServer Functions called as an action.\nServer Actions can be progressively enhanced by passing them to a form element's action prop. The form is interactive before any client-side JavaScript has loaded. This means React hydration is not required for the form to submit.\nServer Mutations\nServer Actions that mutates your data and calls redirect, revalidatePath, or revalidateTag.", "source": "https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions"} {"id": "64d4e2b4532d-0", "text": "CSS Modules\nNext.js has built-in support for CSS Modules using the .module.css extension.\nCSS 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 component-level CSS.\nExample\nCSS Modules can be imported into any file inside the app directory:app/dashboard/layout.tsx import styles from './styles.module.css'\n \nexport default function DashboardLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return
{children}
\n}app/dashboard/styles.module.css .dashboard {\n padding: 24px;\n}\nCSS Modules are an optional feature and are only enabled for files with the .module.css extension.\nRegular stylesheets and global CSS files are still supported.", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-modules"} {"id": "64d4e2b4532d-1", "text": "Regular stylesheets and global CSS files are still supported.\nIn production, all CSS Module files will be automatically concatenated into many minified and code-split .css files.\nThese .css files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application to paint.\nGlobal Styles\nGlobal styles can be imported into any layout, page, or component inside the app directory.\nGood to know: This is different from the pages directory, where you can only import global styles inside the _app.js file.\nFor example, consider a stylesheet named app/global.css: body {\n padding: 20px 20px 60px;\n max-width: 680px;\n margin: 0 auto;\n}Inside the root layout (app/layout.js), import the global.css stylesheet to apply the styles to every route in your application:app/layout.tsx // These styles apply to every route in the application", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-modules"} {"id": "64d4e2b4532d-2", "text": "import './global.css'\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nExternal Stylesheets\nStylesheets published by external packages can be imported anywhere in the app directory, including colocated components:app/layout.tsx import 'bootstrap/dist/css/bootstrap.css'\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nGood to know: External stylesheets must be directly imported from an npm package or downloaded and colocated with your codebase. You cannot use .\nAdditional Features", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-modules"} {"id": "64d4e2b4532d-3", "text": "Additional Features\nNext.js includes additional features to improve the authoring experience of adding styles:\nWhen 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.\nWhen building for production with next build, CSS files will be bundled into fewer minified .css files to reduce the number of network requests needed to retrieve styles.\nIf you disable JavaScript, styles will still be loaded in the production build (next start). However, JavaScript is still required for next dev to enable Fast Refresh.", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-modules"} {"id": "64e8c07c73bb-0", "text": "Tailwind CSS\nTailwind CSS is a utility-first CSS framework that works exceptionally well with Next.js.\nInstalling Tailwind\nInstall the Tailwind CSS packages and run the init command to generate both the tailwind.config.js and postcss.config.js files:\nTerminal npm install -D tailwindcss postcss autoprefixer\nnpx tailwindcss init -p\nConfiguring Tailwind\nInside tailwind.config.js, add paths to the files that will use Tailwind CSS class names:\ntailwind.config.js /** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n './app/**/*.{js,ts,jsx,tsx,mdx}', // Note the addition of the `app` directory.\n './pages/**/*.{js,ts,jsx,tsx,mdx}',\n './components/**/*.{js,ts,jsx,tsx,mdx}',", "source": "https://nextjs.org/docs/app/building-your-application/styling/tailwind-css"} {"id": "64e8c07c73bb-1", "text": "'./components/**/*.{js,ts,jsx,tsx,mdx}',\n \n // Or if using `src` directory:\n './src/**/*.{js,ts,jsx,tsx,mdx}',\n ],\n theme: {\n extend: {},\n },\n plugins: [],\n}\nYou do not need to modify postcss.config.js.\nImporting Styles\nAdd the Tailwind CSS directives that Tailwind will use to inject its generated styles to a Global Stylesheet in your application, for example:app/globals.css @tailwind base;\n@tailwind components;\n@tailwind utilities;Inside the root layout (app/layout.tsx), import the globals.css stylesheet to apply the styles to every route in your application.app/layout.tsx import type { Metadata } from 'next'\n \n// These styles apply to every route in the application\nimport './globals.css'", "source": "https://nextjs.org/docs/app/building-your-application/styling/tailwind-css"} {"id": "64e8c07c73bb-2", "text": "// These styles apply to every route in the application\nimport './globals.css'\n \nexport const metadata: Metadata = {\n title: 'Create Next App',\n description: 'Generated by create next app',\n}\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}Using Classes\nAfter installing Tailwind CSS and adding the global styles, you can use Tailwind's utility classes in your application.app/page.tsx export default function Page() {\n return

Hello, Next.js!

\n}\nUsage with Turbopack\nAs of Next.js 13.1, Tailwind CSS and PostCSS are supported with Turbopack.", "source": "https://nextjs.org/docs/app/building-your-application/styling/tailwind-css"} {"id": "8945e7d1627d-0", "text": "CSS-in-JS\nWarning: 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.\nWe're working with the React team on upstream APIs to handle CSS and JavaScript assets with support for React Server Components and streaming architecture.\nThe following libraries are supported in Client Components in the app directory (alphabetical):\nkuma-ui\n@mui/material\npandacss\nstyled-jsx\nstyled-components\nstyle9\ntamagui\ntss-react\nvanilla-extract\nThe following are currently working on support:\nemotion\nGood to know: We're testing out different CSS-in-JS libraries and we'll be adding more examples for libraries that support React 18 features and/or the app directory.", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-1", "text": "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\nConfiguring CSS-in-JS is a three-step opt-in process that involves:\nA style registry to collect all CSS rules in a render.\nThe new useServerInsertedHTML hook to inject rules before any content that might use them.\nA Client Component that wraps your app with the style registry during initial server-side rendering.\nstyled-jsx\nUsing styled-jsx in Client Components requires using v5.1.0. First, create a new registry:app/registry.tsx 'use client'\n \nimport React, { useState } from 'react'\nimport { useServerInsertedHTML } from 'next/navigation'\nimport { StyleRegistry, createStyleRegistry } from 'styled-jsx'\n \nexport default function StyledJsxRegistry({\n children,", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-2", "text": "export default function StyledJsxRegistry({\n children,\n}: {\n children: React.ReactNode\n}) {\n // Only create stylesheet once with lazy initial state\n // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state\n const [jsxStyleRegistry] = useState(() => createStyleRegistry())\n \n useServerInsertedHTML(() => {\n const styles = jsxStyleRegistry.styles()\n jsxStyleRegistry.flush()\n return <>{styles}\n })\n \n return {children}\n}Then, wrap your root layout with the registry:app/layout.tsx import StyledJsxRegistry from './registry'\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n ", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-3", "text": "}) {\n return (\n \n \n {children}\n \n \n )\n}View an example here.Styled Components\nBelow 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 component to collect all CSS style rules generated during a render, and a function to return those rules. Then use the useServerInsertedHTML hook to inject the styles collected in the registry into the HTML tag in the root layout.lib/registry.tsx 'use client'\n \nimport React, { useState } from 'react'\nimport { useServerInsertedHTML } from 'next/navigation'\nimport { ServerStyleSheet, StyleSheetManager } from 'styled-components'\n \nexport default function StyledComponentsRegistry({", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-4", "text": "export default function StyledComponentsRegistry({\n children,\n}: {\n children: React.ReactNode\n}) {\n // Only create stylesheet once with lazy initial state\n // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state\n const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())\n \n useServerInsertedHTML(() => {\n const styles = styledComponentsStyleSheet.getStyleElement()\n styledComponentsStyleSheet.instance.clearTag()\n return <>{styles}\n })\n \n if (typeof window !== 'undefined') return <>{children}\n \n return (\n \n {children}\n \n )\n}Wrap the children of the root layout with the style registry component:app/layout.tsx import StyledComponentsRegistry from './lib/registry'", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-5", "text": "export default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n \n {children}\n \n \n )\n}View an example here.\nGood to know:\nDuring server rendering, styles will be extracted to a global registry and flushed to the of your HTML. This ensures the style rules are placed before any content that might use them. In the future, we may use an upcoming React feature to determine where to inject the styles.\nDuring streaming, styles from each chunk will be collected and appended to existing styles. After client-side hydration is complete, styled-components will take over as usual and inject any further dynamic styles.", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "8945e7d1627d-6", "text": "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.", "source": "https://nextjs.org/docs/app/building-your-application/styling/css-in-js"} {"id": "af7a2f69c782-0", "text": "Sass\nNext.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.\nFirst, install sass:\nTerminal npm install --save-dev sass\nGood to know:\nSass supports two different syntax, each with their own extension.\nThe .scss extension requires you use the SCSS syntax,\nwhile the .sass extension requires you use the Indented Syntax (\"Sass\").\nIf you're not sure which to choose, start with the .scss extension which is a superset of CSS, and doesn't require you learn the\nIndented Syntax (\"Sass\").\nCustomizing Sass Options\nIf you want to configure the Sass compiler, use sassOptions in next.config.js.\nnext.config.js const path = require('path')\n \nmodule.exports = {\n sassOptions: {", "source": "https://nextjs.org/docs/app/building-your-application/styling/sass"} {"id": "af7a2f69c782-1", "text": "module.exports = {\n sassOptions: {\n includePaths: [path.join(__dirname, 'styles')],\n },\n}\nSass Variables\nNext.js supports Sass variables exported from CSS Module files.\nFor example, using the exported primaryColor Sass variable:\napp/variables.module.scss $primary-color: #64ff00;\n \n:export {\n primaryColor: $primary-color;\n}\napp/page.js // maps to root `/` URL\n \nimport variables from './variables.module.scss'\n \nexport default function Page() {\n return

Hello, Next.js!

\n}", "source": "https://nextjs.org/docs/app/building-your-application/styling/sass"} {"id": "f6dc9a7dd197-0", "text": "Image Optimization\nExamples\nImage Component\nAccording to Web Almanac, images account for a huge portion of the typical website\u2019s page weight and can have a sizable impact on your website's LCP performance.\nThe Next.js Image component extends the HTML element with features for automatic image optimization:\nSize Optimization: Automatically serve correctly sized images for each device, using modern image formats like WebP and AVIF.\nVisual Stability: Prevent layout shift automatically when images are loading.\nFaster Page Loads: Images are only loaded when they enter the viewport using native browser lazy loading, with optional blur-up placeholders.\nAsset Flexibility: On-demand image resizing, even for images stored on remote servers\n\ud83c\udfa5 Watch: Learn more about how to use next/image \u2192 YouTube (9 minutes).\nUsage\n import Image from 'next/image'\nYou can then define the src for your image (either local or remote).\nLocal Images", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-1", "text": "You can then define the src for your image (either local or remote).\nLocal Images\nTo use a local image, import your .jpg, .png, or .webp image files.\nNext.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 image is loading.\napp/page.js import Image from 'next/image'\nimport profilePic from './me.png'\n \nexport default function Page() {\n return (\n \n )\n}", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-2", "text": "/>\n )\n}\nWarning: Dynamic await import() or require() are not supported. The import must be static so it can be analyzed at build time.\nRemote Images\nTo use a remote image, the src property should be a URL string.\nSince Next.js does not have access to remote files during the build process, you'll need to provide the width, height and optional blurDataURL props manually.\nThe width and height attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The width and height do not determine the rendered size of the image file. Learn more about Image Sizing.\napp/page.js import Image from 'next/image'\n \nexport default function Page() {\n return (\n \n )\n}\nTo 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:\nnext.config.js module.exports = {\n images: {\n remotePatterns: [\n {\n protocol: 'https',\n hostname: 's3.amazonaws.com',\n port: '',\n pathname: '/my-bucket/**',\n },\n ],\n },\n}\nLearn more about remotePatterns configuration. If you want to use relative URLs for the image src, use a loader.\nDomains", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-4", "text": "Domains\nSometimes 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.\nTo protect your application from malicious users, you must define a list of remote hostnames you intend to use with the next/image component.\nLearn more about remotePatterns configuration.\nLoaders\nNote that in the example earlier, a partial URL (\"/me.png\") is provided for a remote image. This is possible because of the loader architecture.\nA loader is a function that generates the URLs for your image. It modifies the provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-5", "text": "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 lines of JavaScript.\nYou can define a loader per-image with the loader prop, or at the application level with the loaderFile configuration.\nPriority\nYou should add the priority property to the image that will be the Largest Contentful Paint (LCP) element for each page. Doing so allows Next.js to specially prioritize the image for loading (e.g. through preload tags or priority hints), leading to a meaningful boost in LCP.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-6", "text": "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 without the priority property.\nOnce you've identified the LCP image, you can add the property like this:\napp/page.js import Image from 'next/image'\nimport profilePic from '../public/me.png'\n \nexport default function Page() {\n return \"Picture\n}\nSee more about priority in the next/image component documentation.\nImage Sizing", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-7", "text": "}\nSee more about priority in the next/image component documentation.\nImage Sizing\nOne 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 Vital, called Cumulative Layout Shift. The way to avoid image-based layout shifts is to always size your images. This allows the browser to reserve precisely enough space for the image before it loads.\nBecause next/image is designed to guarantee good performance results, it cannot be used in a way that will contribute to layout shift, and must be sized in one of three ways:\nAutomatically, using a static import\nExplicitly, by including a width and height property\nImplicitly, by using fill which causes the image to expand to fill its parent element.\nWhat if I don't know the size of my images?", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-8", "text": "What if I don't know the size of my images?\nIf you are accessing images from a source without knowledge of the images' sizes, there are several things you can do:\nUse fill\nThe 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 sizes prop to match any media query break points. You can also use object-fit with fill, contain, or cover, and object-position to define how the image should occupy that space.\nNormalize your images\nIf you're serving images from a source that you control, consider modifying your image pipeline to normalize the images to a specific size.\nModify your API calls\nIf your application is retrieving image URLs using an API call (such as to a CMS), you may be able to modify the API call to return the image dimensions along with the URL.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-9", "text": "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 elements.\nStyling\nStyling the Image component is similar to styling a normal element, but there are a few guidelines to keep in mind:\nUse className or style, not styled-jsx.\nIn most cases, we recommend using the className prop. This can be an imported CSS Module, a global stylesheet, etc.\nYou can also use the style prop to assign inline styles.\nYou cannot use styled-jsx because it's scoped to the current component (unless you mark the style as global).\nWhen using fill, the parent element must have position: relative\nThis is necessary for the proper rendering of the image element in that layout mode.\nWhen using fill, the parent element must have display: block\nThis is the default for
elements but should be specified otherwise.\nExamples\nResponsive", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-10", "text": "This is the default for
elements but should be specified otherwise.\nExamples\nResponsive\n import Image from 'next/image'\nimport mountains from '../public/mountains.jpg'\n \nexport default function Responsive() {\n return (\n
\n \n
\n )\n}\nFill Container\n import Image from 'next/image'\nimport mountains from '../public/mountains.jpg'\n \nexport default function Fill() {\n return (\n \n
\n \n
\n {/* And more images in the grid... */}\n
\n )\n}\nBackground Image\n import Image from 'next/image'\nimport mountains from '../public/mountains.jpg'\n \nexport default function Background() {", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "f6dc9a7dd197-12", "text": "import mountains from '../public/mountains.jpg'\n \nexport default function Background() {\n return (\n \n )\n}\nFor examples of the Image component used with the various styles, see the Image Component Demo.\nOther Properties\nView all properties available to the next/image component.\nConfiguration\nThe next/image component and Next.js Image Optimization API can be configured in the next.config.js file. These configurations allow you to enable remote images, define custom image breakpoints, change caching behavior and more.\nRead the full image configuration documentation for more information.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/images"} {"id": "43a365f70a81-0", "text": "Font Optimization\nnext/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance.\n\ud83c\udfa5 Watch: Learn more about how to use next/font \u2192 YouTube (6 minutes).\nnext/font includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS size-adjust property used.\nThis new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser.\nGoogle Fonts\nAutomatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. No requests are sent to Google by the browser.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-1", "text": "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.\napp/layout.tsx import { Inter } from 'next/font/google'\n \n// If loading a variable font, you don't need to specify the font weight\nconst inter = Inter({\n subsets: ['latin'],\n display: 'swap',\n})\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}If you can't use a variable font, you will need to specify a weight:app/layout.tsx import { Roboto } from 'next/font/google'\n \nconst roboto = Roboto({\n weight: '400',", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-2", "text": "const roboto = Roboto({\n weight: '400',\n subsets: ['latin'],\n display: 'swap',\n})\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nYou can specify multiple weights and/or styles by using an array:\napp/layout.js const roboto = Roboto({\n weight: ['400', '700'],\n style: ['normal', 'italic'],\n subsets: ['latin'],\n display: 'swap',\n})\nGood to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono.\nSpecifying a subset", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-3", "text": "Specifying a subset\nGoogle 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.\nThis can be done by adding it to the function call:\napp/layout.tsx const inter = Inter({ subsets: ['latin'] })\nView the Font API Reference for more information.\nUsing Multiple Fonts\nYou can import and use multiple fonts in your application. There are two approaches you can take.\nThe first approach is to create a utility function that exports a font, imports it, and applies its className where needed. This ensures the font is preloaded only when it's rendered:\napp/fonts.ts import { Inter, Roboto_Mono } from 'next/font/google'\n \nexport const inter = Inter({\n subsets: ['latin'],\n display: 'swap',\n})", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-4", "text": "subsets: ['latin'],\n display: 'swap',\n})\n \nexport const roboto_mono = Roboto_Mono({\n subsets: ['latin'],\n display: 'swap',\n})\napp/layout.tsx import { inter } from './fonts'\n \nexport default function Layout({ children }: { children: React.ReactNode }) {\n return (\n \n \n
{children}
\n \n \n )\n}app/page.tsx import { roboto_mono } from './fonts'\n \nexport default function Page() {\n return (\n <>\n

My page

\n \n )\n}", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-5", "text": "\n )\n}\nIn the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed.\nAlternatively, you can create a CSS variable and use it with your preferred CSS solution:\napp/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google'\nimport styles from './global.css'\n \nconst inter = Inter({\n subsets: ['latin'],\n variable: '--font-inter',\n display: 'swap',\n})\n \nconst roboto_mono = Roboto_Mono({\n subsets: ['latin'],\n variable: '--font-roboto-mono',\n display: 'swap',\n})\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-6", "text": "children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n \n

My App

\n
{children}
\n \n \n )\n}\napp/global.css html {\n font-family: var(--font-inter);\n}\n \nh1 {\n font-family: var(--font-roboto-mono);\n}\nIn the example above, Inter will be applied globally, and any

tags will be styled with Roboto Mono.\nRecommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download.\nLocal Fonts", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-7", "text": "Local Fonts\nImport next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility.\napp/layout.tsx import localFont from 'next/font/local'\n \n// Font files can be colocated inside of `app`\nconst myFont = localFont({\n src: './my-font.woff2',\n display: 'swap',\n})\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nIf you want to use multiple files for a single font family, src can be an array:\n const roboto = localFont({\n src: [\n {\n path: './Roboto-Regular.woff2',", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-8", "text": "src: [\n {\n path: './Roboto-Regular.woff2',\n weight: '400',\n style: 'normal',\n },\n {\n path: './Roboto-Italic.woff2',\n weight: '400',\n style: 'italic',\n },\n {\n path: './Roboto-Bold.woff2',\n weight: '700',\n style: 'normal',\n },\n {\n path: './Roboto-BoldItalic.woff2',\n weight: '700',\n style: 'italic',\n },\n ],\n})\nView the Font API Reference for more information.\nWith Tailwind CSS\nnext/font can be used with Tailwind CSS through a CSS variable.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-9", "text": "With Tailwind CSS\nnext/font can be used with Tailwind CSS through a CSS variable.\nIn 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 to add the CSS variable to your HTML document.\napp/layout.tsx import { Inter, Roboto_Mono } from 'next/font/google'\n \nconst inter = Inter({\n subsets: ['latin'],\n display: 'swap',\n variable: '--font-inter',\n})\n \nconst roboto_mono = Roboto_Mono({\n subsets: ['latin'],\n display: 'swap',\n variable: '--font-roboto-mono',\n})\n \nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode\n}) {", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-10", "text": "children,\n}: {\n children: React.ReactNode\n}) {\n return (\n \n {children}\n \n )\n}\nFinally, add the CSS variable to your Tailwind CSS config:\ntailwind.config.js /** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: [\n './pages/**/*.{js,ts,jsx,tsx}',\n './components/**/*.{js,ts,jsx,tsx}',\n './app/**/*.{js,ts,jsx,tsx}',\n ],\n theme: {\n extend: {\n fontFamily: {\n sans: ['var(--font-inter)'],\n mono: ['var(--font-roboto-mono)'],\n },\n },\n },", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-11", "text": "},\n },\n },\n plugins: [],\n}\nYou can now use the font-sans and font-mono utility classes to apply the font to your elements.\nPreloading\nWhen 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 the type of file where it is used:\nIf it's a unique page, it is preloaded on the unique route for that page.\nIf it's a layout, it is preloaded on all the routes wrapped by the layout.\nIf it's the root layout, it is preloaded on all routes.\nReusing fonts", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "43a365f70a81-12", "text": "If it's the root layout, it is preloaded on all routes.\nReusing fonts\nEvery 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 is recommended to do the following:\nCall the font loader function in one shared file\nExport it as a constant\nImport the constant in each file where you would like to use this font", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/fonts"} {"id": "995394ed8592-0", "text": "Script Optimization\nLayout Scripts\nTo 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'\n \nexport default function DashboardLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <>\n
{children}
\n \nOr by using the dangerouslySetInnerHTML property:\n \nWarning: An id property must be assigned for inline scripts in order for Next.js to track and optimize the script.\nExecuting Additional Code", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/scripts"} {"id": "995394ed8592-5", "text": "Executing Additional Code\nEvent handlers can be used with the Script component to execute additional code after a certain event occurs:\nonLoad: Execute code after the script has finished loading.\nonReady: Execute code after the script has finished loading and every time the component is mounted.\nonError: Execute code if the script fails to load.\nThese handlers will only work when next/script is imported and used inside of a Client Component where \"use client\" is defined as the first line of code:app/page.tsx 'use client'\n \nimport Script from 'next/script'\n \nexport default function Page() {\n return (\n <>\n {\n console.log('Script has loaded')\n }}\n />\n \n )\n}Refer to the next/script API reference to learn more about each event handler and view examples.", "source": "https://nextjs.org/docs/app/building-your-application/optimizing/scripts"} {"id": "995394ed8592-6", "text": "}Refer to the next/script API reference to learn more about each event handler and view examples.\nAdditional Attributes\nThere are many DOM attributes that can be assigned to a