diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/ar/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/05-images.mdx index bfed2b90..a516a19b 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T20:02:40.002Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية تحسين الصور nav_title: الصور description: تعلم كيفية تحسين الصور في Next.js diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/ar/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/06-fonts.mdx index 602c8833..f2b223e7 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:27.277Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية استخدام الخطوط nav_title: الخطوط description: تعلم كيفية استخدام الخطوط في Next.js diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/07-css.mdx index 71c103ec..08512eae 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T20:03:14.510Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية استخدام CSS في تطبيقك nav_title: CSS description: تعرف على الطرق المختلفة لإضافة CSS إلى تطبيقك، بما في ذلك وحدات CSS (CSS Modules)، وCSS العام (Global CSS)، وتيلويند CSS (Tailwind CSS)، وغيرها. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/08-server-and-client-components.mdx index d72e5adc..29f28278 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:04:48.815Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية استخدام مكونات الخادم والعميل nav_title: مكونات الخادم والعميل description: تعلم كيف يمكنك استخدام مكونات React للخادم والعميل لتقديم أجزاء من تطبيقك على الخادم أو العميل. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/ar/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index 4f4f4430..4a871359 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:39.535Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية تخزين البيانات مؤقتًا وإعادة التحقق منها nav_title: التخزين المؤقت وإعادة التحقق description: تعلم كيفية تخزين البيانات مؤقتًا وإعادة التحقق منها في تطبيقك. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/11-updating-data.mdx index c74cfc64..4ea82aea 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T17:18:45.960Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية تحديث البيانات nav_title: تحديث البيانات description: تعلم كيفية تحديث البيانات في تطبيق Next.js الخاص بك. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/12-error-handling.mdx index 8a7140d5..230da587 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:26.256Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية التعامل مع الأخطاء nav_title: معالجة الأخطاء description: تعلم كيفية عرض الأخطاء المتوقعة والتعامل مع الاستثناءات غير الملتقطة. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/13-partial-prerendering.mdx index a91063b8..2db1bfcd 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:38.632Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية استخدام التصيير الجزئي المسبق (Partial Prerendering) nav_title: التصيير الجزئي المسبق description: تعلم كيفية الجمع بين مزايا التصيير الثابت والديناميكي باستخدام التصيير الجزئي المسبق. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/ar/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index 696c218f..42cca8bf 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:43.106Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية إضافة بيانات وصفية وإنشاء صور OG nav_title: البيانات الوصفية وصور OG description: تعلم كيفية إضافة بيانات وصفية إلى صفحاتك وإنشاء صور OG ديناميكية. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/15-deploying.mdx similarity index 98% rename from apps/docs/content/ar/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/15-deploying.mdx index b9f99aea..163968e2 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T17:17:41.883Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية نشر تطبيق Next.js الخاص بك nav_title: النشر description: تعلم كيفية نشر تطبيق Next.js الخاص بك. diff --git a/apps/docs/content/ar/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/ar/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 95% rename from apps/docs/content/ar/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/ar/docs/01-app/01-getting-started/16-upgrading.mdx index 80da2c2d..d1023b66 100644 --- a/apps/docs/content/ar/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/ar/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:00:52.683Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: كيفية ترقية تطبيق Next.js الخاص بك nav_title: الترقية description: تعلم كيفية ترقية تطبيق Next.js إلى أحدث إصدار. diff --git a/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index cf78dc3a..00000000 --- a/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:12:10.880Z -title: الربط والتنقل -description: تعرف على كيفية عمل التنقل في Next.js، وكيفية استخدام مكون Link وربط `useRouter`. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -هناك أربع طرق للتنقل بين المسارات في Next.js: - -- استخدام [مكون ``](#link-component) -- استخدام [ربط `useRouter`](#userouter-hook) ([مكونات العميل](/docs/app/getting-started/server-and-client-components)) -- استخدام [دالة `redirect`](#redirect-function) ([مكونات الخادم](/docs/app/getting-started/server-and-client-components)) -- استخدام [واجهة History الأصلية](#using-the-native-history-api) - -ستغطي هذه الصفحة كيفية استخدام كل من هذه الخيارات، والتعمق في كيفية عمل التنقل. - -## مكون `` - -`` هو مكون مدمج يمتد علامة HTML `` لتوفير [الجلب المسبق](#2-prefetching) والتنقل من جانب العميل بين المسارات. إنها الطريقة الأساسية والموصى بها للتنقل بين المسارات في Next.js. - -يمكنك استخدامه عن طريق استيراده من `next/link`، وتمرير خاصية `href` إلى المكون: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return لوحة التحكم -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return لوحة التحكم -} -``` - -هناك خصائص اختيارية أخرى يمكنك تمريرها إلى ``. راجع [مرجع API](/docs/app/api-reference/components/link) للمزيد. - -## ربط `useRouter()` - -يسمح لك ربط `useRouter` بتغيير المسارات برمجيًا من [مكونات العميل](/docs/app/getting-started/server-and-client-components). - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -للحصول على قائمة كاملة بطرق `useRouter`، راجع [مرجع API](/docs/app/api-reference/functions/use-router). - -> **التوصية:** استخدم مكون `` للتنقل بين المسارات ما لم يكن لديك متطلب محدد لاستخدام `useRouter`. - -## دالة `redirect` - -بالنسبة لـ [مكونات الخادم](/docs/app/getting-started/server-and-client-components)، استخدم دالة `redirect` بدلاً من ذلك. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **معلومة مفيدة**: -> -> - تُرجع `redirect` رمز حالة 307 (إعادة توجيه مؤقت) افتراضيًا. عند استخدامها في إجراء خادم، تُرجع 303 (انظر آخر)، والذي يُستخدم عادةً لإعادة التوجيه إلى صفحة نجاح نتيجة لطلب POST. -> - تُطلق `redirect` خطأ داخليًا لذا يجب استدعاؤها خارج كتل `try/catch`. -> - يمكن استدعاء `redirect` في مكونات العميل أثناء عملية التصيير ولكن ليس في معالج الأحداث. يمكنك استخدام [ربط `useRouter`](#userouter-hook) بدلاً من ذلك. -> - تقبل `redirect` أيضًا عناوين URL المطلقة ويمكن استخدامها لإعادة التوجيه إلى روابط خارجية. -> - إذا كنت ترغب في إعادة التوجيه قبل عملية التصيير، استخدم [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) أو [الوسيط](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -راجع [مرجع API لـ `redirect`](/docs/app/api-reference/functions/redirect) للمزيد من المعلومات. - -## استخدام واجهة History الأصلية - -يسمح لك Next.js باستخدام الطرق الأصلية [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) و [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) لتحديث مكدس تاريخ المتصفح دون إعادة تحميل الصفحة. - -تتكامل استدعاءات `pushState` و `replaceState` مع موجه Next.js، مما يسمح لك بالمزامنة مع [`usePathname`](/docs/app/api-reference/functions/use-pathname) و [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). - -### `window.history.pushState` - -استخدمه لإضافة إدخال جديد إلى مكدس تاريخ المتصفح. يمكن للمستخدم التنقل للخلف إلى الحالة السابقة. على سبيل المثال، لفرز قائمة المنتجات: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -استخدمه لاستبدال الإدخال الحالي في مكدس تاريخ المتصفح. لا يمكن للمستخدم التنقل للخلف إلى الحالة السابقة. على سبيل المثال، لتبديل لغة التطبيق: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // مثال: '/en/about' أو '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // مثال: '/en/about' أو '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## كيف يعمل التوجيه والتنقل - -يستخدم موجه التطبيق نهجًا هجينًا للتوجيه والتنقل. على الخادم، يتم [تقسيم الكود](#1-code-splitting) تلقائيًا حسب مقاطع المسار. وعلى العميل، يقوم Next.js [بجلب مسبق](#2-prefetching) و[تخزين مؤقت](#3-caching) لمقاطع المسار. هذا يعني أنه عندما ينتقل المستخدم إلى مسار جديد، لا يعيد المتصفح تحميل الصفحة، ويعاد تصيير فقط مقاطع المسار التي تتغير - مما يحسن تجربة التنقل والأداء. - -### 1. تقسيم الكود - -يسمح لك تقسيم الكود بتقسيم كود التطبيق إلى حزم أصغر ليتم تنزيلها وتنفيذها بواسطة المتصفح. هذا يقلل من كمية البيانات المنقولة ووقت التنفيذ لكل طلب، مما يؤدي إلى تحسين الأداء. - -تسمح لك [مكونات الخادم](/docs/app/getting-started/server-and-client-components) بتقسيم كود التطبيق تلقائيًا حسب مقاطع المسار. هذا يعني أنه يتم تحميل الكود المطلوب فقط للمسار الحالي عند التنقل. - -### 2. الجلب المسبق - -الجلب المسبق هو طريقة لتحميل مسار مسبقًا في الخلفية قبل أن يزوره المستخدم. - -هناك طريقتان لجلب المسارات مسبقًا في Next.js: - -- **مكون ``**: يتم جلب المسارات مسبقًا تلقائيًا عندما تصبح مرئية في نافذة عرض المستخدم. يحدث الجلب المسبق عند تحميل الصفحة لأول مرة أو عندما تظهر في العرض من خلال التمرير. -- **`router.prefetch()`**: يمكن استخدام ربط `useRouter` لجلب المسارات مسبقًا برمجيًا. - -يختلف سلوك الجلب المسبق الافتراضي لـ `` (أي عندما تكون خاصية `prefetch` غير محددة أو مضبوطة على `null`) اعتمادًا على استخدامك لـ [`loading.js`](/docs/app/api-reference/file-conventions/loading). يتم جلب التخطيط المشترك فقط، أسفل "شجرة" المكونات المصيرية حتى ملف `loading.js` الأول، وتخزينه مؤقتًا لمدة `30s`. هذا يقلل من تكلفة جلب مسار ديناميكي كامل، ويعني أنه يمكنك عرض [حالة تحميل فورية](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) لردود فعل مرئية أفضل للمستخدمين. - -يمكنك تعطيل الجلب المسبق عن طريق ضبط خاصية `prefetch` على `false`. بدلاً من ذلك، يمكنك جلب بيانات الصفحة الكاملة مسبقًا خارج حدود التحميل عن طريق ضبط خاصية `prefetch` على `true`. - -راجع [مرجع API لـ ``](/docs/app/api-reference/components/link) للمزيد من المعلومات. - -> **معلومة مفيدة**: -> -> - لا يتم تمكين الجلب المسبق في وضع التطوير، فقط في الإنتاج. - -### 3. التخزين المؤقت - -يحتوي Next.js على **تخزين مؤقت من جانب العميل في الذاكرة** يسمى [تخزين مؤقت للموجه](/docs/app/deep-dive/caching#client-side-router-cache). بينما يتنقل المستخدمون في التطبيق، يتم تخزين حمولة مكون خادم React لمقاطع المسار [المجموعة مسبقًا](#2-prefetching) والمسارات التي تمت زيارتها في التخزين المؤقت. - -هذا يعني عند التنقل، يتم إعادة استخدام التخزين المؤقت قدر الإمكان، بدلاً من إجراء طلب جديد إلى الخادم - مما يحسن الأداء عن طريق تقليل عدد الطلبات والبيانات المنقولة. - -تعرف على المزيد حول كيفية عمل [تخزين مؤقت للموجه](/docs/app/deep-dive/caching#client-side-router-cache) وكيفية تكوينه. - -### 4. التصيير الجزئي - -يعني التصيير الجزئي أنه يتم إعادة تصيير فقط مقاطع المسار التي تتغير عند التنقل على العميل، ويتم الحفاظ على أي مقاطع مشتركة. - -على سبيل المثال، عند التنقل بين مسارين شقيقين، `/dashboard/settings` و `/dashboard/analytics`، سيتم إلغاء تحميل صفحة `settings`، وسيتم تحميل صفحة `analytics` بحالة جديدة، وسيتم الحفاظ على تخطيط `dashboard` المشترك. هذا السلوك موجود أيضًا بين مسارين على نفس المقطع الديناميكي مثل `/blog/[slug]/page` والتنقل من `/blog/first` إلى `/blog/second`. - -كيف يعمل التصيير الجزئي - -بدون التصيير الجزئي، سيؤدي كل تنقل إلى إعادة تصيير الصفحة الكاملة على العميل. يؤدي تصيير المقطع الذي يتغير فقط إلى تقليل كمية البيانات المنقولة ووقت التنفيذ، مما يؤدي إلى تحسين الأداء. - -### 5. التنقل الناعم - -يقوم المتصفحات بتنفيذ "تنقل صعب" عند التنقل بين الصفحات. يمكّن موجه تطبيق Next.js "التنقل الناعم" بين الصفحات، مما يضمن إعادة تصيير فقط مقاطع المسار التي تغيرت (تصيير جزئي). هذا يمكّن من الحفاظ على حالة React للعميل أثناء التنقل. - -### 6. التنقل للخلف وللأمام - -افتراضيًا، ستحافظ Next.js على موضع التمرير للتنقل للخلف وللأمام، وإعادة استخدام مقاطع المسار في [تخزين مؤقت للموجه](/docs/app/deep-dive/caching#client-side-router-cache). - -### 7. التوجيه بين `pages/` و `app/` - -عند الترحيل التدريجي من `pages/` إلى `app/`، سيتعامل موجه Next.js تلقائيًا مع التنقل الصلب بين الاثنين. للكشف عن الانتقالات من `pages/` إلى `app/`، هناك مرشح موجه عميل يستخدم التحقق الاحتمالي لمسارات التطبيق، مما قد يؤدي في بعض الأحيان إلى نتائج إيجابية خاطئة. افتراضيًا، يجب أن تكون مثل هذه الحالات نادرة جدًا، حيث نقوم بتكوين احتمالية النتيجة الإيجابية الخاطئة لتكون 0.01%. يمكن تخصيص هذه الاحتمالية عبر خيار `experimental.clientRouterFilterAllowedRate` في `next.config.js`. من المهم ملاحظة أن خفض معدل النتائج الإيجابية الخاطئة سيزيد من حجم المرشح الذي تم إنشاؤه في حزمة العميل. - -بدلاً من ذلك، إذا كنت تفضل تعطيل هذه المعالجة تمامًا وإدارة التوجيه بين `pages/` و `app/` يدويًا، يمكنك ضبط `experimental.clientRouterFilter` على false في `next.config.js`. عند تعطيل هذه الميزة، لن يتم التنقل بشكل صحيح افتراضيًا إلى أي مسارات ديناميكية في الصفحات التي تتداخل مع مسارات التطبيق. \ No newline at end of file diff --git a/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index b451a04c..00000000 --- a/apps/docs/content/ar/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:11:37.831Z -title: واجهة التحميل والبث المباشر -description: مبنية على Suspense، تتيح لك واجهة التحميل إنشاء واجهة احتياطية لأجزاء مسار محددة، وبث المحتوى تلقائيًا بمجرد استعداده. ---- - -يساعدك الملف الخاص `loading.js` في إنشاء واجهة تحميل ذات معنى باستخدام [React Suspense](https://react.dev/reference/react/Suspense). باستخدام هذه الاتفاقية، يمكنك عرض [حالة تحميل فورية](#instant-loading-states) من الخادم أثناء تحميل محتوى جزء المسار. يتم استبدال المحتوى الجديد تلقائيًا بمجرد اكتمال التقديم. - -واجهة التحميل - -## حالات التحميل الفورية - -حالة التحميل الفورية هي واجهة مستخدم احتياطية تُعرض فورًا عند التنقل. يمكنك تقديم مؤشرات تحميل مسبقًا مثل الهياكل العظمية (skeletons) والدوائر الدوارة (spinners)، أو جزء صغير ولكن ذو معنى من الشاشات المستقبلية مثل صورة الغلاف، العنوان، إلخ. هذا يساعد المستخدمين على فهم أن التطبيق يستجيب ويوفر تجربة مستخدم أفضل. - -قم بإنشاء حالة تحميل عن طريق إضافة ملف `loading.js` داخل مجلد. - -ملف loading.js الخاص - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // يمكنك إضافة أي واجهة مستخدم داخل Loading، بما في ذلك الهيكل العظمي. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // يمكنك إضافة أي واجهة مستخدم داخل Loading، بما في ذلك الهيكل العظمي. - return -} -``` - -في نفس المجلد، سيتم تداخل `loading.js` داخل `layout.js`. سيتم لف ملف `page.js` وأي أطفال تحته تلقائيًا في حدود ``. - -نظرة عامة على loading.js - -> **معلومة مفيدة**: -> -> - التنقل فوري، حتى مع [التوجيه المركزي للخادم](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - التنقل قابل للمقاطعة، مما يعني أن تغيير المسارات لا يحتاج إلى انتظار تحميل محتوى المسار بالكامل قبل التنقل إلى مسار آخر. -> - تبقى التخطيطات المشتركة قابلة للتشغيل أثناء تحميل أجزاء المسار الجديدة. - -> **توصية:** استخدم اتفاقية `loading.js` لأجزاء المسار (التخطيطات والصفحات) حيث يقوم Next.js بتحسين هذه الوظيفة. - -## البث المباشر مع Suspense - -بالإضافة إلى `loading.js`، يمكنك أيضًا إنشاء حدود Suspense يدويًا لمكونات واجهة المستخدم الخاصة بك. يدعم موجه التطبيق (App Router) البث المباشر باستخدام [Suspense](https://react.dev/reference/react/Suspense). - -> **معلومة مفيدة**: -> -> - [بعض المتصفحات](https://bugs.webkit.org/show_bug.cgi?id=252413) تقوم بتخزين استجابة البث مؤقتًا. قد لا ترى الاستجابة المبثوثة حتى تتجاوز الاستجابة 1024 بايت. هذا يؤثر عادةً فقط على تطبيقات "hello world" البسيطة، وليس التطبيقات الحقيقية. - -### ما هو البث المباشر؟ - -لفهم كيفية عمل البث المباشر في React وNext.js، من المفيد فهم **التقديم من جانب الخادم (SSR)** ومحدودياته. - -مع SSR، هناك سلسلة من الخطوات التي يجب إكمالها قبل أن يتمكن المستخدم من رؤية الصفحة والتفاعل معها: - -1. أولاً، يتم جلب جميع البيانات لصفحة معينة على الخادم. -2. ثم يقوم الخادم بتقديم HTML للصفحة. -3. يتم إرسال HTML وCSS وJavaScript للصفحة إلى العميل. -4. يتم عرض واجهة مستخدم غير تفاعلية باستخدام HTML المُنشأ وCSS. -5. أخيرًا، يقوم React [بترطيب (hydrate)](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) واجهة المستخدم لجعلها تفاعلية. - -مخطط يوضح التقديم من الخادم بدون بث مباشر - -هذه الخطوات متسلسلة وحظرية، مما يعني أن الخادم يمكنه فقط تقديم HTML للصفحة بمجرد جلب جميع البيانات. وعلى العميل، يمكن لـ React فقط ترطيب واجهة المستخدم بمجرد تنزيل كود جميع المكونات في الصفحة. - -يساعد SSR مع React وNext.js في تحسين أداء التحميل الملحوظ عن طريق عرض صفحة غير تفاعلية للمستخدم في أسرع وقت ممكن. - -التقديم من الخادم بدون بث مباشر - -ومع ذلك، يمكن أن يظل بطيئًا حيث يجب إكمال جلب جميع البيانات على الخادم قبل إمكانية عرض الصفحة للمستخدم. - -**البث المباشر** يسمح لك بتقسيم HTML للصفحة إلى أجزاء أصغر وإرسال تلك الأجزاء تدريجيًا من الخادم إلى العميل. - -كيف يعمل التقديم من الخادم مع البث المباشر - -هذا يمكّن أجزاء من الصفحة من الظهور عاجلاً، دون انتظار تحميل جميع البيانات قبل أن يمكن تقديم أي واجهة مستخدم. - -يعمل البث المباشر بشكل جيد مع نموذج مكونات React حيث يمكن اعتبار كل مكون جزءًا. يمكن إرسال المكونات ذات الأولوية الأعلى (مثل معلومات المنتج) أو التي لا تعتمد على البيانات أولاً (مثل التخطيط)، ويمكن لـ React بدء الترطيب مبكرًا. يمكن إرسال المكونات ذات الأولوية المنخفضة (مثل المراجعات، المنتجات ذات الصلة) في نفس طلب الخادم بعد جلب بياناتها. - -مخطط يوضح التقديم من الخادم مع البث المباشر - -البث المباشر مفيد بشكل خاص عندما تريد منع طلبات البيانات الطويلة من حظر عرض الصفحة حيث يمكنه تقليل [وقت أول بايت (TTFB)](https://web.dev/ttfb/) و[أول رسم للمحتوى (FCP)](https://web.dev/first-contentful-paint/). كما أنه يساعد في تحسين [الوقت للتفاعل (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/)، خاصة على الأجهزة الأبطأ. - -### مثال - -يعمل `` عن طريق لف مكون يقوم بإجراء عمل غير متزامن (مثل جلب البيانات)، وعرض واجهة مستخدم احتياطية (مثل هيكل عظمي، دائرة دوارة) أثناء حدوثه، ثم استبدال مكونك بمجرد اكتمال الإجراء. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- جاري تحميل التغذية...

}> - -
- جاري تحميل الطقس...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- جاري تحميل التغذية...

}> - -
- جاري تحميل الطقس...

}> - -
-
- ) -} -``` - -باستخدام Suspense، تحصل على فوائد: - -1. **تقديم الخادم مع البث المباشر** - تقديم HTML تدريجيًا من الخادم إلى العميل. -2. **الترطيب الانتقائي** - يعطي React الأولوية للمكونات التي يجب جعلها تفاعلية أولاً بناءً على تفاعل المستخدم. - -لمزيد من أمثلة وحالات استخدام Suspense، يرجى الاطلاع على [توثيق React](https://react.dev/reference/react/Suspense). - -### تحسين محركات البحث (SEO) - -- سينتظر Next.js اكتمال جلب البيانات داخل [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) قبل بث واجهة المستخدم إلى العميل. وهذا يضمن أن الجزء الأول من الاستجابة المبثوثة يتضمن علامات ``. -- نظرًا لأن البث المباشر يتم تقديمه من الخادم، فإنه لا يؤثر على SEO. يمكنك استخدام أداة [Rich Results Test](https://search.google.com/test/rich-results) من Google لمعرفة كيف تظهر صفحتك لمحركات البحث الخاصة بـ Google وعرض HTML المسلسل ([المصدر](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### رموز الحالة - -عند البث المباشر، سيتم إرجاع رمز حالة `200` للإشارة إلى نجاح الطلب. - -يمكن للخادم أن يواصل إبلاغ العميل بالأخطاء أو المشكلات داخل المحتوى المبثوث نفسه، على سبيل المثال، عند استخدام [`redirect`](/docs/app/api-reference/functions/redirect) أو [`notFound`](/docs/app/api-reference/functions/not-found). نظرًا لأنه تم بالفعل إرسال رؤوس الاستجابة إلى العميل، لا يمكن تحديث رمز حالة الاستجابة. هذا لا يؤثر على SEO. - -## دعم المنصة - -| خيار النشر | مدعوم | -| ----------------------------------------------------------- | ------------- | -| [خادم Node.js](/docs/app/getting-started/deploying#nodejs-server) | نعم | -| [حاوية Docker](/docs/app/getting-started/deploying#docker) | نعم | -| [تصدير ثابت](/docs/app/getting-started/deploying#static-export) | لا | -| [المحولات](/docs/app/getting-started/deploying#adapters) | حسب المنصة | - -تعلم كيفية [تكوين البث المباشر](/docs/app/guides/self-hosting#streaming-and-suspense) عند استضافة Next.js ذاتيًا. \ No newline at end of file diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/de/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/05-images.mdx index 8a3d8a70..392dee67 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T20:03:27.028Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Optimierung von Bildern nav_title: Bilder description: Erfahren Sie, wie Sie Bilder in Next.js optimieren können diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/de/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/06-fonts.mdx index 930363ec..ec0ca887 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:03:13.403Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Verwendung von Schriftarten nav_title: Schriftarten description: Erfahren Sie, wie Sie Schriftarten in Next.js verwenden können diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/07-css.mdx index 57bc14fb..5ae8c279 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T20:03:45.455Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Verwendung von CSS in Ihrer Anwendung nav_title: CSS description: Erfahren Sie mehr über die verschiedenen Möglichkeiten, CSS in Ihrer Anwendung zu verwenden, einschließlich CSS-Modulen, globalem CSS, Tailwind CSS und mehr. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/08-server-and-client-components.mdx index 13f0a7a2..e8b3eee1 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:05:29.335Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Verwendung von Server- und Client-Komponenten nav_title: Server- und Client-Komponenten description: Erfahren Sie, wie Sie React Server- und Client-Komponenten verwenden können, um Teile Ihrer Anwendung auf dem Server oder Client zu rendern. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/de/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/de/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index 808a84a0..74de48bd 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:03:19.411Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Daten cachen und revalidieren nav_title: Caching und Revalidierung description: Erfahren Sie, wie Sie Daten in Ihrer Anwendung cachen und revalidieren können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/11-updating-data.mdx index 8e233012..44ddbb4b 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T17:18:41.105Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Datenaktualisierung durchführen nav_title: Daten aktualisieren description: Erfahren Sie, wie Sie Daten in Ihrer Next.js-Anwendung aktualisieren können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/12-error-handling.mdx index 02818010..610e61b1 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:03:12.714Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Umgang mit Fehlern nav_title: Fehlerbehandlung description: Erfahren Sie, wie Sie erwartete Fehler anzeigen und unbehandelte Ausnahmen verwalten können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/13-partial-prerendering.mdx index 9faf70f7..1690673c 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:03:21.152Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Verwendung von Partial Prerendering nav_title: Partial Prerendering description: Erfahren Sie, wie Sie die Vorteile von statischem und dynamischem Rendering mit Partial Prerendering kombinieren können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/de/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index bfd93392..1ec61f1f 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:03:37.493Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Metadaten hinzufügen und OG-Bilder erstellen nav_title: Metadaten und OG-Bilder description: Erfahren Sie, wie Sie Metadaten zu Ihren Seiten hinzufügen und dynamische OG-Bilder erstellen können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/15-deploying.mdx similarity index 97% rename from apps/docs/content/de/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/15-deploying.mdx index 11320443..8d81642a 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T17:17:34.025Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Bereitstellung Ihrer Next.js-Anwendung nav_title: Bereitstellung description: Erfahren Sie, wie Sie Ihre Next.js-Anwendung bereitstellen können. diff --git a/apps/docs/content/de/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/de/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 95% rename from apps/docs/content/de/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/de/docs/01-app/01-getting-started/16-upgrading.mdx index 5866c258..af72ff87 100644 --- a/apps/docs/content/de/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/de/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:37.517Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: So aktualisieren Sie Ihre Next.js-App nav_title: Aktualisierung description: Erfahren Sie, wie Sie Ihre Next.js-Anwendung auf die neueste Version aktualisieren können. diff --git a/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index 0685e214..00000000 --- a/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:13:15.217Z -title: Verlinkung und Navigation -description: Erfahren Sie, wie Navigation in Next.js funktioniert und wie Sie die Link-Komponente sowie den `useRouter`-Hook verwenden. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -In Next.js gibt es vier Möglichkeiten, zwischen Routen zu navigieren: - -- Verwendung der [``-Komponente](#link-component) -- Verwendung des [`useRouter`-Hooks](#userouter-hook) ([Client Components](/docs/app/getting-started/server-and-client-components)) -- Verwendung der [`redirect`-Funktion](#redirect-function) ([Server Components](/docs/app/getting-started/server-and-client-components)) -- Verwendung der nativen [History API](#using-the-native-history-api) - -Diese Seite erklärt die Verwendung dieser Optionen und geht tiefer auf die Funktionsweise der Navigation ein. - -## ``-Komponente - -`` ist eine eingebaute Komponente, die das HTML-`
`-Tag erweitert, um [Prefetching](#2-prefetching) und clientseitige Navigation zwischen Routen zu ermöglichen. Es ist die primäre und empfohlene Methode für die Navigation zwischen Routen in Next.js. - -Sie können sie verwenden, indem Sie sie aus `next/link` importieren und der Komponente eine `href`-Prop übergeben: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -Es gibt weitere optionale Props, die Sie an `` übergeben können. Weitere Informationen finden Sie in der [API-Referenz](/docs/app/api-reference/components/link). - -## `useRouter()`-Hook - -Der `useRouter`-Hook ermöglicht es Ihnen, Routen programmatisch aus [Client Components](/docs/app/getting-started/server-and-client-components) zu ändern. - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -Eine vollständige Liste der `useRouter`-Methoden finden Sie in der [API-Referenz](/docs/app/api-reference/functions/use-router). - -> **Empfehlung:** Verwenden Sie die ``-Komponente für die Navigation zwischen Routen, es sei denn, Sie haben einen spezifischen Grund für die Verwendung von `useRouter`. - -## `redirect`-Funktion - -Für [Server Components](/docs/app/getting-started/server-and-client-components) verwenden Sie stattdessen die `redirect`-Funktion. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **Wissenswertes**: -> -> - `redirect` gibt standardmäßig einen 307 (Temporary Redirect)-Statuscode zurück. Bei Verwendung in einer Server Action wird ein 303 (See Other) zurückgegeben, der häufig für die Weiterleitung zu einer Erfolgsseite nach einer POST-Anfrage verwendet wird. -> - `redirect` wirft intern einen Fehler aus und sollte daher außerhalb von `try/catch`-Blöcken aufgerufen werden. -> - `redirect` kann in Client Components während des Rendering-Prozesses aufgerufen werden, jedoch nicht in Event-Handlern. Verwenden Sie stattdessen den [`useRouter`-Hook](#userouter-hook). -> - `redirect` akzeptiert auch absolute URLs und kann für Weiterleitungen zu externen Links verwendet werden. -> - Wenn Sie vor dem Rendering-Prozess weiterleiten möchten, verwenden Sie [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) oder [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -Weitere Informationen finden Sie in der [`redirect`-API-Referenz](/docs/app/api-reference/functions/redirect). - -## Verwendung der nativen History API - -Next.js ermöglicht die Verwendung der nativen Methoden [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) und [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState), um den Browserverlauf zu aktualisieren, ohne die Seite neu zu laden. - -Aufrufe von `pushState` und `replaceState` werden in den Next.js-Router integriert, sodass Sie sie mit [`usePathname`](/docs/app/api-reference/functions/use-pathname) und [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) synchronisieren können. - -### `window.history.pushState` - -Verwenden Sie diese Methode, um einen neuen Eintrag zum Browserverlauf hinzuzufügen. Der Benutzer kann zum vorherigen Zustand zurücknavigieren. Beispielsweise zum Sortieren einer Produktliste: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -Verwenden Sie diese Methode, um den aktuellen Eintrag im Browserverlauf zu ersetzen. Der Benutzer kann nicht zum vorherigen Zustand zurücknavigieren. Beispielsweise zum Wechseln der Anwendungssprache: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // z.B. '/en/about' oder '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // z.B. '/en/about' oder '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## Funktionsweise von Routing und Navigation - -Der App Router verwendet einen hybriden Ansatz für Routing und Navigation. Auf dem Server wird Ihr Anwendungscode automatisch nach [Route-Segmenten aufgeteilt](#1-code-splitting). Auf dem Client prefetcht und cached Next.js die [Route-Segmente](#2-prefetching). Das bedeutet, dass bei der Navigation zu einer neuen Route die Seite nicht neu geladen wird und nur die sich ändernden Route-Segmente neu gerendert werden – was die Navigationserfahrung und Leistung verbessert. - -### 1. Code Splitting - -Code Splitting ermöglicht es, Ihren Anwendungscode in kleinere Bundles aufzuteilen, die vom Browser heruntergeladen und ausgeführt werden können. Dies reduziert die übertragene Datenmenge und die Ausführungszeit für jede Anfrage und verbessert so die Leistung. - -[Server Components](/docs/app/getting-started/server-and-client-components) ermöglichen die automatische Aufteilung Ihres Anwendungscodes nach Route-Segmenten. Das bedeutet, dass nur der Code für die aktuelle Route bei der Navigation geladen wird. - -### 2. Prefetching - -Prefetching ist eine Methode, um eine Route im Hintergrund vorzuladen, bevor der Benutzer sie besucht. - -Es gibt zwei Möglichkeiten, wie Routen in Next.js geprefetcht werden: - -- **``-Komponente**: Routen werden automatisch geprefetcht, sobald sie im Blickfeld des Benutzers erscheinen. Das Prefetching erfolgt beim ersten Laden der Seite oder beim Scrollen in den sichtbaren Bereich. -- **`router.prefetch()`**: Der `useRouter`-Hook kann verwendet werden, um Routen programmatisch vorzuladen. - -Das Standard-Prefetching-Verhalten von `` (d.h. wenn die `prefetch`-Prop nicht angegeben oder auf `null` gesetzt ist) unterscheidet sich je nach Verwendung von [`loading.js`](/docs/app/api-reference/file-conventions/loading). Nur das gemeinsame Layout bis zur ersten `loading.js`-Datei im gerenderten "Baum" der Komponenten wird geprefetcht und für `30s` gecacht. Dies reduziert die Kosten für das Abrufen einer gesamten dynamischen Route und ermöglicht die Anzeige eines [sofortigen Ladezustands](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) für bessere visuelle Rückmeldung an den Benutzer. - -Sie können das Prefetching deaktivieren, indem Sie die `prefetch`-Prop auf `false` setzen. Alternativ können Sie die vollständigen Seitendaten über die Ladegrenzen hinaus prefetchen, indem Sie die `prefetch`-Prop auf `true` setzen. - -Weitere Informationen finden Sie in der [``-API-Referenz](/docs/app/api-reference/components/link). - -> **Wissenswertes**: -> -> - Prefetching ist in der Entwicklung nicht aktiviert, nur in der Produktion. - -### 3. Caching - -Next.js verfügt über einen **clientseitigen In-Memory-Cache** namens [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). Wenn Benutzer durch die App navigieren, werden die React Server Component Payloads von [geprefetchten](#2-prefetching) Route-Segmenten und besuchten Routen im Cache gespeichert. - -Das bedeutet, dass bei der Navigation der Cache so weit wie möglich wiederverwendet wird, anstatt eine neue Anfrage an den Server zu stellen – was die Leistung durch Reduzierung der Anzahl der Anfragen und der übertragenen Daten verbessert. - -Erfahren Sie mehr über die Funktionsweise des [Router Caches](/docs/app/deep-dive/caching#client-side-router-cache) und dessen Konfiguration. - -### 4. Partielles Rendering - -Partielles Rendering bedeutet, dass nur die Route-Segmente, die sich bei der Navigation ändern, clientseitig neu gerendert werden, während gemeinsame Segmente erhalten bleiben. - -Beispielsweise wird beim Navigieren zwischen zwei Geschwisterrouten, `/dashboard/settings` und `/dashboard/analytics`, die `settings`-Seite ausgeblendet, die `analytics`-Seite mit frischem Zustand eingeblendet und das gemeinsame `dashboard`-Layout beibehalten. Dieses Verhalten tritt auch zwischen zwei Routen auf demselben dynamischen Segment auf, z.B. bei `/blog/[slug]/page` und der Navigation von `/blog/first` zu `/blog/second`. - -Wie partielles Rendering funktioniert - -Ohne partielles Rendering würde jede Navigation ein vollständiges Neu-Rendering der Seite auf dem Client verursachen. Das Rendern nur des sich ändernden Segments reduziert die übertragene Datenmenge und die Ausführungszeit, was die Leistung verbessert. - -### 5. Soft Navigation - -Browser führen eine "Hard Navigation" durch, wenn zwischen Seiten navigiert wird. Der Next.js App Router ermöglicht eine "Soft Navigation" zwischen Seiten, bei der nur die sich ändernden Route-Segmente neu gerendert werden (partielles Rendering). Dadurch bleibt der clientseitige React-Zustand während der Navigation erhalten. - -### 6. Vor- und Zurück-Navigation - -Standardmäßig behält Next.js die Scroll-Position für Vor- und Zurück-Navigation bei und verwendet Route-Segmente aus dem [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) wieder. - -### 7. Routing zwischen `pages/` und `app/` - -Bei der schrittweisen Migration von `pages/` zu `app/` behandelt der Next.js-Router die Hard Navigation zwischen den beiden automatisch. Um Übergänge von `pages/` zu `app/` zu erkennen, gibt es einen Client-Router-Filter, der probabilistische Prüfungen von App-Routen nutzt, was gelegentlich zu falsch positiven Ergebnissen führen kann. Standardmäßig sollten solche Vorkommnisse sehr selten sein, da wir die Wahrscheinlichkeit für falsch positive Ergebnisse auf 0,01 % konfigurieren. Diese Wahrscheinlichkeit kann über die Option `experimental.clientRouterFilterAllowedRate` in `next.config.js` angepasst werden. Es ist wichtig zu beachten, dass eine Senkung der falsch positiven Rate die Größe des generierten Filters im Client-Bundle erhöht. - -Alternativ können Sie diese automatische Handhabung deaktivieren und das Routing zwischen `pages/` und `app/` manuell verwalten, indem Sie `experimental.clientRouterFilter` in `next.config.js` auf `false` setzen. Wenn diese Funktion deaktiviert ist, werden dynamische Routen in pages, die mit app-Routen überlappen, standardmäßig nicht korrekt angesteuert. \ No newline at end of file diff --git a/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index ea05bb5f..00000000 --- a/apps/docs/content/de/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:12:23.580Z -title: Lade-UI und Streaming -description: Auf Suspense aufbauend ermöglicht das Lade-UI die Erstellung eines Fallbacks für bestimmte Routensegmente und streamt Inhalte automatisch, sobald sie bereitstehen. ---- - -Die spezielle Datei `loading.js` hilft Ihnen, aussagekräftige Lade-UIs mit [React Suspense](https://react.dev/reference/react/Suspense) zu erstellen. Mit dieser Konvention können Sie einen [sofortigen Ladezustand](#instant-loading-states) vom Server anzeigen, während der Inhalt eines Routensegments geladen wird. Der neue Inhalt wird automatisch eingeblendet, sobald das Rendering abgeschlossen ist. - -Lade-UI - -## Sofortige Ladezustände - -Ein sofortiger Ladezustand ist eine Fallback-UI, die unmittelbar bei der Navigation angezeigt wird. Sie können Ladeindikatoren wie Skelette oder Spinner vorrendern oder einen kleinen, aber bedeutungsvollen Teil zukünftiger Bildschirme wie ein Titelbild, Titel usw. Dies hilft Benutzern zu verstehen, dass die Anwendung reagiert, und bietet eine bessere Benutzererfahrung. - -Erstellen Sie einen Ladezustand, indem Sie eine `loading.js`-Datei in einem Ordner hinzufügen. - -loading.js spezielle Datei - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // Sie können jede UI innerhalb von Loading hinzufügen, einschließlich eines Skeletts. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // Sie können jede UI innerhalb von Loading hinzufügen, einschließlich eines Skeletts. - return -} -``` - -Im selben Ordner wird `loading.js` innerhalb von `layout.js` verschachtelt. Es wird automatisch die `page.js`-Datei und alle untergeordneten Elemente in eine ``-Grenze einwickeln. - -loading.js Übersicht - -> **Wissenswert**: -> -> - Die Navigation ist unmittelbar, auch mit [serverzentriertem Routing](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - Die Navigation ist unterbrechbar, d.h. das Wechseln der Route muss nicht warten, bis der Inhalt der Route vollständig geladen ist, bevor zu einer anderen Route navigiert wird. -> - Gemeinsame Layouts bleiben interaktiv, während neue Routensegmente laden. - -> **Empfehlung:** Verwenden Sie die `loading.js`-Konvention für Routensegmente (Layouts und Seiten), da Next.js diese Funktionalität optimiert. - -## Streaming mit Suspense - -Zusätzlich zu `loading.js` können Sie auch manuell Suspense-Grenzen für Ihre eigenen UI-Komponenten erstellen. Der App-Router unterstützt Streaming mit [Suspense](https://react.dev/reference/react/Suspense). - -> **Wissenswert**: -> -> - [Einige Browser](https://bugs.webkit.org/show_bug.cgi?id=252413) puffern eine Streaming-Antwort. Möglicherweise sehen Sie die gestreamte Antwort erst, wenn die Antwort 1024 Bytes überschreitet. Dies betrifft normalerweise nur "Hallo Welt"-Anwendungen, nicht jedoch reale Anwendungen. - -### Was ist Streaming? - -Um zu verstehen, wie Streaming in React und Next.js funktioniert, ist es hilfreich, **Server-Side Rendering (SSR)** und seine Grenzen zu kennen. - -Bei SSR müssen mehrere Schritte abgeschlossen werden, bevor ein Benutzer eine Seite sehen und mit ihr interagieren kann: - -1. Zuerst werden alle Daten für eine bestimmte Seite auf dem Server abgerufen. -2. Der Server rendert dann das HTML für die Seite. -3. Das HTML, CSS und JavaScript für die Seite werden an den Client gesendet. -4. Eine nicht-interaktive Benutzeroberfläche wird mit dem generierten HTML und CSS angezeigt. -5. Schließlich [hydriert](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) React die Benutzeroberfläche, um sie interaktiv zu machen. - -Diagramm zum Server-Rendering ohne Streaming - -Diese Schritte sind sequenziell und blockierend, d.h. der Server kann das HTML für eine Seite erst rendern, wenn alle Daten abgerufen wurden. Und auf dem Client kann React die UI erst hydrieren, wenn der Code für alle Komponenten der Seite heruntergeladen wurde. - -SSR mit React und Next.js verbessert die wahrgenommene Ladeleistung, indem dem Benutzer so schnell wie möglich eine nicht-interaktive Seite angezeigt wird. - -Server-Rendering ohne Streaming - -Es kann jedoch immer noch langsam sein, da alle Datenabfragen auf dem Server abgeschlossen sein müssen, bevor die Seite dem Benutzer angezeigt werden kann. - -**Streaming** ermöglicht es Ihnen, das HTML einer Seite in kleinere Teile aufzuteilen und diese schrittweise vom Server an den Client zu senden. - -Wie Server-Rendering mit Streaming funktioniert - -Dadurch können Teile der Seite früher angezeigt werden, ohne auf das Laden aller Daten warten zu müssen, bevor irgendeine UI gerendert werden kann. - -Streaming funktioniert gut mit dem Komponentenmodell von React, da jede Komponente als Teil betrachtet werden kann. Komponenten mit höherer Priorität (z.B. Produktinformationen) oder solche, die keine Daten benötigen, können zuerst gesendet werden (z.B. Layout), und React kann früher mit der Hydration beginnen. Komponenten mit niedrigerer Priorität (z.B. Bewertungen, verwandte Produkte) können in derselben Serveranfrage gesendet werden, nachdem ihre Daten abgerufen wurden. - -Diagramm zum Server-Rendering mit Streaming - -Streaming ist besonders nützlich, wenn Sie verhindern möchten, dass lange Datenanfragen das Rendern der Seite blockieren, da es die [Time To First Byte (TTFB)](https://web.dev/ttfb/) und [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/) reduzieren kann. Es verbessert auch die [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), insbesondere auf langsameren Geräten. - -### Beispiel - -`` funktioniert, indem es eine Komponente umschließt, die eine asynchrone Aktion ausführt (z.B. Daten abruft), währenddessen eine Fallback-UI (z.B. Skelett, Spinner) anzeigt und dann Ihre Komponente einblendet, sobald die Aktion abgeschlossen ist. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Lade Feed...

}> - -
- Lade Wetter...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Lade Feed...

}> - -
- Lade Wetter...

}> - -
-
- ) -} -``` - -Durch die Verwendung von Suspense erhalten Sie die Vorteile von: - -1. **Streaming Server Rendering** - Fortschreitendes Rendern von HTML vom Server zum Client. -2. **Selektive Hydration** - React priorisiert, welche Komponenten zuerst interaktiv gemacht werden, basierend auf Benutzerinteraktionen. - -Weitere Suspense-Beispiele und Anwendungsfälle finden Sie in der [React-Dokumentation](https://react.dev/reference/react/Suspense). - -### SEO - -- Next.js wartet, bis die Datenabfrage innerhalb von [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) abgeschlossen ist, bevor die UI an den Client gestreamt wird. Dadurch wird sichergestellt, dass der erste Teil einer gestreamten Antwort ``-Tags enthält. -- Da Streaming servergerendert ist, hat es keine Auswirkungen auf die SEO. Sie können das [Rich Results Test](https://search.google.com/test/rich-results)-Tool von Google verwenden, um zu sehen, wie Ihre Seite für die Webcrawler von Google erscheint, und das serialisierte HTML anzuzeigen ([Quelle](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### Statuscodes - -Beim Streaming wird ein `200`-Statuscode zurückgegeben, um anzuzeigen, dass die Anfrage erfolgreich war. - -Der Server kann dem Client weiterhin Fehler oder Probleme innerhalb des gestreamten Inhalts mitteilen, z.B. bei Verwendung von [`redirect`](/docs/app/api-reference/functions/redirect) oder [`notFound`](/docs/app/api-reference/functions/not-found). Da die Antwortheader bereits an den Client gesendet wurden, kann der Statuscode der Antwort nicht aktualisiert werden. Dies hat keine Auswirkungen auf die SEO. - -## Plattformunterstützung - -| Bereitstellungsoption | Unterstützt | -| ------------------------------------------------------------------- | ----------------- | -| [Node.js-Server](/docs/app/getting-started/deploying#nodejs-server) | Ja | -| [Docker-Container](/docs/app/getting-started/deploying#docker) | Ja | -| [Statischer Export](/docs/app/getting-started/deploying#static-export) | Nein | -| [Adapter](/docs/app/getting-started/deploying#adapters) | Plattformspezifisch | - -Erfahren Sie, wie Sie [Streaming konfigurieren](/docs/app/guides/self-hosting#streaming-and-suspense), wenn Sie Next.js selbst hosten. \ No newline at end of file diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/02-project-structure.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/02-project-structure.mdx index 056e332b..2de5d3d3 100644 --- a/apps/docs/content/en/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/apps/docs/content/en/docs/01-app/01-getting-started/02-project-structure.mdx @@ -375,7 +375,7 @@ To opt specific routes into a layout, create a new route group (e.g. `(shop)`) a ### Opting for loading skeletons on a specific route -To apply a [loading skeleton](/docs/app/building-your-application/routing/loading-ui-and-streaming) via a `loading.js` file to a specific route, create a new route group (e.g., `/(overview)`) and then move your `loading.tsx` inside that route group. +To apply a [loading skeleton](/docs/app/api-reference/file-conventions/loading) via a `loading.js` file to a specific route, create a new route group (e.g., `/(overview)`) and then move your `loading.tsx` inside that route group. Folder structure showing a loading.tsx and a page.tsx inside the route group` component](/docs/app/api-reference/components/link) to navigate between routes. `` is a built-in Next.js component that extends the HTML `
` tag to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) and [client-side navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation). +You can use the [`` component](/docs/app/api-reference/components/link) to navigate between routes. `` is a built-in Next.js component that extends the HTML `` tag to provide [prefetching](/docs/app/getting-started/linking-and-navigating#prefetching) and [client-side navigation](/docs/app/getting-started/linking-and-navigating#client-side-transitions). For example, to generate a list of blog posts, import `` from `next/link` and pass a `href` prop to the component: @@ -289,4 +290,4 @@ export default async function Post({ post }) { } ``` -`` is the primary and recommended way to navigate between routes in your Next.js application. However, you can also use the [`useRouter` hook](/docs/app/api-reference/functions/use-router) for more advanced navigation. +> **Good to know**: `` is the primary way to navigate between routes in Next.js. You can also use the [`useRouter` hook](/docs/app/api-reference/functions/use-router) for more advanced navigation. diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/04-linking-and-navigating.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/04-linking-and-navigating.mdx new file mode 100644 index 00000000..b201ad72 --- /dev/null +++ b/apps/docs/content/en/docs/01-app/01-getting-started/04-linking-and-navigating.mdx @@ -0,0 +1,464 @@ +--- +title: Linking and Navigating +description: Learn how prefetching, prerendering, and client-side navigation works in Next.js, and how to use the Link Component. +related: + links: + - app/api-reference/components/link + - app/api-reference/file-conventions/loading +--- + +In Next.js, routes are rendered on the server by default. This often means the client has to wait for a server response before a new route can be shown. Next.js comes built-in [prefetching](#prefetching), [streaming](#streaming), and [client-side transitions](#client-side-transitions) ensuring navigation stays fast and responsive. + +This guide explains how navigation works in Next.js and how you can optimize it for [dynamic routes](#dynamic-routes-without-loadingtsx) and [slow networks](#slow-networks). + +## How navigation works + +To understand how navigation works in Next.js, it helps to be familiar with the following concepts: + +- [Server Rendering](#server-rendering) +- [Prefetching](#prefetching) +- [Streaming](#streaming) +- [Client-side transitions](#client-side-transitions) + +### Server Rendering + +In Next.js, [Layouts and Pages](/docs/app/getting-started/layouts-and-pages) are [React Server Components](https://react.dev/reference/rsc/server-components) by default. On initial and subsequent navigations, the [Server Component Payload](/docs/app/getting-started/server-and-client-components#how-do-server-and-client-components-work-in-nextjs) is generated on the server before being sent to the client. + +There are two types of server rendering, based on _when_ it happens: + +- **Static Rendering (or Prerendering)** happens at build time or during [revalidation](/docs/app/getting-started/caching-and-revalidating) and the result is cached. +- **Dynamic Rendering** happens at request time in response to a client request. + +The trade-off of server rendering is that the client must wait for the server to respond before the new route can be shown. Next.js addresses this delay by [prefetching](#prefetching) routes the user is likely to visit and performing [client-side transitions](#client-side-transitions). + +> **Good to know**: HTML is also generated for the initial visit. + +### Prefetching + +Prefetching is the process of loading a route in the background before the user navigates to it. This makes navigation between routes in your application feel instant, because by the time a user clicks on a link, the data to render the next route is already available client side. + +Next.js automatically prefetches routes linked with the [`` component](/docs/app/api-reference/components/link) when they enter the user's viewport. + +```tsx filename="app/layout.tsx" switcher +import Link from 'next/link' + +export default function Layout({ children }: { children: React.ReactNode }) { + return ( + + + + {children} + + + ) +} +``` + +```jsx filename="app/blog/page.js" switcher +import Link from 'next/link' + +export default function Layout() { + return ( + + + + {children} + + + ) +} +``` + +How much of the route is prefetched depends on whether it's static or dynamic: + +- **Static Route**: the full route is prefetched. +- **Dynamic Route**: prefetching is skipped, or the route is partially prefetched if [`loading.tsx`](/docs/app/api-reference/file-conventions/loading) is present. + +By skipping or partially prefetching dynamic routes, Next.js avoids unnecessary work on the server for routes the users may never visit. However, waiting for a server response before navigation can give the users the impression that the app is not responding. + +Server Rendering without Streaming + +To improve the navigation experience to dynamic routes, you can use [streaming](#streaming). + +### Streaming + +Streaming allows the server to send parts of a dynamic route to the client as soon as they're ready, rather than waiting for the entire route to be rendered. This means users see something sooner, even if parts of the page are still loading. + +For dynamic routes, it means they can be **partially prefetched**. That is, shared layouts and loading skeletons can be requested ahead of time. + +How Server Rendering with Streaming Works + +To use streaming, create a `loading.tsx` in your route folder: + +loading.js special file + +```tsx filename="app/dashboard/loading.tsx" switcher +export default function Loading() { + // Add fallback UI that will be shown while the route is loading. + return +} +``` + +```jsx filename="app/dashboard/loading.js" switcher +export default function Loading() { + // Add fallback UI that will be shown while the route is loading. + return +} +``` + +Behind the scenes, Next.js will automatically wrap the `page.tsx` contents and in a `` boundary. The prefetched fallback UI will be shown while the route is loading, and swapped for the actual content once ready. + +> **Good to know**: You can also use [``](https://react.dev/reference/react/Suspense) to create loading UI for nested components. + +Benefits of `loading.tsx`: + +- Immediate navigation and visual feedback for the user. +- Shared layouts remain interactive and navigation is interruptible. +- Improved Core Web Vitals: [TTFB](https://web.dev/articles/ttfb), [FCP](https://web.dev/articles/fcp), and [TTI](https://web.dev/articles/tti). + +To further improve the navigation experience, Next.js performs a [client-side transition](#client-side-transitions) with the `` component. + +### Client-side transitions + +Traditionally, navigation to a server-rendered page triggers a full page load. This clears state, resets scroll position, and blocks interactivity. + +Next.js avoids this with client-side transitions using the `` component. Instead of reloading the page, it updates the content dynamically by: + +- Keeping any shared layouts and UI. +- Replacing the current page with the prefetched loading state or a new page if available. + +Client-side transitions are what makes a server-rendered apps _feel_ like client-rendered apps. And when paired with [prefetching](#prefetching) and [streaming](#streaming), it enables fast transitions, even for dynamic routes. + +## What can make transitions slow? + +These Next.js optimizations make navigation fast and responsive. However, under certain conditions, transitions can still _feel_ slow. Here are some common causes and how to improve the user experience: + +### Dynamic routes without `loading.tsx` + +When navigating to a dynamic route, the client must wait for the server response before showing the result. This can give the users the impression that the app is not responding. + +We recommend adding `loading.tsx` to dynamic routes to enable partial prefetching, trigger immediate navigation, and display a loading UI while the route renders. + +```tsx filename="app/blog/[slug]/loading.tsx" switcher +export default function Loading() { + return +} +``` + +```jsx filename="app/blog/[slug]/loading.js" switcher +export default function Loading() { + return +} +``` + +> **Good to know**: In development mode, you can use the Next.js Devtools to identify if the route is static or dynamic. See [`devIndicators`](/docs/app/api-reference/config/next-config-js/devIndicators) for more information. + +### Dynamic segments without `generateStaticParams` + +If a [dynamic segment](/docs/app/api-reference/file-conventions/dynamic-routes) could be prerendered but isn't because it's missing [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), the route will fallback to dynamic rendering at request time. + +Ensure the route is statically generated at build time by adding `generateStaticParams`: + +```tsx filename="app/blog/[slug]/page.tsx" switcher +export async function generateStaticParams() { + const posts = await fetch('https://.../posts').then((res) => res.json()) + + return posts.map((post) => ({ + slug: post.slug, + })) +} + +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const { slug } = await params + // ... +} +``` + +```jsx filename="app/blog/[slug]/page.js" switcher +export async function generateStaticParams() { + const posts = await fetch('https://.../posts').then((res) => res.json()) + + return posts.map((post) => ({ + slug: post.slug, + })) + +export default async function Page({ params }) { + const { slug } = await params + // ... +} +``` + +### Slow networks + +On slow or unstable networks, prefetching may not finish before the user clicks a link. This can affect both static and dynamic routes. In these cases, the `loading.js` fallback may not appear immediately because it hasn't been prefetched yet. + +To improve perceived performance, you can use the [`useLinkStatus` hook](/docs/app/api-reference/functions/use-link-status) to show inline visual feedback to the user (like spinners or text glimmers on the link) while a transition is in progress. + +```tsx +'use client' + +import { useLinkStatus } from 'next/link' + +export default function LoadingIndicator() { + const { pending } = useLinkStatus() + return pending ? ( +
+ ) : null +} +``` + +```tsx +'use client' + +import { useLinkStatus } from 'next/link' + +export default function LoadingIndicator() { + const { pending } = useLinkStatus() + return pending ? ( +
+ ) : null +} +``` + +You can "debounce" the loading indicator by adding an initial animation delay (e.g. 100ms) and starting the animation as invisible (e.g. `opacity: 0`). This means the loading indicator will only be shown if the navigation takes longer than the specified delay. + +```css +.spinner { + /* ... */ + opacity: 0; + animation: + fadeIn 500ms 100ms forwards, + rotate 1s linear infinite; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes rotate { + to { + transform: rotate(360deg); + } +} +``` + +> **Good to know**: You can use other visual feedback patterns like a progress bar. View an example [here](https://github.com/vercel/react-transition-progress). + +### Disabling prefetching + +You can opt out of prefetching by setting the `prefetch` prop to `false` on the `` component. This is useful to avoid unnecessary usage of resources when rendering large lists of links (e.g. an infinite scroll table). + +```tsx + + Blog + +``` + +However, disabling prefetching comes with trade-offs: + +- **Static routes** will only be fetched when the user clicks the link. +- **Dynamic routes** will need to be rendered on the server first before the client can navigate to it. + +To reduce resouce usage without fully disabling prefetch, you can prefetch only on hover. This limits prefetching to routes the user is more _likely_ to visit, rather all links in the viewport. + +```tsx filename="app/ui/hover-prefetch-link.tsx" switcher +'use client' + +import Link from 'next/link' +import { useState } from 'react' + +function HoverPrefetchLink({ + href, + children, +}: { + href: string + children: React.ReactNode +}) { + const [active, setActive] = useState(false) + + return ( + setActive(true)} + > + {children} + + ) +} +``` + +```jsx filename="app/ui/hover-prefetch-link.js" switcher +'use client' + +import Link from 'next/link' +import { useState } from 'react' + +function HoverPrefetchLink({ href, children }) { + const [active, setActive] = useState(false) + + return ( + setActive(true)} + > + {children} + + ) +} +``` + +### Hydration not completed + +`` is a Client Component and must be hydrated before it can prefetch routes. On the initial visit, large JavaScript bundles can delay hydration, preventing prefetching from starting right away. + +React mitigates this with Selective Hydration and you can further improve this by: + +- Using the [`@next/bundle-analyzer`](/docs/app/guides/package-bundling#analyzing-javascript-bundles) plugin to identify and reduce bundle size by removing large dependencies. +- Moving logic from the client to the server where possible. See the [Server and Client Components](/docs/app/getting-started/server-and-client-components) docs for guidance. + +## Examples + +### Native History API + +Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page. + +`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). + +#### `window.history.pushState` + +Use it to add a new entry to the browser's history stack. The user can navigate back to the previous state. For example, to sort a list of products: + +```tsx fileName="app/ui/sort-products.tsx" switcher +'use client' + +import { useSearchParams } from 'next/navigation' + +export default function SortProducts() { + const searchParams = useSearchParams() + + function updateSorting(sortOrder: string) { + const params = new URLSearchParams(searchParams.toString()) + params.set('sort', sortOrder) + window.history.pushState(null, '', `?${params.toString()}`) + } + + return ( + <> + + + + ) +} +``` + +```jsx fileName="app/ui/sort-products.js" switcher +'use client' + +import { useSearchParams } from 'next/navigation' + +export default function SortProducts() { + const searchParams = useSearchParams() + + function updateSorting(sortOrder) { + const params = new URLSearchParams(searchParams.toString()) + params.set('sort', sortOrder) + window.history.pushState(null, '', `?${params.toString()}`) + } + + return ( + <> + + + + ) +} +``` + +#### `window.history.replaceState` + +Use it to replace the current entry on the browser's history stack. The user is not able to navigate back to the previous state. For example, to switch the application's locale: + +```tsx fileName="app/ui/locale-switcher.tsx" switcher +'use client' + +import { usePathname } from 'next/navigation' + +export function LocaleSwitcher() { + const pathname = usePathname() + + function switchLocale(locale: string) { + // e.g. '/en/about' or '/fr/contact' + const newPath = `/${locale}${pathname}` + window.history.replaceState(null, '', newPath) + } + + return ( + <> + + + + ) +} +``` + +```jsx fileName="app/ui/locale-switcher.js" switcher +'use client' + +import { usePathname } from 'next/navigation' + +export function LocaleSwitcher() { + const pathname = usePathname() + + function switchLocale(locale) { + // e.g. '/en/about' or '/fr/contact' + const newPath = `/${locale}${pathname}` + window.history.replaceState(null, '', newPath) + } + + return ( + <> + + + + ) +} +``` diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/05-images.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/05-images.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/06-fonts.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/06-fonts.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/07-css.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/07-css.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/08-server-and-client-components.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 98% rename from apps/docs/content/en/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/09-fetching-data.mdx index 6cbd7bb1..5c97c4fc 100644 --- a/apps/docs/content/en/docs/01-app/01-getting-started/08-fetching-data.mdx +++ b/apps/docs/content/en/docs/01-app/01-getting-started/09-fetching-data.mdx @@ -478,7 +478,7 @@ async function Playlists({ artistID }) { } ``` -To improve the user experience, you should use [React ``](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) to show a `fallback` while data is being fetch. This will enable [streaming](#streaming) and prevent the whole route from being blocked by the sequential data requests. +To improve the user experience, you should use [React ``](/docs/app/getting-started/linking-and-navigating#streaming) to show a `fallback` while data is being fetch. This will enable [streaming](#streaming) and prevent the whole route from being blocked by the sequential data requests. ### Parallel data fetching diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/11-updating-data.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/12-error-handling.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/13-partial-prerendering.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/15-deploying.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/15-deploying.mdx diff --git a/apps/docs/content/en/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/en/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 100% rename from apps/docs/content/en/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/en/docs/01-app/01-getting-started/16-upgrading.mdx diff --git a/apps/docs/content/en/docs/01-app/02-guides/authentication.mdx b/apps/docs/content/en/docs/01-app/02-guides/authentication.mdx index 2f7c011e..7f25ea33 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/authentication.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/authentication.mdx @@ -1028,7 +1028,7 @@ There are some cases where you may want to use [Middleware](/docs/app/building-y - To perform optimistic checks. Since Middleware runs on every route, it's a good way to centralize redirect logic and pre-filter unauthorized users. - To protect static routes that share data between users (e.g. content behind a paywall). -However, since Middleware runs on every route, including [prefetched](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) routes, it's important to only read the session from the cookie (optimistic checks), and avoid database checks to prevent performance issues. +However, since Middleware runs on every route, including [prefetched](/docs/app/getting-started/linking-and-navigating#prefetching) routes, it's important to only read the session from the cookie (optimistic checks), and avoid database checks to prevent performance issues. For example: @@ -1347,7 +1347,7 @@ In the example, we use the `verifySession()` function from our DAL to check for ### Layouts and auth checks -Due to [Partial Rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), be cautious when doing checks in [Layouts](/docs/app/api-reference/file-conventions/layout) as these don't re-render on navigation, meaning the user session won't be checked on every route change. +Due to [Partial Rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions), be cautious when doing checks in [Layouts](/docs/app/api-reference/file-conventions/layout) as these don't re-render on navigation, meaning the user session won't be checked on every route change. Instead, you should do the checks close to your data source or the component that'll be conditionally rendered. diff --git a/apps/docs/content/en/docs/01-app/02-guides/lazy-loading.mdx b/apps/docs/content/en/docs/01-app/02-guides/lazy-loading.mdx index 4e0b477a..7d42ded2 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/lazy-loading.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/lazy-loading.mdx @@ -15,7 +15,7 @@ There are two ways you can implement lazy loading in Next.js: 1. Using [Dynamic Imports](#nextdynamic) with `next/dynamic` 2. Using [`React.lazy()`](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense) -By default, Server Components are automatically [code split](https://developer.mozilla.org/docs/Glossary/Code_splitting), and you can use [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) to progressively send pieces of UI from the server to the client. Lazy loading applies to Client Components. +By default, Server Components are automatically [code split](https://developer.mozilla.org/docs/Glossary/Code_splitting), and you can use [streaming](/docs/app/api-reference/file-conventions/loading) to progressively send pieces of UI from the server to the client. Lazy loading applies to Client Components. ## `next/dynamic` diff --git a/apps/docs/content/en/docs/01-app/02-guides/migrating/app-router-migration.mdx b/apps/docs/content/en/docs/01-app/02-guides/migrating/app-router-migration.mdx index 9dae588f..361c1acf 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/migrating/app-router-migration.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/migrating/app-router-migration.mdx @@ -60,7 +60,7 @@ There are two codemods to help you migrate to the new Image Component: ### `` Component -The [`` Component](/docs/app/building-your-application/routing/linking-and-navigating#link-component) no longer requires manually adding an `` tag as a child. This behavior was added as an experimental option in [version 12.2](https://nextjs.org/blog/next-12-2) and is now the default. In Next.js 13, `` always renders `` and allows you to forward props to the underlying tag. +The [`` Component](/docs/app/api-reference/components/link) no longer requires manually adding an `` tag as a child. This behavior was added as an experimental option in [version 12.2](https://nextjs.org/blog/next-12-2) and is now the default. In Next.js 13, `` always renders `` and allows you to forward props to the underlying tag. For example: diff --git a/apps/docs/content/en/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/apps/docs/content/en/docs/01-app/02-guides/migrating/from-create-react-app.mdx index 07224660..58be925b 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -29,7 +29,7 @@ While client-side data fetching is supported in Next.js, Next.js also lets you m ### Fast and intentional loading states -With built-in support for [streaming through React Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense), you can define which parts of your UI load first and in what order, without creating network waterfalls. +With built-in support for [streaming through React Suspense](/docs/app/getting-started/linking-and-navigating#streaming), you can define which parts of your UI load first and in what order, without creating network waterfalls. This enables you to build pages that are faster to load and eliminate [layout shifts](https://vercel.com/blog/how-core-web-vitals-affect-seo). @@ -571,7 +571,7 @@ If everything worked, you now have a functioning Next.js application running as - **Migrate from React Router** to the [Next.js App Router](/docs/app/building-your-application/routing) for: - Automatic code splitting - - [Streaming server rendering](/docs/app/building-your-application/routing/loading-ui-and-streaming) + - [Streaming server rendering](/docs/app/api-reference/file-conventions/loading) - [React Server Components](/docs/app/getting-started/server-and-client-components) - **Optimize images** with the [`` component](/docs/app/api-reference/components/image) - **Optimize fonts** with [`next/font`](/docs/app/api-reference/components/font) diff --git a/apps/docs/content/en/docs/01-app/02-guides/migrating/from-vite.mdx b/apps/docs/content/en/docs/01-app/02-guides/migrating/from-vite.mdx index f5b7aaab..313df9f0 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/migrating/from-vite.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/migrating/from-vite.mdx @@ -29,7 +29,7 @@ While fetching data on the client is supported with Next.js, it also gives you t ### Fast and intentional loading states -With built-in support for [streaming through React Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense), you can be more intentional about which parts of your UI you want to load first and in what order without introducing network waterfalls. +With built-in support for [streaming through React Suspense](/docs/app/getting-started/linking-and-navigating#streaming), you can be more intentional about which parts of your UI you want to load first and in what order without introducing network waterfalls. This enables you to build pages that are faster to load and eliminate [layout shifts](https://vercel.com/blog/how-core-web-vitals-affect-seo). @@ -594,7 +594,7 @@ do next: - Migrate from React Router to the [Next.js App Router](/docs/app/building-your-application/routing) to get: - Automatic code splitting - - [Streaming Server-Rendering](/docs/app/building-your-application/routing/loading-ui-and-streaming) + - [Streaming Server-Rendering](/docs/app/api-reference/file-conventions/loading) - [React Server Components](/docs/app/getting-started/server-and-client-components) - [Optimize images with the `` component](/docs/app/api-reference/components/image) - [Optimize fonts with `next/font`](/docs/app/api-reference/components/font) diff --git a/apps/docs/content/en/docs/01-app/02-guides/production-checklist.mdx b/apps/docs/content/en/docs/01-app/02-guides/production-checklist.mdx index 710596c8..ee09b326 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/production-checklist.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/production-checklist.mdx @@ -15,8 +15,8 @@ These Next.js optimizations are enabled by default and require no configuration: - **[Server Components](/docs/app/getting-started/server-and-client-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/getting-started/server-and-client-components) as needed for interactivity. -- **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. -- **[Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. +- **[Code-splitting](/docs/app/getting-started/linking-and-navigating#how-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. +- **[Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Static Rendering](/docs/app/getting-started/partial-prerendering#static-rendering):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} - **[Caching](/docs/app/deep-dive/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. @@ -40,8 +40,8 @@ While building your application, we recommend using the following features to en -- **[Layouts](/docs/app/api-reference/file-conventions/layout):** Use layouts to share UI across pages and enable [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering) on navigation. -- **[`` component](/docs/app/building-your-application/routing/linking-and-navigating#link-component):** Use the `` component for [client-side navigation and prefetching](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). +- **[Layouts](/docs/app/api-reference/file-conventions/layout):** Use layouts to share UI across pages and enable [partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions) on navigation. +- **[`` component](/docs/app/api-reference/components/link):** Use the `` component for [client-side navigation and prefetching](/docs/app/getting-started/linking-and-navigating#how-navigation-works). - **[Error Handling](/docs/app/getting-started/error-handling):** Gracefully handle [catch-all errors](/docs/app/getting-started/error-handling) and [404 errors](/docs/app/api-reference/file-conventions/not-found) in production by creating custom error pages. - **[Client and Server Components](/docs/app/getting-started/server-and-client-components#examples):** Follow the recommended composition patterns for Server and Client Components, and check the placement of your [`"use client"` boundaries](/docs/app/getting-started/server-and-client-components#examples#moving-client-components-down-the-tree) to avoid unnecessarily increasing your client-side JavaScript bundle. - **[Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering):** Be aware that Dynamic APIs like [`cookies`](/docs/app/api-reference/functions/cookies) and the [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) prop will opt the entire route into [Dynamic Rendering](/docs/app/getting-started/partial-prerendering#dynamic-rendering) (or your whole application if used in the [Root Layout](/docs/app/api-reference/file-conventions/layout#root-layout)). Ensure Dynamic API usage is intentional and wrap them in `` boundaries where appropriate. @@ -63,7 +63,7 @@ While building your application, we recommend using the following features to en - **[Server Components](/docs/app/getting-started/fetching-data):** Leverage the benefits of fetching data on the server using Server Components. - **[Route Handlers](/docs/app/building-your-application/routing/route-handlers):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request. -- **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. +- **[Streaming](/docs/app/api-reference/file-conventions/loading):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Parallel Data Fetching](/docs/app/getting-started/fetching-data#parallel-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/getting-started/fetching-data#preloading-data) where appropriate. - **[Data Caching](/docs/app/deep-dive/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). - **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. diff --git a/apps/docs/content/en/docs/01-app/02-guides/self-hosting.mdx b/apps/docs/content/en/docs/01-app/02-guides/self-hosting.mdx index 301d2eb6..19075444 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/self-hosting.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/self-hosting.mdx @@ -187,7 +187,7 @@ When the application is reloaded, there may be a loss of application state if it ## Streaming and Suspense -The Next.js App Router supports [streaming responses](/docs/app/building-your-application/routing/loading-ui-and-streaming) when self-hosting. If you are using Nginx or a similar proxy, you will need to configure it to disable buffering to enable streaming. +The Next.js App Router supports [streaming responses](/docs/app/api-reference/file-conventions/loading) when self-hosting. If you are using Nginx or a similar proxy, you will need to configure it to disable buffering to enable streaming. For example, you can disable buffering in Nginx by setting `X-Accel-Buffering` to `no`: diff --git a/apps/docs/content/en/docs/01-app/02-guides/single-page-applications.mdx b/apps/docs/content/en/docs/01-app/02-guides/single-page-applications.mdx index 391f986f..8c0d23c1 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/single-page-applications.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/single-page-applications.mdx @@ -347,7 +347,7 @@ export default function SortProducts() { } ``` -Learn more about how [routing and navigation](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works) work in Next.js. +Learn more about how [routing and navigation](/docs/app/getting-started/linking-and-navigating#how-navigation-works) work in Next.js. ### Using Server Actions in Client Components diff --git a/apps/docs/content/en/docs/01-app/02-guides/videos.mdx b/apps/docs/content/en/docs/01-app/02-guides/videos.mdx index b31d993c..048a9444 100644 --- a/apps/docs/content/en/docs/01-app/02-guides/videos.mdx +++ b/apps/docs/content/en/docs/01-app/02-guides/videos.mdx @@ -108,7 +108,7 @@ export default async function VideoComponent() { **2. Stream the video component using React Suspense** -After creating the Server Component to embed the video, the next step is to [stream](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming) the component using [React Suspense](https://react.dev/reference/react/Suspense). +After creating the Server Component to embed the video, the next step is to [stream](https://nextjs.org/docs/app/api-reference/file-conventions/loading) the component using [React Suspense](https://react.dev/reference/react/Suspense). ```jsx filename="app/page.jsx" import { Suspense } from 'react' diff --git a/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index 3c475455..00000000 --- a/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,320 +0,0 @@ ---- -title: Linking and Navigating -description: Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -There are four ways to navigate between routes in Next.js: - -- Using the [`` Component](#link-component) -- Using the [`useRouter` hook](#userouter-hook) ([Client Components](/docs/app/getting-started/server-and-client-components)) -- Using the [`redirect` function](#redirect-function) ([Server Components](/docs/app/getting-started/server-and-client-components)) -- Using the native [History API](#using-the-native-history-api) - -This page will go through how to use each of these options, and dive deeper into how navigation works. - -## `` Component - -`` is a built-in component that extends the HTML `` tag to provide [prefetching](#2-prefetching) and client-side navigation between routes. It is the primary and recommended way to navigate between routes in Next.js. - -You can use it by importing it from `next/link`, and passing a `href` prop to the component: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -There are other optional props you can pass to ``. See the [API reference](/docs/app/api-reference/components/link) for more. - -## `useRouter()` hook - -The `useRouter` hook allows you to programmatically change routes from [Client Components](/docs/app/getting-started/server-and-client-components). - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -For a full list of `useRouter` methods, see the [API reference](/docs/app/api-reference/functions/use-router). - -> **Recommendation:** Use the `` component to navigate between routes unless you have a specific requirement for using `useRouter`. - -## `redirect` function - -For [Server Components](/docs/app/getting-started/server-and-client-components), use the `redirect` function instead. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **Good to know**: -> -> - `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request. -> - `redirect` internally throws an error so it should be called outside of `try/catch` blocks. -> - `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead. -> - `redirect` also accepts absolute URLs and can be used to redirect to external links. -> - If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) or [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) for more information. - -## Using the native History API - -Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page. - -`pushState` and `replaceState` calls integrate into the Next.js Router, allowing you to sync with [`usePathname`](/docs/app/api-reference/functions/use-pathname) and [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). - -### `window.history.pushState` - -Use it to add a new entry to the browser's history stack. The user can navigate back to the previous state. For example, to sort a list of products: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -Use it to replace the current entry on the browser's history stack. The user is not able to navigate back to the previous state. For example, to switch the application's locale: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // e.g. '/en/about' or '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // e.g. '/en/about' or '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## How Routing and Navigation Works - -The App Router uses a hybrid approach for routing and navigation. On the server, your application code is automatically [code-split](#1-code-splitting) by route segments. And on the client, Next.js [prefetches](#2-prefetching) and [caches](#3-caching) the route segments. This means, when a user navigates to a new route, the browser doesn't reload the page, and only the route segments that change re-render - improving the navigation experience and performance. - -### 1. Code Splitting - -Code splitting allows you to split your application code into smaller bundles to be downloaded and executed by the browser. This reduces the amount of data transferred and execution time for each request, leading to improved performance. - -[Server Components](/docs/app/getting-started/server-and-client-components) allow your application code to be automatically code-split by route segments. This means only the code needed for the current route is loaded on navigation. - -### 2. Prefetching - -Prefetching is a way to preload a route in the background before the user visits it. - -There are two ways routes are prefetched in Next.js: - -- **`` component**: Routes are automatically prefetched as they become visible in the user's viewport. Prefetching happens when the page first loads or when it comes into view through scrolling. -- **`router.prefetch()`**: The `useRouter` hook can be used to prefetch routes programmatically. - -The ``'s default prefetching behavior (i.e. when the `prefetch` prop is left unspecified or set to `null`) is different depending on your usage of [`loading.js`](/docs/app/api-reference/file-conventions/loading). Only the shared layout, down the rendered "tree" of components until the first `loading.js` file, is prefetched and cached for `30s`. This reduces the cost of fetching an entire dynamic route, and it means you can show an [instant loading state](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) for better visual feedback to users. - -You can disable prefetching by setting the `prefetch` prop to `false`. Alternatively, you can prefetch the full page data beyond the loading boundaries by setting the `prefetch` prop to `true`. - -See the [`` API reference](/docs/app/api-reference/components/link) for more information. - -> **Good to know**: -> -> - Prefetching is not enabled in development, only in production. - -### 3. Caching - -Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. - -This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred. - -Learn more about how the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) works and how to configure it. - -### 4. Partial Rendering - -Partial rendering means only the route segments that change on navigation re-render on the client, and any shared segments are preserved. - -For example, when navigating between two sibling routes, `/dashboard/settings` and `/dashboard/analytics`, the `settings` page will be unmounted, the `analytics` page will be mounted with fresh state, and the shared `dashboard` layout will be preserved. This behavior is also present between two routes on the same dynamic segment e.g. with `/blog/[slug]/page` and navigating from `/blog/first` to `/blog/second`. - -How partial rendering works - -Without partial rendering, each navigation would cause the full page to re-render on the client. Rendering only the segment that changes reduces the amount of data transferred and execution time, leading to improved performance. - -### 5. Soft Navigation - -Browsers perform a "hard navigation" when navigating between pages. The Next.js App Router enables "soft navigation" between pages, ensuring only the route segments that have changed are re-rendered (partial rendering). This enables client React state to be preserved during navigation. - -### 6. Back and Forward Navigation - -By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). - -### 7. Routing between `pages/` and `app/` - -When incrementally migrating from `pages/` to `app/`, the Next.js router will automatically handle hard navigation between the two. To detect transitions from `pages/` to `app/`, there is a client router filter that leverages probabilistic checking of app routes, which can occasionally result in false positives. By default, such occurrences should be very rare, as we configure the false positive likelihood to be 0.01%. This likelihood can be customized via the `experimental.clientRouterFilterAllowedRate` option in `next.config.js`. It's important to note that lowering the false positive rate will increase the size of the generated filter in the client bundle. - -Alternatively, if you prefer to disable this handling completely and manage the routing between `pages/` and `app/` manually, you can set `experimental.clientRouterFilter` to false in `next.config.js`. When this feature is disabled, any dynamic routes in pages that overlap with app routes won't be navigated to properly by default. diff --git a/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 6d81d799..00000000 --- a/apps/docs/content/en/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Loading UI and Streaming -description: Built on top of Suspense, Loading UI allows you to create a fallback for specific route segments, and automatically stream content as it becomes ready. ---- - -The special file `loading.js` helps you create meaningful Loading UI with [React Suspense](https://react.dev/reference/react/Suspense). With this convention, you can show an [instant loading state](#instant-loading-states) from the server while the content of a route segment loads. The new content is automatically swapped in once rendering is complete. - -Loading UI - -## Instant Loading States - -An 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. - -Create a loading state by adding a `loading.js` file inside a folder. - -loading.js special file - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // You can add any UI inside Loading, including a Skeleton. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // You can add any UI inside Loading, including a Skeleton. - return -} -``` - -In 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 `` boundary. - -loading.js overview - -> **Good to know**: -> -> - Navigation is immediate, even with [server-centric routing](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route. -> - Shared layouts remain interactive while new route segments load. - -> **Recommendation:** Use the `loading.js` convention for route segments (layouts and pages) as Next.js optimizes this functionality. - -## Streaming with Suspense - -In addition to `loading.js`, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with [Suspense](https://react.dev/reference/react/Suspense). - -> **Good to know**: -> -> - [Some browsers](https://bugs.webkit.org/show_bug.cgi?id=252413) buffer a streaming response. You may not see the streamed response until the response exceeds 1024 bytes. This typically only affects “hello world” applications, but not real applications. - -### What is Streaming? - -To learn how Streaming works in React and Next.js, it's helpful to understand **Server-Side Rendering (SSR)** and its limitations. - -With SSR, there's a series of steps that need to be completed before a user can see and interact with a page: - -1. First, all data for a given page is fetched on the server. -2. The server then renders the HTML for the page. -3. The HTML, CSS, and JavaScript for the page are sent to the client. -4. A non-interactive user interface is shown using the generated HTML, and CSS. -5. Finally, React [hydrates](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) the user interface to make it interactive. - -Chart showing Server Rendering without Streaming - -These 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. - -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. - -Server Rendering without Streaming - -However, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user. - -**Streaming** allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client. - -How Server Rendering with Streaming Works - -This enables parts of the page to be displayed sooner, without waiting for all the data to load before any UI can be rendered. - -Streaming 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. - -Chart showing Server Rendering with Streaming - -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)](https://web.dev/ttfb/) and [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/). It also helps improve [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), especially on slower devices. - -### Example - -`` 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. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Loading feed...

}> - -
- Loading weather...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Loading feed...

}> - -
- Loading weather...

}> - -
-
- ) -} -``` - -By using Suspense, you get the benefits of: - -1. **Streaming Server Rendering** - Progressively rendering HTML from the server to the client. -2. **Selective Hydration** - React prioritizes what components to make interactive first based on user interaction. - -For more Suspense examples and use cases, please see the [React Documentation](https://react.dev/reference/react/Suspense). - -### SEO - -- Next.js will wait for data fetching inside [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) to complete before streaming UI to the client. This guarantees the first part of a streamed response includes `` tags. -- Since streaming is server-rendered, it does not impact SEO. You can use the [Rich Results Test](https://search.google.com/test/rich-results) tool from Google to see how your page appears to Google's web crawlers and view the serialized HTML ([source](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### Status Codes - -When streaming, a `200` status code will be returned to signal that the request was successful. - -The server can still communicate errors or issues to the client within the streamed content itself, for example, when using [`redirect`](/docs/app/api-reference/functions/redirect) or [`notFound`](/docs/app/api-reference/functions/not-found). Since the response headers have already been sent to the client, the status code of the response cannot be updated. This does not affect SEO. - -## Platform Support - -| Deployment Option | Supported | -| ------------------------------------------------------------------- | ----------------- | -| [Node.js server](/docs/app/getting-started/deploying#nodejs-server) | Yes | -| [Docker container](/docs/app/getting-started/deploying#docker) | Yes | -| [Static export](/docs/app/getting-started/deploying#static-export) | No | -| [Adapters](/docs/app/getting-started/deploying#adapters) | Platform-specific | - -Learn how to [configure streaming](/docs/app/guides/self-hosting#streaming-and-suspense) when self-hosting Next.js. diff --git a/apps/docs/content/en/docs/01-app/04-deep-dive/caching.mdx b/apps/docs/content/en/docs/01-app/04-deep-dive/caching.mdx index deb50262..e6cb955c 100644 --- a/apps/docs/content/en/docs/01-app/04-deep-dive/caching.mdx +++ b/apps/docs/content/en/docs/01-app/04-deep-dive/caching.mdx @@ -314,12 +314,12 @@ You can opt out of the Full Route Cache, or in other words, dynamically render c Next.js has an in-memory client-side router cache that stores the RSC payload of route segments, split by layouts, loading states, and pages. -When a user navigates between routes, Next.js caches the visited route segments and [prefetches](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the routes the user is likely to navigate to. This results in instant back/forward navigation, no full-page reload between navigations, and preservation of React state and browser state. +When a user navigates between routes, Next.js caches the visited route segments and [prefetches](/docs/app/getting-started/linking-and-navigating#prefetching) the routes the user is likely to navigate to. This results in instant back/forward navigation, no full-page reload between navigations, and preservation of React state and browser state. With the Router Cache: -- **Layouts** are cached and reused on navigation ([partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering)). -- **Loading states** are cached and reused on navigation for [instant navigation](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states). +- **Layouts** are cached and reused on navigation ([partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions)). +- **Loading states** are cached and reused on navigation for [instant navigation](/docs/app/api-reference/file-conventions/loading#instant-loading-states). - **Pages** are not cached by default, but are reused during browser backward and forward navigation. You can enable caching for page segments by using the experimental [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes) config option. {/* TODO: Update diagram to match v15 behavior */} @@ -352,7 +352,7 @@ There are two ways you can invalidate the Router Cache: As of Next.js 15, page segments are opted out by default. -> **Good to know:** You can also opt out of [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) by setting the `prefetch` prop of the `` component to `false`. +> **Good to know:** You can also opt out of [prefetching](/docs/app/getting-started/linking-and-navigating#prefetching) by setting the `prefetch` prop of the `` component to `false`. ## Cache Interactions diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/02-components/form.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/02-components/form.mdx index 08acee89..577fb054 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/02-components/form.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/02-components/form.mdx @@ -3,7 +3,7 @@ title: Form description: Learn how to use the `
` component to handle form submissions and search params updates with client-side navigation. --- -The `` component extends the HTML `` element to provide [**prefetching**](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) of [loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming), **client-side navigation** on submission, and **progressive enhancement**. +The `` component extends the HTML `` element to provide [**prefetching**](/docs/app/getting-started/linking-and-navigating#prefetching) of [loading UI](/docs/app/api-reference/file-conventions/loading), **client-side navigation** on submission, and **progressive enhancement**. It's useful for forms that update URL search params as it reduces the boilerplate code needed to achieve the above. @@ -84,8 +84,8 @@ The behavior of the `` component depends on whether the `action` prop is p - When `action` is a **string**, the `` behaves like a native HTML form that uses a **`GET`** method. The form data is encoded into the URL as search params, and when the form is submitted, it navigates to the specified URL. In addition, Next.js: - - [Prefetches](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the path when the form becomes visible, this preloads shared UI (e.g. `layout.js` and `loading.js`), resulting in faster navigation. - - Performs a [client-side navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation) instead of a full page reload when the form is submitted. This retains shared UI and client-side state. + - [Prefetches](/docs/app/getting-started/linking-and-navigating#prefetching) the path when the form becomes visible, this preloads shared UI (e.g. `layout.js` and `loading.js`), resulting in faster navigation. + - Performs a [client-side navigation](/docs/app/getting-started/linking-and-navigating#client-side-transitions) instead of a full page reload when the form is submitted. This retains shared UI and client-side state. - When `action` is a **function** (Server Action), `` behaves like a [React form](https://react.dev/reference/react-dom/components/form), executing the action when the form is submitted. @@ -93,7 +93,7 @@ The behavior of the `` component depends on whether the `action` prop is p - When `action` is a **string**, the `` behaves like a native HTML form that uses a **`GET`** method. The form data is encoded into the URL as search params, and when the form is submitted, it navigates to the specified URL. In addition, Next.js: - - Performs a [client-side navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation) instead of a full page reload when the form is submitted. This retains shared UI and client-side state. + - Performs a [client-side navigation](/docs/app/getting-started/linking-and-navigating#client-side-transitions) instead of a full page reload when the form is submitted. This retains shared UI and client-side state. diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/02-components/link.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/02-components/link.mdx index bf0bdd37..5a512830 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/02-components/link.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/02-components/link.mdx @@ -5,7 +5,7 @@ description: Enable fast client-side navigation with the built-in `next/link` co {/* The content of this doc is shared between the app and pages router. You can use the `Content` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -`` is a React component that extends the HTML `` element to provide [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js. +`` is a React component that extends the HTML `` element to provide [prefetching](/docs/app/getting-started/linking-and-navigating#prefetching) and client-side navigation between routes. It is the primary way to navigate between routes in Next.js. Basic usage: @@ -299,7 +299,7 @@ Prefetching happens when a `` component enters the user's viewport (init The following values can be passed to the `prefetch` prop: -- **`null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) boundary will be prefetched. +- **`null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched. - `true`: The full route will be prefetched for both static and dynamic routes. - `false`: Prefetching will never happen both on entering the viewport and on hover. diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/default.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/default.mdx index e91dbb8f..68f32a30 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/default.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/default.mdx @@ -9,7 +9,7 @@ related: The `default.js` file is used to render a fallback within [Parallel Routes](/docs/app/api-reference/file-conventions/parallel-routes) when Next.js cannot recover a [slot's](/docs/app/api-reference/file-conventions/parallel-routes#slots) active state after a full-page load. -During [soft navigation](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation), Next.js keeps track of the active _state_ (subpage) for each slot. However, for hard navigations (full-page load), Next.js cannot recover the active state. In this case, a `default.js` file can be rendered for subpages that don't match the current URL. +During [soft navigation](/docs/app/getting-started/linking-and-navigating#client-side-transitions), Next.js keeps track of the active _state_ (subpage) for each slot. However, for hard navigations (full-page load), Next.js cannot recover the active state. In this case, a `default.js` file can be rendered for subpages that don't match the current URL. Consider the following folder structure. The `@team` slot has a `settings` page, but `@analytics` does not. diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/layout.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/layout.mdx index 2d44622d..22469ccb 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/layout.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/layout.mdx @@ -53,7 +53,7 @@ export default function RootLayout({ children }) { #### `children` (required) -Layout components should accept and use a `children` prop. During rendering, `children` will be populated with the route segments the layout is wrapping. These will primarily be the component of a child [Layout](/docs/app/api-reference/file-conventions/page) (if it exists) or [Page](/docs/app/api-reference/file-conventions/page), but could also be other special files like [Loading](/docs/app/building-your-application/routing/loading-ui-and-streaming) or [Error](/docs/app/getting-started/error-handling) when applicable. +Layout components should accept and use a `children` prop. During rendering, `children` will be populated with the route segments the layout is wrapping. These will primarily be the component of a child [Layout](/docs/app/api-reference/file-conventions/page) (if it exists) or [Page](/docs/app/api-reference/file-conventions/page), but could also be other special files like [Loading](/docs/app/api-reference/file-conventions/loading) or [Error](/docs/app/getting-started/error-handling) when applicable. #### `params` (optional) diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/loading.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/loading.mdx index 083df343..001af06c 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/loading.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/loading.mdx @@ -3,9 +3,15 @@ title: loading.js description: API reference for the loading.js file. --- -A **loading** file can create instant loading states built on [Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming). +The special file `loading.js` helps you create meaningful Loading UI with [React Suspense](https://react.dev/reference/react/Suspense). With this convention, you can show an [instant loading state](#instant-loading-states) from the server while the content of a route segment streams in. The new content is automatically swapped in once complete. -By default, this file is a [Server Component](/docs/app/getting-started/server-and-client-components) - but can also be used as a Client Component through the `"use client"` directive. +Loading UI ```tsx filename="app/feed/loading.tsx" switcher export default function Loading() { @@ -21,11 +27,138 @@ export default function Loading() { } ``` +Inside the `loading.js` file, you can add any light-weight loading UI. You may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Suspense boundaries. + +By default, this file is a [Server Component](/docs/app/getting-started/server-and-client-components) - but can also be used as a Client Component through the `"use client"` directive. + +## Reference + +### Parameters + Loading UI components do not accept any parameters. -> **Good to know**: -> -> - While designing loading UI, you may find it helpful to use the [React Developer Tools](https://react.dev/learn/react-developer-tools) to manually toggle Suspense boundaries. +## Behavior + +### Navigation + +- The Fallback UI is [prefetched](/docs/app/getting-started/linking-and-navigating#prefetching), making navigation is immediate unless prefetching hasn't completed. +- Navigation is interruptible, meaning changing routes does not need to wait for the content of the route to fully load before navigating to another route. +- Shared layouts remain interactive while new route segments load. + +### Instant Loading States + +An 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. + +Create a loading state by adding a `loading.js` file inside a folder. + +loading.js special file + +```tsx filename="app/dashboard/loading.tsx" switcher +export default function Loading() { + // You can add any UI inside Loading, including a Skeleton. + return +} +``` + +```jsx filename="app/dashboard/loading.js" switcher +export default function Loading() { + // You can add any UI inside Loading, including a Skeleton. + return +} +``` + +In 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 `` boundary. + +loading.js overview + +### SEO + +- Next.js will wait for data fetching inside [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) to complete before streaming UI to the client. This guarantees the first part of a streamed response includes `` tags. +- Since streaming is server-rendered, it does not impact SEO. You can use the [Rich Results Test](https://search.google.com/test/rich-results) tool from Google to see how your page appears to Google's web crawlers and view the serialized HTML ([source](https://web.dev/rendering-on-the-web/#seo-considerations)). + +### Status Codes + +When streaming, a `200` status code will be returned to signal that the request was successful. + +The server can still communicate errors or issues to the client within the streamed content itself, for example, when using [`redirect`](/docs/app/api-reference/functions/redirect) or [`notFound`](/docs/app/api-reference/functions/not-found). Since the response headers have already been sent to the client, the status code of the response cannot be updated. This does not affect SEO. + +### Browser limits + +[Some browsers](https://bugs.webkit.org/show_bug.cgi?id=252413) buffer a streaming response. You may not see the streamed response until the response exceeds 1024 bytes. This typically only affects “hello world” applications, but not real applications. + +## Platform Support + +| Deployment Option | Supported | +| ------------------------------------------------------------------- | ----------------- | +| [Node.js server](/docs/app/getting-started/deploying#nodejs-server) | Yes | +| [Docker container](/docs/app/getting-started/deploying#docker) | Yes | +| [Static export](/docs/app/getting-started/deploying#static-export) | No | +| [Adapters](/docs/app/getting-started/deploying#adapters) | Platform-specific | + +Learn how to [configure streaming](/docs/app/guides/self-hosting#streaming-and-suspense) when self-hosting Next.js. + +## Examples + +### Streaming with Suspense + +In addition to `loading.js`, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with [Suspense](https://react.dev/reference/react/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. + +```tsx filename="app/dashboard/page.tsx" switcher +import { Suspense } from 'react' +import { PostFeed, Weather } from './Components' + +export default function Posts() { + return ( +
+ Loading feed...

}> + +
+ Loading weather...

}> + +
+
+ ) +} +``` + +```jsx filename="app/dashboard/page.js" switcher +import { Suspense } from 'react' +import { PostFeed, Weather } from './Components' + +export default function Posts() { + return ( +
+ Loading feed...

}> + +
+ Loading weather...

}> + +
+
+ ) +} +``` + +By using Suspense, you get the benefits of: + +1. **Streaming Server Rendering** - Progressively rendering HTML from the server to the client. +2. **Selective Hydration** - React prioritizes what components to make interactive first based on user interaction. + +For more Suspense examples and use cases, please see the [React Documentation](https://react.dev/reference/react/Suspense). ## Version History diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/parallel-routes.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/parallel-routes.mdx index a250c4ad..b2210152 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/parallel-routes.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/parallel-routes.mdx @@ -96,7 +96,7 @@ Additionally, since `children` is an implicit slot, you also need to create a `d By default, Next.js keeps track of the active _state_ (or subpage) for each slot. However, the content rendered within a slot will depend on the type of navigation: -- [**Soft Navigation**](/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation): During client-side navigation, Next.js will perform a [partial render](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), changing the subpage within the slot, while maintaining the other slot's active subpages, even if they don't match the current URL. +- [**Soft Navigation**](/docs/app/getting-started/linking-and-navigating#client-side-transitions): During client-side navigation, Next.js will perform a [partial render](/docs/app/getting-started/linking-and-navigating#client-side-transitions), changing the subpage within the slot, while maintaining the other slot's active subpages, even if they don't match the current URL. - **Hard Navigation**: After a full-page load (browser refresh), Next.js cannot determine the active state for the slots that don't match the current URL. Instead, it will render a [`default.js`](#defaultjs) file for the unmatched slots, or `404` if `default.js` doesn't exist. > **Good to know**: @@ -477,4 +477,4 @@ Parallel Routes can be streamed independently, allowing you to define independen height="1218" /> -See the [Loading UI](/docs/app/building-your-application/routing/loading-ui-and-streaming) and [Error Handling](/docs/app/getting-started/error-handling) documentation for more information. +See the [Loading UI](/docs/app/api-reference/file-conventions/loading) and [Error Handling](/docs/app/getting-started/error-handling) documentation for more information. diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/route-segment-config.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/route-segment-config.mdx index 1d571fcf..485b8b5e 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/route-segment-config.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/03-file-conventions/route-segment-config.mdx @@ -86,7 +86,7 @@ export const dynamicParams = true // true | false, > > - This option replaces the `fallback: true | false | blocking` option of `getStaticPaths` in the `pages` directory. > - To statically render all paths the first time they're visited, you'll need to return an empty array in `generateStaticParams` or utilize `export const dynamic = 'force-static'`. -> - When `dynamicParams = true`, the segment uses [Streaming Server Rendering](/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense). +> - When `dynamicParams = true`, the segment uses [Streaming Server Rendering](/docs/app/getting-started/linking-and-navigating#streaming). ### `revalidate` diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/redirect.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/redirect.mdx index 90ec377c..8f44f45f 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/redirect.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/redirect.mdx @@ -8,16 +8,13 @@ related: The `redirect` function allows you to redirect the user to another URL. `redirect` can be used in [Server Components](/docs/app/getting-started/server-and-client-components), [Route Handlers](/docs/app/building-your-application/routing/route-handlers), and [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations). -When used in a [streaming context](/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller. +When used in a [streaming context](/docs/app/getting-started/linking-and-navigating#streaming), this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller. If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api-reference/functions/not-found) instead. -> **Good to know**: -> -> - In Server Actions and Route Handlers, `redirect` should be called after the `try/catch` block. -> - If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the [`permanentRedirect` function](/docs/app/api-reference/functions/permanentRedirect) instead. +## Reference -## Parameters +### Parameters The `redirect` function accepts two arguments: @@ -34,10 +31,19 @@ By default, `redirect` will use `push` (adding a new entry to the browser histor The `type` parameter has no effect when used in Server Components. -## Returns +### Returns `redirect` does not return a value. +## Behavior + +- In Server Actions and Route Handlers, `redirect` should be called after the `try/catch` block. +- If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the [`permanentRedirect` function](/docs/app/api-reference/functions/permanentRedirect) instead. +- `redirect` internally throws an error so it should be called outside of `try/catch` blocks. +- `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](/docs/app/api-reference/functions/use-router) instead. +- `redirect` also accepts absolute URLs and can be used to redirect to external links. +- If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) or [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). + ## Example ### Server Component diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-link-status.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-link-status.mdx index 11bbf42b..29d7e636 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-link-status.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-link-status.mdx @@ -13,7 +13,7 @@ The `useLinkStatus` hook lets you tracks the **pending** state of a ``. Yo `useLinkStatus` is useful when: -- [Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled or in progress meaning navigation is blocked. +- [Prefetching](/docs/app/getting-started/linking-and-navigating#prefetching) is disabled or in progress meaning navigation is blocked. - The destination route is dynamic **and** doesn't include a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file that would allow an instant navigation. ```tsx filename="app/loading-indicator.tsx" switcher diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-router.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-router.mdx index e0b80285..c9a30334 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-router.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-router.mdx @@ -5,7 +5,7 @@ description: API reference for the useRouter hook. The `useRouter` hook allows you to programmatically change routes inside [Client Components](/docs/app/getting-started/server-and-client-components). -> **Recommendation:** Use the [`` component](/docs/app/building-your-application/routing/linking-and-navigating#link-component) for navigation unless you have a specific requirement for using `useRouter`. +> **Recommendation:** Use the [`` component](/docs/app/api-reference/components/link) for navigation unless you have a specific requirement for using `useRouter`. ```tsx filename="app/example-client-component.tsx" switcher 'use client' @@ -44,7 +44,7 @@ export default function Page() { - `router.push(href: string, { scroll: boolean })`: Perform a client-side navigation to the provided route. Adds a new entry into the [browser’s history](https://developer.mozilla.org/docs/Web/API/History_API) stack. - `router.replace(href: string, { scroll: boolean })`: Perform a client-side navigation to the provided route without adding a new entry into the [browser’s history stack](https://developer.mozilla.org/docs/Web/API/History_API). - `router.refresh()`: Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. `useState`) or browser state (e.g. scroll position). -- `router.prefetch(href: string)`: [Prefetch](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) the provided route for faster client-side transitions. +- `router.prefetch(href: string)`: [Prefetch](/docs/app/getting-started/linking-and-navigating#prefetching) the provided route for faster client-side transitions. - `router.back()`: Navigate back to the previous route in the browser’s history stack. - `router.forward()`: Navigate forwards to the next page in the browser’s history stack. @@ -111,7 +111,7 @@ export default function Layout({ children }) { } ``` -> **Good to know**: `` is wrapped in a [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/getting-started/partial-prerendering#static-rendering). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior). +> **Good to know**: `` is wrapped in a [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) because[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params) causes client-side rendering up to the closest `Suspense` boundary during [static rendering](/docs/app/getting-started/partial-prerendering#static-rendering). [Learn more](/docs/app/api-reference/functions/use-search-params#behavior). ### Disabling scroll to top diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-search-params.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-search-params.mdx index 3650cbe3..5dcead44 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-search-params.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/04-functions/use-search-params.mdx @@ -71,14 +71,14 @@ const searchParams = useSearchParams() > **Good to know**: > -> - `useSearchParams` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook and is **not supported** in [Server Components](/docs/app/getting-started/server-and-client-components) to prevent stale values during [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering). +> - `useSearchParams` is a [Client Component](/docs/app/getting-started/server-and-client-components) hook and is **not supported** in [Server Components](/docs/app/getting-started/server-and-client-components) to prevent stale values during [partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions). > - If an application includes the `/pages` directory, `useSearchParams` will return `ReadonlyURLSearchParams | null`. The `null` value is for compatibility during migration since search params cannot be known during pre-rendering of a page that doesn't use `getServerSideProps` ## Behavior ### Static Rendering -If a route is [statically rendered](/docs/app/getting-started/partial-prerendering#static-rendering), calling `useSearchParams` will cause the Client Component tree up to the closest [`Suspense` boundary](/docs/app/building-your-application/routing/loading-ui-and-streaming#example) to be client-side rendered. +If a route is [statically rendered](/docs/app/getting-started/partial-prerendering#static-rendering), calling `useSearchParams` will cause the Client Component tree up to the closest [`Suspense` boundary](/docs/app/api-reference/file-conventions/loading#examples) to be client-side rendered. This allows a part of the route to be statically rendered while the dynamic part that uses `useSearchParams` is client-side rendered. @@ -258,7 +258,7 @@ To access search params in [Pages](/docs/app/api-reference/file-conventions/page #### Layouts -Unlike Pages, [Layouts](/docs/app/api-reference/file-conventions/layout) (Server Components) **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering) which could lead to stale `searchParams` between navigations. View [detailed explanation](/docs/app/api-reference/file-conventions/layout#query-params). +Unlike Pages, [Layouts](/docs/app/api-reference/file-conventions/layout) (Server Components) **do not** receive the `searchParams` prop. This is because a shared layout is [not re-rendered during navigation](/docs/app/getting-started/linking-and-navigating#client-side-transitions) which could lead to stale `searchParams` between navigations. View [detailed explanation](/docs/app/api-reference/file-conventions/layout#query-params). Instead, use the Page [`searchParams`](/docs/app/api-reference/file-conventions/page) prop or the [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) hook in a Client Component, which is re-rendered on the client with the latest `searchParams`. diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/appDir.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/appDir.mdx index 86673c2e..8c6ce88d 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/appDir.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/appDir.mdx @@ -6,6 +6,6 @@ version: legacy > **Good to know**: This option is **no longer** needed as of Next.js 13.4. The App Router is now stable. -The App Router ([`app` directory](/docs/app/building-your-application/routing)) enables support for [layouts](/docs/app/api-reference/file-conventions/layout), [Server Components](/docs/app/getting-started/server-and-client-components), [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming), and [colocated data fetching](/docs/app/building-your-application/data-fetching). +The App Router ([`app` directory](/docs/app/building-your-application/routing)) enables support for [layouts](/docs/app/api-reference/file-conventions/layout), [Server Components](/docs/app/getting-started/server-and-client-components), [streaming](/docs/app/api-reference/file-conventions/loading), and [colocated data fetching](/docs/app/building-your-application/data-fetching). Using the `app` directory will automatically enable [React Strict Mode](https://react.dev/reference/react/StrictMode). Learn how to [incrementally adopt `app`](/docs/app/guides/migrating/app-router-migration#migrating-from-pages-to-app). diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/devIndicators.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/devIndicators.mdx index 8bdb44a1..8e394aca 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/devIndicators.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/devIndicators.mdx @@ -40,7 +40,7 @@ There are two reasons a route might opt out of static rendering: - The presence of [Dynamic APIs](/docs/app/getting-started/partial-prerendering#dynamic-rendering) which rely on runtime information. - An [uncached data request](/docs/app/getting-started/fetching-data), like a call to an ORM or database driver. -Check your route for any of these conditions, and if you are not able to statically render the route, then consider using [`loading.js`](/docs/app/api-reference/file-conventions/loading) or [``](https://react.dev/reference/react/Suspense) to leverage [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming#what-is-streaming). +Check your route for any of these conditions, and if you are not able to statically render the route, then consider using [`loading.js`](/docs/app/api-reference/file-conventions/loading) or [``](https://react.dev/reference/react/Suspense) to leverage [streaming](/docs/app/getting-started/linking-and-navigating#streaming). diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx index 2fca6a21..80560ca2 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx @@ -32,7 +32,7 @@ The `static` and `dynamic` properties correspond with the time period (in second > **Good to know:** > > - [Loading boundaries](/docs/app/api-reference/file-conventions/loading) are considered reusable for the `static` period defined in this configuration. -> - This doesn't affect [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), **meaning shared layouts won't automatically be refetched on every navigation, only the page segment that changes.** +> - This doesn't affect [partial rendering](/docs/app/getting-started/linking-and-navigating#client-side-transitions), **meaning shared layouts won't automatically be refetched on every navigation, only the page segment that changes.** > - This doesn't change [back/forward caching](/docs/app/deep-dive/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position. You can learn more about the Client Router Cache [here](/docs/app/deep-dive/caching#client-side-router-cache). diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/07-edge.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/07-edge.mdx index fa2530f2..36f8c33f 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/07-edge.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/07-edge.mdx @@ -14,7 +14,7 @@ Next.js has two server runtimes you can use in your application: - The Edge Runtime does not support all Node.js APIs. Some packages may not work as expected. - The Edge Runtime does not support Incremental Static Regeneration (ISR). -- Both runtimes can support [streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) depending on your deployment adapter. +- Both runtimes can support [streaming](/docs/app/api-reference/file-conventions/loading) depending on your deployment adapter. ## Reference diff --git a/apps/docs/content/en/docs/01-app/05-api-reference/08-turbopack.mdx b/apps/docs/content/en/docs/01-app/05-api-reference/08-turbopack.mdx index b260b716..5aafcd4c 100644 --- a/apps/docs/content/en/docs/01-app/05-api-reference/08-turbopack.mdx +++ b/apps/docs/content/en/docs/01-app/05-api-reference/08-turbopack.mdx @@ -99,6 +99,8 @@ Some features are not yet implemented or not planned: - Standalone `:local` and `:global` pseudo-classes (only the function variant `:global(...)` is supported). - The `@value` rule (superseded by CSS variables). - `:import` and `:export` ICSS rules. + - `composes` in `.module.css` composing a `.css` file. In webpack this would treat the `.css` file as a CSS Module, with Turbopack the `.css` file will always be global. This means that if you want to use `composes` in a CSS Module, you need to change the `.css` file to a `.module.css` file. + - `@import` in CSS Modules importing `.css` as a CSS Module. In webpack this would treat the `.css` file as a CSS Module, with Turbopack the `.css` file will always be global. This means that if you want to use `@import` in a CSS Module, you need to change the `.css` file to a `.module.css` file. - **`webpack()` configuration** in `next.config.js` Turbopack replaces webpack, so `webpack()` configs are not recognized. Use the [`turbopack` config](/docs/app/api-reference/config/next-config-js/turbopack) instead. - **AMP** diff --git a/apps/docs/content/en/docs/02-pages/03-building-your-application/02-rendering/05-client-side-rendering.mdx b/apps/docs/content/en/docs/02-pages/03-building-your-application/02-rendering/05-client-side-rendering.mdx index 447804a5..6a9a5726 100644 --- a/apps/docs/content/en/docs/02-pages/03-building-your-application/02-rendering/05-client-side-rendering.mdx +++ b/apps/docs/content/en/docs/02-pages/03-building-your-application/02-rendering/05-client-side-rendering.mdx @@ -7,7 +7,6 @@ related: - pages/building-your-application/rendering/server-side-rendering - pages/building-your-application/rendering/static-site-generation - pages/guides/incremental-static-regeneration - - app/building-your-application/routing/loading-ui-and-streaming --- In Client-Side Rendering (CSR) with React, the browser downloads a minimal HTML page and the JavaScript needed for the page. The JavaScript is then used to update the DOM and render the page. When the application is first loaded, the user may notice a slight delay before they can see the full page, this is because the page isn't fully rendered until all the JavaScript is downloaded, parsed, and executed. @@ -69,4 +68,4 @@ export function Page() { > **Good to know**: > -> Keep in mind that CSR can impact SEO. Some search engine crawlers might not execute JavaScript and therefore only see the initial empty or loading state of your application. It can also lead to performance issues for users with slower internet connections or devices, as they need to wait for all the JavaScript to load and run before they can see the full page. Next.js promotes a hybrid approach that allows you to use a combination of [server-side rendering](/docs/pages/building-your-application/rendering/server-side-rendering), [static site generation](/docs/pages/building-your-application/rendering/static-site-generation), and client-side rendering, **depending on the needs of each page** in your application. In the App Router, you can also use [Loading UI with Suspense](/docs/app/building-your-application/routing/loading-ui-and-streaming) to show a loading indicator while the page is being rendered. +> Keep in mind that CSR can impact SEO. Some search engine crawlers might not execute JavaScript and therefore only see the initial empty or loading state of your application. It can also lead to performance issues for users with slower internet connections or devices, as they need to wait for all the JavaScript to load and run before they can see the full page. Next.js promotes a hybrid approach that allows you to use a combination of [server-side rendering](/docs/pages/building-your-application/rendering/server-side-rendering), [static site generation](/docs/pages/building-your-application/rendering/static-site-generation), and client-side rendering, **depending on the needs of each page** in your application. In the App Router, you can also use [Loading UI with Suspense](/docs/app/api-reference/file-conventions/loading) to show a loading indicator while the page is being rendered. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/es/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/05-images.mdx index 6f60daa2..42799eee 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T20:02:45.834Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo optimizar imágenes nav_title: Imágenes description: Aprenda a optimizar imágenes en Next.js diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/es/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/06-fonts.mdx index 2cbaf6c8..ab31716b 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:27.959Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo usar fuentes nav_title: Fuentes description: Aprenda a utilizar fuentes en Next.js diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/07-css.mdx index 20ce88be..891e71c2 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T20:03:03.214Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo usar CSS en tu aplicación nav_title: CSS description: Conoce las diferentes formas de agregar CSS a tu aplicación, incluyendo Módulos CSS, CSS Global, Tailwind CSS y más. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/08-server-and-client-components.mdx index 3c1b1517..4f8f283f 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:04:55.321Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo usar Componentes de Servidor y Cliente nav_title: Componentes de Servidor y Cliente description: Aprende cómo puedes usar los Componentes de Servidor y Cliente de React para renderizar partes de tu aplicación en el servidor o en el cliente. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/es/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/es/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index 293b9f69..6593454c 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:43.857Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo almacenar en caché y revalidar datos nav_title: Almacenamiento en caché y revalidación description: Aprenda a almacenar en caché y revalidar datos en su aplicación. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/11-updating-data.mdx index 39f1dde3..32bcfb3a 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T16:38:51.012Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo actualizar datos nav_title: Actualización de datos description: Aprende a actualizar datos en tu aplicación Next.js. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/12-error-handling.mdx index c7bdf358..53cabcf6 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:45.399Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo manejar errores nav_title: Manejo de errores description: Aprenda a mostrar errores esperados y manejar excepciones no capturadas. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/13-partial-prerendering.mdx index ba9bc702..89a62deb 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:41.448Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo usar el Renderizado Parcial (Partial Prerendering) nav_title: Renderizado Parcial description: Aprende a combinar los beneficios del renderizado estático y dinámico con el Renderizado Parcial (Partial Prerendering). diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/es/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index 542db7a8..710648d0 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:43.630Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo agregar metadatos y crear imágenes OG nav_title: Metadatos e imágenes OG description: Aprende cómo agregar metadatos a tus páginas y crear imágenes OG dinámicas. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/15-deploying.mdx similarity index 97% rename from apps/docs/content/es/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/15-deploying.mdx index 6f877043..1fcb2113 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T16:37:42.475Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo desplegar tu aplicación Next.js nav_title: Despliegue description: Aprende cómo desplegar tu aplicación Next.js. diff --git a/apps/docs/content/es/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/es/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 95% rename from apps/docs/content/es/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/es/docs/01-app/01-getting-started/16-upgrading.mdx index f8ad4a94..37c3ed01 100644 --- a/apps/docs/content/es/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/es/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:00:58.584Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Cómo actualizar tu aplicación Next.js nav_title: Actualización description: Aprende cómo actualizar tu aplicación Next.js a la versión más reciente. diff --git a/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index 087d7ee4..00000000 --- a/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:12:15.841Z -title: Enlaces y Navegación -description: Aprenda cómo funciona la navegación en Next.js y cómo usar el componente `Link` y el hook `useRouter`. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -Existen cuatro formas de navegar entre rutas en Next.js: - -- Usando el [componente ``](#link-component) -- Usando el [hook `useRouter`](#userouter-hook) ([Componentes del Cliente](/docs/app/getting-started/server-and-client-components)) -- Usando la [función `redirect`](#redirect-function) ([Componentes del Servidor](/docs/app/getting-started/server-and-client-components)) -- Usando la [API History nativa](#using-the-native-history-api) - -Esta página explicará cómo usar cada una de estas opciones y profundizará en el funcionamiento de la navegación. - -## Componente `` - -`` es un componente integrado que extiende la etiqueta HTML `
` para proporcionar [precarga (prefetching)](#2-prefetching) y navegación del lado del cliente entre rutas. Es la forma principal y recomendada para navegar entre rutas en Next.js. - -Puede usarlo importándolo desde `next/link` y pasando una propiedad `href` al componente: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -Hay otras propiedades opcionales que puede pasar a ``. Consulte la [referencia de API](/docs/app/api-reference/components/link) para más información. - -## Hook `useRouter()` - -El hook `useRouter` permite cambiar rutas programáticamente desde [Componentes del Cliente](/docs/app/getting-started/server-and-client-components). - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -Para una lista completa de métodos de `useRouter`, consulte la [referencia de API](/docs/app/api-reference/functions/use-router). - -> **Recomendación:** Use el componente `` para navegar entre rutas a menos que tenga un requisito específico para usar `useRouter`. - -## Función `redirect` - -Para [Componentes del Servidor](/docs/app/getting-started/server-and-client-components), use la función `redirect` en su lugar. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **Importante**: -> -> - `redirect` devuelve por defecto un código de estado 307 (Redirección Temporal). Cuando se usa en una Server Action, devuelve un 303 (Ver Otro), que se usa comúnmente para redirigir a una página de éxito como resultado de una solicitud POST. -> - `redirect` internamente lanza un error, por lo que debe llamarse fuera de bloques `try/catch`. -> - `redirect` puede llamarse en Componentes del Cliente durante el proceso de renderizado pero no en manejadores de eventos. Puede usar el [hook `useRouter`](#userouter-hook) en su lugar. -> - `redirect` también acepta URLs absolutas y puede usarse para redirigir a enlaces externos. -> - Si desea redirigir antes del proceso de renderizado, use [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) o [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -Consulte la [referencia de API de `redirect`](/docs/app/api-reference/functions/redirect) para más información. - -## Uso de la API History nativa - -Next.js permite usar los métodos nativos [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) y [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) para actualizar el historial del navegador sin recargar la página. - -Las llamadas a `pushState` y `replaceState` se integran con el Router de Next.js, permitiéndole sincronizarse con [`usePathname`](/docs/app/api-reference/functions/use-pathname) y [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). - -### `window.history.pushState` - -Úselo para añadir una nueva entrada al historial del navegador. El usuario puede navegar de vuelta al estado anterior. Por ejemplo, para ordenar una lista de productos: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -Úselo para reemplazar la entrada actual en el historial del navegador. El usuario no podrá navegar de vuelta al estado anterior. Por ejemplo, para cambiar el idioma de la aplicación: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // ej. '/en/about' o '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // ej. '/en/about' o '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## Cómo Funcionan el Enrutamiento y la Navegación - -El App Router utiliza un enfoque híbrido para el enrutamiento y la navegación. En el servidor, su código de aplicación se divide automáticamente [por segmentos de ruta](#1-code-splitting). Y en el cliente, Next.js [precarga](#2-prefetching) y [almacena en caché](#3-caching) los segmentos de ruta. Esto significa que cuando un usuario navega a una nueva ruta, el navegador no recarga la página, y solo los segmentos de ruta que cambian se vuelven a renderizar, mejorando la experiencia de navegación y el rendimiento. - -### 1. División de Código (Code Splitting) - -La división de código permite dividir el código de su aplicación en paquetes más pequeños para que el navegador los descargue y ejecute. Esto reduce la cantidad de datos transferidos y el tiempo de ejecución por cada solicitud, mejorando el rendimiento. - -Los [Componentes del Servidor](/docs/app/getting-started/server-and-client-components) permiten que su código de aplicación se divida automáticamente por segmentos de ruta. Esto significa que solo se carga el código necesario para la ruta actual durante la navegación. - -### 2. Precarga (Prefetching) - -La precarga es una forma de cargar una ruta en segundo plano antes de que el usuario la visite. - -Hay dos formas en que las rutas se precargan en Next.js: - -- **Componente ``**: Las rutas se precargan automáticamente cuando son visibles en el viewport del usuario. La precarga ocurre cuando la página se carga por primera vez o cuando entra en vista al desplazarse. -- **`router.prefetch()`**: El hook `useRouter` puede usarse para precargar rutas programáticamente. - -El comportamiento predeterminado de precarga de `` (es decir, cuando la propiedad `prefetch` no se especifica o se establece en `null`) varía según el uso de [`loading.js`](/docs/app/api-reference/file-conventions/loading). Solo el diseño compartido, hacia abajo en el "árbol" de componentes renderizados hasta el primer archivo `loading.js`, se precarga y almacena en caché durante `30s`. Esto reduce el costo de obtener una ruta dinámica completa y significa que puede mostrar un [estado de carga instantánea](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) para una mejor retroalimentación visual a los usuarios. - -Puede desactivar la precarga estableciendo la propiedad `prefetch` en `false`. Alternativamente, puede precargar los datos completos de la página más allá de los límites de carga estableciendo la propiedad `prefetch` en `true`. - -Consulte la [referencia de API de ``](/docs/app/api-reference/components/link) para más información. - -> **Importante**: -> -> - La precarga no está activada en desarrollo, solo en producción. - -### 3. Almacenamiento en Caché (Caching) - -Next.js tiene una **caché del lado del cliente en memoria** llamada [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). A medida que los usuarios navegan por la aplicación, la carga útil del Componente del Servidor React de los segmentos de ruta [precargados](#2-prefetching) y las rutas visitadas se almacenan en la caché. - -Esto significa que durante la navegación, la caché se reutiliza tanto como sea posible, en lugar de hacer una nueva solicitud al servidor, mejorando el rendimiento al reducir el número de solicitudes y datos transferidos. - -Aprenda más sobre cómo funciona el [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) y cómo configurarlo. - -### 4. Renderizado Parcial (Partial Rendering) - -El renderizado parcial significa que solo los segmentos de ruta que cambian durante la navegación se vuelven a renderizar en el cliente, y cualquier segmento compartido se preserva. - -Por ejemplo, al navegar entre dos rutas hermanas, `/dashboard/settings` y `/dashboard/analytics`, la página `settings` se desmontará, la página `analytics` se montará con estado fresco, y el diseño compartido `dashboard` se preservará. Este comportamiento también está presente entre dos rutas en el mismo segmento dinámico, por ejemplo con `/blog/[slug]/page` y navegando de `/blog/first` a `/blog/second`. - -Cómo funciona el renderizado parcial - -Sin el renderizado parcial, cada navegación causaría que toda la página se vuelva a renderizar en el cliente. Renderizar solo el segmento que cambia reduce la cantidad de datos transferidos y el tiempo de ejecución, mejorando el rendimiento. - -### 5. Navegación Suave (Soft Navigation) - -Los navegadores realizan una "navegación dura" al moverse entre páginas. El App Router de Next.js habilita la "navegación suave" entre páginas, asegurando que solo los segmentos de ruta que han cambiado se vuelvan a renderizar (renderizado parcial). Esto permite que el estado React del cliente se preserve durante la navegación. - -### 6. Navegación Atrás y Adelante - -Por defecto, Next.js mantendrá la posición de desplazamiento para navegaciones hacia atrás y adelante, y reutilizará segmentos de ruta en el [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). - -### 7. Enrutamiento entre `pages/` y `app/` - -Al migrar incrementalmente de `pages/` a `app/`, el router de Next.js manejará automáticamente la navegación dura entre ambos. Para detectar transiciones de `pages/` a `app/`, hay un filtro de router del cliente que utiliza comprobación probabilística de rutas de app, lo que ocasionalmente puede resultar en falsos positivos. Por defecto, tales ocurrencias deberían ser muy raras, ya que configuramos la probabilidad de falso positivo en un 0.01%. Esta probabilidad puede personalizarse mediante la opción `experimental.clientRouterFilterAllowedRate` en `next.config.js`. Es importante notar que reducir la tasa de falsos positivos aumentará el tamaño del filtro generado en el paquete del cliente. - -Alternativamente, si prefiere desactivar completamente este manejo y administrar manualmente el enrutamiento entre `pages/` y `app/`, puede establecer `experimental.clientRouterFilter` en false en `next.config.js`. Cuando esta característica está desactivada, cualquier ruta dinámica en pages que coincida con rutas de app no se navegará correctamente por defecto. \ No newline at end of file diff --git a/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 5e0344c7..00000000 --- a/apps/docs/content/es/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:11:29.567Z -title: Interfaz de carga y transmisión en streaming -description: Basado en Suspense, la interfaz de carga permite crear un respaldo para segmentos de ruta específicos y transmitir contenido automáticamente a medida que esté listo. ---- - -El archivo especial `loading.js` te ayuda a crear una Interfaz de Carga significativa con [React Suspense](https://react.dev/reference/react/Suspense). Con esta convención, puedes mostrar un [estado de carga instantáneo](#estados-de-carga-instantáneos) desde el servidor mientras se carga el contenido de un segmento de ruta. El nuevo contenido se intercambia automáticamente una vez que se completa el renderizado. - -Interfaz de carga - -## Estados de carga instantáneos - -Un estado de carga instantáneo es una interfaz de respaldo que se muestra inmediatamente al navegar. Puedes pre-renderizar indicadores de carga como esqueletos (skeletons) y spinners, o partes pequeñas pero significativas de pantallas futuras como una foto de portada, título, etc. Esto ayuda a los usuarios a entender que la aplicación está respondiendo y proporciona una mejor experiencia de usuario. - -Crea un estado de carga añadiendo un archivo `loading.js` dentro de una carpeta. - -Archivo especial loading.js - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // Puedes añadir cualquier interfaz dentro de Loading, incluyendo un Skeleton. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // Puedes añadir cualquier interfaz dentro de Loading, incluyendo un Skeleton. - return -} -``` - -En la misma carpeta, `loading.js` se anidará dentro de `layout.js`. Envolverá automáticamente el archivo `page.js` y cualquier hijo en un límite ``. - -Resumen de loading.js - -> **Nota importante**: -> -> - La navegación es inmediata, incluso con [enrutamiento centrado en el servidor](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - La navegación es interrumpible, lo que significa que cambiar de ruta no necesita esperar a que el contenido de la ruta actual se cargue completamente antes de navegar a otra ruta. -> - Los diseños compartidos (layouts) permanecen interactivos mientras se cargan nuevos segmentos de ruta. - -> **Recomendación:** Usa la convención `loading.js` para segmentos de ruta (layouts y páginas) ya que Next.js optimiza esta funcionalidad. - -## Transmisión en streaming con Suspense - -Además de `loading.js`, también puedes crear manualmente límites de Suspense para tus propios componentes de interfaz. El App Router admite transmisión en streaming con [Suspense](https://react.dev/reference/react/Suspense). - -> **Nota importante**: -> -> - [Algunos navegadores](https://bugs.webkit.org/show_bug.cgi?id=252413) almacenan en búfer una respuesta en streaming. Puede que no veas la respuesta transmitida hasta que supere los 1024 bytes. Esto generalmente solo afecta a aplicaciones de ejemplo "hola mundo", no a aplicaciones reales. - -### ¿Qué es la transmisión en streaming? - -Para entender cómo funciona el streaming en React y Next.js, es útil comprender el **Renderizado del lado del servidor (SSR)** y sus limitaciones. - -Con SSR, hay una serie de pasos que deben completarse antes de que un usuario pueda ver e interactuar con una página: - -1. Primero, todos los datos para una página se obtienen en el servidor. -2. Luego, el servidor renderiza el HTML para la página. -3. El HTML, CSS y JavaScript de la página se envían al cliente. -4. Se muestra una interfaz no interactiva usando el HTML generado y el CSS. -5. Finalmente, React [hidrata](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) la interfaz para hacerla interactiva. - -Gráfico mostrando renderizado en servidor sin streaming - -Estos pasos son secuenciales y bloqueantes, lo que significa que el servidor solo puede renderizar el HTML de una página una vez que se han obtenido todos los datos. Y, en el cliente, React solo puede hidratar la interfaz una vez que se ha descargado el código de todos los componentes de la página. - -SSR con React y Next.js ayuda a mejorar el rendimiento de carga percibido al mostrar una página no interactiva al usuario lo antes posible. - -Renderizado en servidor sin streaming - -Sin embargo, aún puede ser lento ya que toda la obtención de datos en el servidor debe completarse antes de que la página pueda mostrarse al usuario. - -**Streaming** te permite dividir el HTML de la página en fragmentos más pequeños y enviar esos fragmentos progresivamente desde el servidor al cliente. - -Cómo funciona el renderizado en servidor con streaming - -Esto permite que partes de la página se muestren antes, sin esperar a que todos los datos se carguen antes de que se pueda renderizar cualquier interfaz. - -El streaming funciona bien con el modelo de componentes de React porque cada componente puede considerarse un fragmento. Los componentes con mayor prioridad (ej. información del producto) o que no dependen de datos pueden enviarse primero (ej. layout), y React puede comenzar la hidratación antes. Los componentes con menor prioridad (ej. reseñas, productos relacionados) pueden enviarse en la misma solicitud del servidor después de obtener sus datos. - -Gráfico mostrando renderizado en servidor con streaming - -El streaming es particularmente beneficioso cuando deseas evitar que solicitudes de datos largas bloqueen el renderizado de la página, ya que puede reducir el [Time To First Byte (TTFB)](https://web.dev/ttfb/) y [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/). También ayuda a mejorar el [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), especialmente en dispositivos más lentos. - -### Ejemplo - -`` funciona envolviendo un componente que realiza una acción asíncrona (ej. obtener datos), mostrando una interfaz de respaldo (ej. skeleton, spinner) mientras ocurre, y luego intercambiando tu componente una vez que se completa la acción. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Cargando feed...

}> - -
- Cargando clima...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Cargando feed...

}> - -
- Cargando clima...

}> - -
-
- ) -} -``` - -Al usar Suspense, obtienes los beneficios de: - -1. **Renderizado en servidor con streaming** - Renderizado progresivo de HTML desde el servidor al cliente. -2. **Hidratación selectiva** - React prioriza qué componentes hacer interactivos primero basándose en la interacción del usuario. - -Para más ejemplos y casos de uso de Suspense, consulta la [documentación de React](https://react.dev/reference/react/Suspense). - -### SEO - -- Next.js esperará a que se complete la obtención de datos dentro de [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) antes de transmitir la interfaz al cliente. Esto garantiza que la primera parte de una respuesta transmitida incluya las etiquetas ``. -- Dado que el streaming se renderiza en el servidor, no afecta al SEO. Puedes usar la herramienta [Rich Results Test](https://search.google.com/test/rich-results) de Google para ver cómo aparece tu página para los rastreadores web de Google y ver el HTML serializado ([fuente](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### Códigos de estado - -Al transmitir en streaming, se devolverá un código de estado `200` para indicar que la solicitud fue exitosa. - -El servidor aún puede comunicar errores o problemas al cliente dentro del contenido transmitido, por ejemplo, al usar [`redirect`](/docs/app/api-reference/functions/redirect) o [`notFound`](/docs/app/api-reference/functions/not-found). Dado que los encabezados de respuesta ya se han enviado al cliente, el código de estado de la respuesta no se puede actualizar. Esto no afecta al SEO. - -## Compatibilidad con plataformas - -| Opción de despliegue | Compatible | -| ------------------------------------------------------------------- | ----------------- | -| [Servidor Node.js](/docs/app/getting-started/deploying#nodejs-server) | Sí | -| [Contenedor Docker](/docs/app/getting-started/deploying#docker) | Sí | -| [Exportación estática](/docs/app/getting-started/deploying#static-export) | No | -| [Adaptadores](/docs/app/getting-started/deploying#adapters) | Depende de la plataforma | - -Aprende cómo [configurar streaming](/docs/app/guides/self-hosting#streaming-and-suspense) al autoalojar Next.js. \ No newline at end of file diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/fr/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/05-images.mdx index 85936c1a..b8792f56 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T20:02:08.743Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment optimiser les images nav_title: Images description: Apprenez comment optimiser les images dans Next.js diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/fr/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/06-fonts.mdx index 98639e5e..cbf7d17a 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-06T16:46:29.469Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment utiliser les polices nav_title: Polices description: Apprenez à utiliser les polices dans Next.js diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/07-css.mdx index 13d9b3be..30d7529a 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T20:02:19.654Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment utiliser CSS dans votre application nav_title: CSS description: Découvrez les différentes méthodes pour ajouter CSS à votre application, y compris les modules CSS, le CSS global, Tailwind CSS et plus encore. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/08-server-and-client-components.mdx index d0a98009..6e554b25 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:03:58.409Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment utiliser les composants Serveur et Client nav_title: Composants Serveur et Client description: Apprenez à utiliser les composants Serveur et Client de React pour afficher certaines parties de votre application côté serveur ou côté client. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/fr/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/fr/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index b9f1bea5..55bab822 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:56.984Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment mettre en cache et revalider les données nav_title: Cache et revalidation description: Apprenez à mettre en cache et revalider les données dans votre application. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/11-updating-data.mdx index 9aa48286..446a148f 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T16:52:39.859Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment mettre à jour des données nav_title: Mise à jour des données description: Apprenez à mettre à jour des données dans votre application Next.js. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/12-error-handling.mdx index 429473ef..b2f8c0e2 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:53.713Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Gestion des erreurs nav_title: Gestion des erreurs description: Apprenez à afficher les erreurs attendues et à gérer les exceptions non capturées. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/13-partial-prerendering.mdx index c607f306..cd67aedd 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:56.561Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment utiliser le Prérendu Partiel (Partial Prerendering) nav_title: Prérendu Partiel description: Découvrez comment combiner les avantages du rendu statique et dynamique avec le Prérendu Partiel (Partial Prerendering). diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/fr/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index 7b3aa034..d036691c 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:02:14.557Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment ajouter des métadonnées et créer des images OG nav_title: Métadonnées et images OG description: Apprenez à ajouter des métadonnées à vos pages et à créer des images OG dynamiques. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/15-deploying.mdx similarity index 98% rename from apps/docs/content/fr/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/15-deploying.mdx index ff0d2606..d2c7211b 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T16:51:52.474Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment déployer votre application Next.js nav_title: Déploiement description: Apprenez à déployer votre application Next.js. diff --git a/apps/docs/content/fr/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/fr/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 95% rename from apps/docs/content/fr/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/fr/docs/01-app/01-getting-started/16-upgrading.mdx index 710e2872..43f826db 100644 --- a/apps/docs/content/fr/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/fr/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:00:14.344Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Comment mettre à jour votre application Next.js nav_title: Mise à jour description: Apprenez comment mettre à jour votre application Next.js vers la dernière version. diff --git a/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index 6fe9ef29..00000000 --- a/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:11:07.902Z -title: Liaison et Navigation -description: Découvrez comment fonctionne la navigation dans Next.js, et comment utiliser le composant Link et le hook `useRouter`. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -Il existe quatre façons de naviguer entre les routes dans Next.js : - -- En utilisant le [composant ``](#link-component) -- En utilisant le [hook `useRouter`](#userouter-hook) ([Composants Client](/docs/app/getting-started/server-and-client-components)) -- En utilisant la [fonction `redirect`](#redirect-function) ([Composants Serveur](/docs/app/getting-started/server-and-client-components)) -- En utilisant l'[API History native](#using-the-native-history-api) - -Cette page expliquera comment utiliser chacune de ces options, et approfondira le fonctionnement de la navigation. - -## Composant `` - -`` est un composant intégré qui étend la balise HTML `
` pour fournir un [préchargement](#2-prefetching) et une navigation côté client entre les routes. C'est la méthode principale et recommandée pour naviguer entre les routes dans Next.js. - -Vous pouvez l'utiliser en l'important depuis `next/link`, et en passant une prop `href` au composant : - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -Il existe d'autres props optionnelles que vous pouvez passer à ``. Consultez la [référence API](/docs/app/api-reference/components/link) pour en savoir plus. - -## Hook `useRouter()` - -Le hook `useRouter` vous permet de changer de route programmatiquement depuis des [Composants Client](/docs/app/getting-started/server-and-client-components). - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -Pour une liste complète des méthodes de `useRouter`, consultez la [référence API](/docs/app/api-reference/functions/use-router). - -> **Recommandation :** Utilisez le composant `` pour naviguer entre les routes, sauf si vous avez une exigence spécifique nécessitant l'utilisation de `useRouter`. - -## Fonction `redirect` - -Pour les [Composants Serveur](/docs/app/getting-started/server-and-client-components), utilisez la fonction `redirect` à la place. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **Bon à savoir :** -> -> - `redirect` retourne par défaut un code d'état 307 (Redirection Temporaire). Lorsqu'il est utilisé dans une Action Serveur, il retourne un 303 (Voir Autre), couramment utilisé pour rediriger vers une page de succès après une requête POST. -> - `redirect` lance une erreur en interne, donc il doit être appelé en dehors des blocs `try/catch`. -> - `redirect` peut être appelé dans les Composants Client pendant le processus de rendu, mais pas dans les gestionnaires d'événements. Vous pouvez utiliser le [hook `useRouter`](#userouter-hook) à la place. -> - `redirect` accepte également les URLs absolues et peut être utilisé pour rediriger vers des liens externes. -> - Si vous souhaitez rediriger avant le processus de rendu, utilisez [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) ou [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -Consultez la [référence API de `redirect`](/docs/app/api-reference/functions/redirect) pour plus d'informations. - -## Utilisation de l'API History native - -Next.js vous permet d'utiliser les méthodes natives [`window.history.pushState`](https://developer.mozilla.org/fr/docs/Web/API/History/pushState) et [`window.history.replaceState`](https://developer.mozilla.org/fr/docs/Web/API/History/replaceState) pour mettre à jour la pile d'historique du navigateur sans recharger la page. - -Les appels `pushState` et `replaceState` s'intègrent au routeur Next.js, vous permettant de vous synchroniser avec [`usePathname`](/docs/app/api-reference/functions/use-pathname) et [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). - -### `window.history.pushState` - -Utilisez-le pour ajouter une nouvelle entrée à la pile d'historique du navigateur. L'utilisateur peut naviguer vers l'état précédent. Par exemple, pour trier une liste de produits : - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -Utilisez-le pour remplacer l'entrée actuelle dans la pile d'historique du navigateur. L'utilisateur ne peut pas naviguer vers l'état précédent. Par exemple, pour changer la locale de l'application : - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // ex. '/en/about' ou '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // ex. '/en/about' ou '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## Fonctionnement du Routage et de la Navigation - -Le routeur App utilise une approche hybride pour le routage et la navigation. Sur le serveur, votre code d'application est automatiquement [découpé en morceaux](#1-code-splitting) par segments de route. Et sur le client, Next.js [précharge](#2-prefetching) et [met en cache](#3-caching) les segments de route. Cela signifie que lorsqu'un utilisateur navigue vers une nouvelle route, le navigateur ne recharge pas la page, et seuls les segments de route qui changent sont re-rendus - améliorant ainsi l'expérience de navigation et les performances. - -### 1. Découpage du Code (Code Splitting) - -Le découpage du code vous permet de diviser votre code d'application en paquets plus petits à télécharger et exécuter par le navigateur. Cela réduit la quantité de données transférées et le temps d'exécution pour chaque requête, améliorant ainsi les performances. - -Les [Composants Serveur](/docs/app/getting-started/server-and-client-components) permettent à votre code d'application d'être automatiquement découpé par segments de route. Cela signifie que seul le code nécessaire pour la route actuelle est chargé lors de la navigation. - -### 2. Préchargement (Prefetching) - -Le préchargement est un moyen de charger une route en arrière-plan avant que l'utilisateur ne la visite. - -Il existe deux façons de précharger les routes dans Next.js : - -- **Composant ``** : Les routes sont automatiquement préchargées lorsqu'elles deviennent visibles dans le viewport de l'utilisateur. Le préchargement se produit lors du premier chargement de la page ou lorsqu'elle apparaît à l'écran par défilement. -- **`router.prefetch()`** : Le hook `useRouter` peut être utilisé pour précharger des routes programmatiquement. - -Le comportement de préchargement par défaut de `` (c'est-à-dire lorsque la prop `prefetch` n'est pas spécifiée ou définie à `null`) diffère selon votre utilisation de [`loading.js`](/docs/app/api-reference/file-conventions/loading). Seule la mise en page partagée, en descendant l'"arbre" des composants rendus jusqu'au premier fichier `loading.js`, est préchargée et mise en cache pour `30s`. Cela réduit le coût de récupération d'une route dynamique entière, et signifie que vous pouvez afficher un [état de chargement instantané](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) pour un meilleur retour visuel aux utilisateurs. - -Vous pouvez désactiver le préchargement en définissant la prop `prefetch` à `false`. Alternativement, vous pouvez précharger les données complètes de la page au-delà des limites de chargement en définissant la prop `prefetch` à `true`. - -Consultez la [référence API de ``](/docs/app/api-reference/components/link) pour plus d'informations. - -> **Bon à savoir :** -> -> - Le préchargement n'est pas activé en développement, seulement en production. - -### 3. Mise en Cache (Caching) - -Next.js a un **cache côté client en mémoire** appelé [Cache du Routeur](/docs/app/deep-dive/caching#client-side-router-cache). Lorsque les utilisateurs naviguent dans l'application, la charge utile des Composants Serveur React des segments de route [préchargés](#2-prefetching) et des routes visitées est stockée dans le cache. - -Cela signifie que lors de la navigation, le cache est réutilisé autant que possible, au lieu de faire une nouvelle requête au serveur - améliorant les performances en réduisant le nombre de requêtes et de données transférées. - -Apprenez-en plus sur le fonctionnement du [Cache du Routeur](/docs/app/deep-dive/caching#client-side-router-cache) et comment le configurer. - -### 4. Rendu Partiel (Partial Rendering) - -Le rendu partiel signifie que seuls les segments de route qui changent lors de la navigation sont re-rendus côté client, et tous les segments partagés sont préservés. - -Par exemple, lors de la navigation entre deux routes sœurs, `/dashboard/settings` et `/dashboard/analytics`, la page `settings` sera démontée, la page `analytics` sera montée avec un nouvel état, et la mise en page partagée `dashboard` sera préservée. Ce comportement est également présent entre deux routes sur le même segment dynamique, par exemple avec `/blog/[slug]/page` et la navigation de `/blog/first` vers `/blog/second`. - -Fonctionnement du rendu partiel - -Sans rendu partiel, chaque navigation entraînerait un re-rendu complet de la page côté client. Le rendu uniquement du segment qui change réduit la quantité de données transférées et le temps d'exécution, améliorant ainsi les performances. - -### 5. Navigation Douce (Soft Navigation) - -Les navigateurs effectuent une "navigation dure" lors de la navigation entre les pages. Le routeur App de Next.js permet une "navigation douce" entre les pages, garantissant que seuls les segments de route qui ont changé sont re-rendus (rendu partiel). Cela permet de préserver l'état React côté client pendant la navigation. - -### 6. Navigation Arrière et Avant - -Par défaut, Next.js maintiendra la position de défilement pour les navigations arrière et avant, et réutilisera les segments de route dans le [Cache du Routeur](/docs/app/deep-dive/caching#client-side-router-cache). - -### 7. Routage entre `pages/` et `app/` - -Lors d'une migration progressive de `pages/` vers `app/`, le routeur Next.js gérera automatiquement la navigation dure entre les deux. Pour détecter les transitions de `pages/` vers `app/`, il y a un filtre de routeur côté client qui utilise une vérification probabiliste des routes d'application, ce qui peut occasionnellement entraîner des faux positifs. Par défaut, ces occurrences devraient être très rares, car nous configurons la probabilité de faux positifs à 0,01%. Cette probabilité peut être personnalisée via l'option `experimental.clientRouterFilterAllowedRate` dans `next.config.js`. Il est important de noter que réduire le taux de faux positifs augmentera la taille du filtre généré dans le bundle client. - -Alternativement, si vous préférez désactiver complètement cette gestion et gérer manuellement le routage entre `pages/` et `app/`, vous pouvez définir `experimental.clientRouterFilter` à false dans `next.config.js`. Lorsque cette fonctionnalité est désactivée, les routes dynamiques dans pages qui chevauchent des routes d'application ne seront pas correctement naviguées par défaut. \ No newline at end of file diff --git a/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 01c63fb5..00000000 --- a/apps/docs/content/fr/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:10:24.769Z -title: Interface de chargement et streaming -description: Basée sur Suspense, l'interface de chargement permet de créer un contenu de repli pour des segments de route spécifiques et de diffuser automatiquement le contenu dès qu'il est prêt. ---- - -Le fichier spécial `loading.js` vous aide à créer une interface de chargement significative avec [React Suspense](https://react.dev/reference/react/Suspense). Grâce à cette convention, vous pouvez afficher un [état de chargement instantané](#instant-loading-states) depuis le serveur pendant le chargement du contenu d'un segment de route. Le nouveau contenu est automatiquement remplacé une fois le rendu terminé. - -Interface de chargement - -## États de chargement instantanés - -Un état de chargement instantané est une interface de repli qui s'affiche immédiatement lors de la navigation. Vous pouvez pré-rendre des indicateurs de chargement comme des squelettes ou des spinners, ou une petite partie significative des écrans futurs comme une photo de couverture, un titre, etc. Cela aide les utilisateurs à comprendre que l'application répond et améliore l'expérience utilisateur. - -Créez un état de chargement en ajoutant un fichier `loading.js` dans un dossier. - -Fichier spécial loading.js - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // Vous pouvez ajouter n'importe quelle interface dans Loading, y compris un Skeleton. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // Vous pouvez ajouter n'importe quelle interface dans Loading, y compris un Skeleton. - return -} -``` - -Dans le même dossier, `loading.js` sera imbriqué dans `layout.js`. Il englobera automatiquement le fichier `page.js` et tous ses enfants dans une limite ``. - -Vue d'ensemble de loading.js - -> **Bon à savoir** : -> -> - La navigation est instantanée, même avec [le routage centré sur le serveur](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - La navigation est interruptible, ce qui signifie que changer de route ne nécessite pas d'attendre que le contenu de la route en cours soit entièrement chargé. -> - Les layouts partagés restent interactifs pendant le chargement des nouveaux segments de route. - -> **Recommandation** : Utilisez la convention `loading.js` pour les segments de route (layouts et pages) car Next.js optimise cette fonctionnalité. - -## Streaming avec Suspense - -En plus de `loading.js`, vous pouvez aussi créer manuellement des limites Suspense pour vos propres composants d'interface. Le routeur App prend en charge le streaming avec [Suspense](https://react.dev/reference/react/Suspense). - -> **Bon à savoir** : -> -> - [Certains navigateurs](https://bugs.webkit.org/show_bug.cgi?id=252413) mettent en mémoire tampon une réponse en streaming. Vous ne verrez peut-être pas la réponse streamée tant que celle-ci ne dépasse pas 1024 octets. Cela affecte généralement seulement les applications de démonstration, pas les applications réelles. - -### Qu'est-ce que le streaming ? - -Pour comprendre comment le streaming fonctionne dans React et Next.js, il est utile de connaître le **rendu côté serveur (SSR)** et ses limites. - -Avec le SSR, une série d'étapes doivent être accomplies avant qu'un utilisateur puisse voir et interagir avec une page : - -1. D'abord, toutes les données pour une page donnée sont récupérées sur le serveur. -2. Le serveur rend ensuite le HTML pour la page. -3. Le HTML, CSS et JavaScript pour la page sont envoyés au client. -4. Une interface utilisateur non interactive est affichée en utilisant le HTML généré et le CSS. -5. Enfin, React [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) l'interface utilisateur pour la rendre interactive. - -Diagramme montrant le rendu serveur sans streaming - -Ces étapes sont séquentielles et bloquantes, ce qui signifie que le serveur ne peut rendre le HTML d'une page qu'une fois toutes les données récupérées. Et, côté client, React ne peut hydrater l'interface qu'une fois le code de tous les composants de la page téléchargé. - -Le SSR avec React et Next.js aide à améliorer les performances perçues de chargement en affichant une page non interactive à l'utilisateur le plus tôt possible. - -Rendu serveur sans streaming - -Cependant, cela peut encore être lent car toutes les requêtes de données côté serveur doivent être terminées avant que la page puisse être montrée à l'utilisateur. - -Le **streaming** vous permet de découper le HTML de la page en morceaux plus petits et d'envoyer progressivement ces morceaux du serveur au client. - -Fonctionnement du rendu serveur avec streaming - -Cela permet d'afficher des parties de la page plus tôt, sans attendre que toutes les données soient chargées avant qu'une interface ne soit rendue. - -Le streaming fonctionne bien avec le modèle de composants de React car chaque composant peut être considéré comme un morceau. Les composants ayant une priorité plus élevée (par exemple les informations sur un produit) ou ne dépendant pas de données peuvent être envoyés en premier (par exemple le layout), et React peut commencer l'hydratation plus tôt. Les composants ayant une priorité plus faible (par exemple les avis, produits similaires) peuvent être envoyés dans la même requête serveur après que leurs données ont été récupérées. - -Diagramme montrant le rendu serveur avec streaming - -Le streaming est particulièrement bénéfique lorsque vous voulez éviter que des requêtes de données longues bloquent le rendu de la page, car il peut réduire le [Time To First Byte (TTFB)](https://web.dev/ttfb/) et le [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/). Il aide aussi à améliorer le [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), surtout sur les appareils lents. - -### Exemple - -`` fonctionne en englobant un composant qui effectue une action asynchrone (par exemple récupérer des données), en affichant une interface de repli (par exemple un squelette, un spinner) pendant l'action, puis en remplaçant par votre composant une fois l'action terminée. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Chargement du flux...

}> - -
- Chargement de la météo...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Chargement du flux...

}> - -
- Chargement de la météo...

}> - -
-
- ) -} -``` - -En utilisant Suspense, vous bénéficiez de : - -1. **Rendu serveur en streaming** - Rendu progressif du HTML du serveur vers le client. -2. **Hydratation sélective** - React priorise quels composants rendre interactifs en premier selon l'interaction utilisateur. - -Pour plus d'exemples et de cas d'usage de Suspense, consultez la [documentation React](https://react.dev/reference/react/Suspense). - -### SEO - -- Next.js attendra que la récupération de données dans [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) soit terminée avant de streamer l'interface vers le client. Cela garantit que la première partie de la réponse streamée inclut les balises ``. -- Comme le streaming est rendu côté serveur, il n'affecte pas le SEO. Vous pouvez utiliser l'outil [Rich Results Test](https://search.google.com/test/rich-results) de Google pour voir comment votre page apparaît aux robots d'indexation et voir le HTML sérialisé ([source](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### Codes de statut - -Lors du streaming, un code de statut `200` sera retourné pour indiquer que la requête a réussi. - -Le serveur peut toujours communiquer des erreurs ou problèmes au client dans le contenu streamé lui-même, par exemple en utilisant [`redirect`](/docs/app/api-reference/functions/redirect) ou [`notFound`](/docs/app/api-reference/functions/not-found). Comme les en-têtes de réponse ont déjà été envoyés au client, le code de statut de la réponse ne peut pas être mis à jour. Cela n'affecte pas le SEO. - -## Support des plateformes - -| Option de déploiement | Supporté | -| ------------------------------------------------------------------- | ----------------- | -| [Serveur Node.js](/docs/app/getting-started/deploying#nodejs-server) | Oui | -| [Conteneur Docker](/docs/app/getting-started/deploying#docker) | Oui | -| [Export statique](/docs/app/getting-started/deploying#static-export) | Non | -| [Adaptateurs](/docs/app/getting-started/deploying#adapters) | Dépend de la plateforme | - -Apprenez comment [configurer le streaming](/docs/app/guides/self-hosting#streaming-and-suspense) lors de l'hébergement autonome de Next.js. \ No newline at end of file diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/ja/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/05-images.mdx index c4223517..b4745b69 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T20:01:10.215Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 画像最適化の方法 nav_title: 画像 description: Next.jsにおける画像最適化について学ぶ diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/ja/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/06-fonts.mdx index d4b40542..abdda85f 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:01.061Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: フォントの使用方法 nav_title: フォント description: Next.jsでフォントを使用する方法を学ぶ diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/07-css.mdx index 30a32cbe..13b9b32a 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T20:01:46.267Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: アプリケーションでCSSを使用する方法 nav_title: CSS description: CSSモジュール、グローバルCSS、Tailwind CSSなど、アプリケーションにCSSを追加するさまざまな方法について学びましょう。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/08-server-and-client-components.mdx index c9fc0a0d..05fbbf54 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:03:27.810Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: サーバーコンポーネントとクライアントコンポーネントの使用方法 nav_title: サーバーとクライアントコンポーネント description: Reactのサーバーコンポーネントとクライアントコンポーネントを使用して、アプリケーションの一部をサーバーまたはクライアントでレンダリングする方法を学びましょう。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/ja/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/ja/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index dda67d68..cab76af2 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:07.019Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: データのキャッシュと再検証方法 nav_title: キャッシュと再検証 description: アプリケーションでデータをキャッシュおよび再検証する方法を学びます。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/11-updating-data.mdx index a8da7a4a..ca127f80 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T16:36:21.895Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: データ更新方法 nav_title: データ更新 description: Next.jsアプリケーションでデータを更新する方法について学びます。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/12-error-handling.mdx index 58929656..3b21e8e2 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:06.286Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: エラーハンドリング方法 nav_title: エラーハンドリング description: 予期されるエラーの表示方法とキャッチされない例外の処理方法について学びます。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/13-partial-prerendering.mdx index 245a7f5e..92b4cbec 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:12.039Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 部分プリレンダリング (Partial Prerendering) の使用方法 nav_title: 部分プリレンダリング description: 静的レンダリングと動的レンダリングの利点を組み合わせた部分プリレンダリング (PPR) の使用方法を学びましょう。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/ja/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index 9b5ee240..5b877725 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:01:15.255Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: メタデータの追加とOG画像の作成方法 nav_title: メタデータとOG画像 description: ページにメタデータを追加し、動的なOG画像を作成する方法を学びましょう。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/15-deploying.mdx similarity index 98% rename from apps/docs/content/ja/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/15-deploying.mdx index ca0c8266..d0e14036 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T16:35:25.702Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Next.js アプリケーションのデプロイ方法 nav_title: デプロイ description: Next.js アプリケーションをデプロイする方法を学びます。 diff --git a/apps/docs/content/ja/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/ja/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 95% rename from apps/docs/content/ja/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/ja/docs/01-app/01-getting-started/16-upgrading.mdx index 4cfedcd2..b5609092 100644 --- a/apps/docs/content/ja/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/ja/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:59:29.652Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Next.jsアプリケーションのアップグレード方法 nav_title: アップグレード description: Next.jsアプリケーションを最新バージョンにアップグレードする方法について学びます。 diff --git a/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index eb6d9cee..00000000 --- a/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:10:59.681Z -title: リンクとナビゲーション -description: Next.jsにおけるナビゲーションの仕組みと、`` コンポーネントおよび `useRouter` フックの使用方法について学びましょう。 -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -Next.jsでは、ルート間を移動する方法が4つあります: - -- [`` コンポーネント](#link-component)を使用する -- [`useRouter` フック](#userouter-hook)を使用する([クライアントコンポーネント](/docs/app/getting-started/server-and-client-components)) -- [`redirect` 関数](#redirect-function)を使用する([サーバーコンポーネント](/docs/app/getting-started/server-and-client-components)) -- ネイティブの[History API](#using-the-native-history-api)を使用する - -このページでは、これらの各オプションの使用方法と、ナビゲーションの仕組みについて詳しく説明します。 - -## `` コンポーネント - -`` はHTMLの`
`タグを拡張した組み込みコンポーネントで、[プリフェッチ](#2-prefetching)とクライアントサイドのルート間ナビゲーションを提供します。Next.jsでルート間を移動する主要かつ推奨される方法です。 - -`next/link`からインポートし、`href`プロパティをコンポーネントに渡すことで使用できます: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return ダッシュボード -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return ダッシュボード -} -``` - -``には他にもオプションのプロパティを渡せます。詳細は[APIリファレンス](/docs/app/api-reference/components/link)をご覧ください。 - -## `useRouter()` フック - -`useRouter`フックを使用すると、[クライアントコンポーネント](/docs/app/getting-started/server-and-client-components)からプログラムでルートを変更できます。 - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -`useRouter`の全メソッドについては、[APIリファレンス](/docs/app/api-reference/functions/use-router)をご覧ください。 - -> **推奨事項**: 特別な要件がない限り、ルート間の移動には``コンポーネントを使用してください。 - -## `redirect` 関数 - -[サーバーコンポーネント](/docs/app/getting-started/server-and-client-components)では、代わりに`redirect`関数を使用します。 - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **知っておくと良いこと**: -> -> - `redirect`はデフォルトで307(Temporary Redirect)ステータスコードを返します。Server Actionで使用すると、303(See Other)を返します。これはPOSTリクエストの結果として成功ページにリダイレクトする際によく使用されます。 -> - `redirect`は内部的にエラーをスローするため、`try/catch`ブロックの外で呼び出す必要があります。 -> - `redirect`はレンダリングプロセス中にクライアントコンポーネントで呼び出せますが、イベントハンドラー内では呼び出せません。代わりに[`useRouter`フック](#userouter-hook)を使用してください。 -> - `redirect`は絶対URLも受け入れ、外部リンクへのリダイレクトにも使用できます。 -> - レンダリングプロセスの前にリダイレクトしたい場合は、[`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs)または[ミドルウェア](/docs/app/guides/redirecting#nextresponseredirect-in-middleware)を使用してください。 - -詳細については、[`redirect` APIリファレンス](/docs/app/api-reference/functions/redirect)をご覧ください。 - -## ネイティブのHistory APIの使用 - -Next.jsでは、ネイティブの[`window.history.pushState`](https://developer.mozilla.org/ja/docs/Web/API/History/pushState)と[`window.history.replaceState`](https://developer.mozilla.org/ja/docs/Web/API/History/replaceState)メソッドを使用して、ページを再読み込みせずにブラウザの履歴スタックを更新できます。 - -`pushState`と`replaceState`の呼び出しはNext.jsルーターと統合され、[`usePathname`](/docs/app/api-reference/functions/use-pathname)や[`useSearchParams`](/docs/app/api-reference/functions/use-search-params)と同期できます。 - -### `window.history.pushState` - -ブラウザの履歴スタックに新しいエントリを追加するために使用します。ユーザーは前の状態に戻ることができます。例えば、製品リストをソートする場合: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -ブラウザの履歴スタックの現在のエントリを置き換えるために使用します。ユーザーは前の状態に戻ることができません。例えば、アプリケーションのロケールを切り替える場合: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // 例: '/en/about' または '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // 例: '/en/about' または '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## ルーティングとナビゲーションの仕組み - -App Routerはルーティングとナビゲーションにハイブリッドアプローチを使用します。サーバー側では、アプリケーションコードがルートセグメントごとに自動的に[コード分割](#1-code-splitting)されます。クライアント側では、Next.jsがルートセグメントを[プリフェッチ](#2-prefetching)して[キャッシュ](#3-caching)します。つまり、ユーザーが新しいルートに移動する際、ブラウザはページを再読み込みせず、変更のあるルートセグメントのみが再レンダリングされ、ナビゲーション体験とパフォーマンスが向上します。 - -### 1. コード分割 - -コード分割により、アプリケーションコードを小さなバンドルに分割してブラウザがダウンロード・実行できるようになります。これにより、リクエストごとに転送されるデータ量と実行時間が減少し、パフォーマンスが向上します。 - -[サーバーコンポーネント](/docs/app/getting-started/server-and-client-components)により、アプリケーションコードはルートセグメントごとに自動的にコード分割されます。つまり、ナビゲーション時に現在のルートに必要なコードのみが読み込まれます。 - -### 2. プリフェッチ - -プリフェッチは、ユーザーが訪れる前にルートをバックグラウンドで事前読み込みする方法です。 - -Next.jsでは、ルートをプリフェッチする方法が2つあります: - -- **``コンポーネント**: ユーザーのビューポートに表示されると、ルートが自動的にプリフェッチされます。プリフェッチはページが最初に読み込まれるときや、スクロールによって表示されたときに発生します。 -- **`router.prefetch()`**: `useRouter`フックを使用してプログラムでルートをプリフェッチできます。 - -``のデフォルトのプリフェッチ動作(`prefetch`プロパティが未指定または`null`の場合)は、[`loading.js`](/docs/app/api-reference/file-conventions/loading)の使用状況によって異なります。共有レイアウトと、最初の`loading.js`ファイルまでのレンダリング「ツリー」内のコンポーネントのみがプリフェッチされ、`30秒間`キャッシュされます。これにより、動的ルート全体をフェッチするコストが削減され、ユーザーに視覚的なフィードバックを提供するための[インスタントローディング状態](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states)を表示できます。 - -`prefetch`プロパティを`false`に設定するとプリフェッチを無効にできます。または、`prefetch`プロパティを`true`に設定すると、ローディング境界を超えたページデータ全体をプリフェッチできます。 - -詳細については、[`` APIリファレンス](/docs/app/api-reference/components/link)をご覧ください。 - -> **知っておくと良いこと**: -> -> - プリフェッチは開発環境では有効にならず、本番環境でのみ有効です。 - -### 3. キャッシュ - -Next.jsには[ルーターキャッシュ](/docs/app/deep-dive/caching#client-side-router-cache)と呼ばれる**メモリ内のクライアントサイドキャッシュ**があります。ユーザーがアプリ内を移動すると、[プリフェッチ](#2-prefetching)されたルートセグメントと訪問済みルートのReactサーバーコンポーネントペイロードがキャッシュに保存されます。 - -つまり、ナビゲーション時にキャッシュが可能な限り再利用され、サーバーへの新しいリクエストが減るため、リクエスト数と転送データ量が減少し、パフォーマンスが向上します。 - -[ルーターキャッシュ](/docs/app/deep-dive/caching#client-side-router-cache)の仕組みと設定方法について詳しく学びましょう。 - -### 4. 部分レンダリング - -部分レンダリングとは、ナビゲーション時に変更のあるルートセグメントのみがクライアント側で再レンダリングされ、共有セグメントは保持されることを意味します。 - -例えば、`/dashboard/settings`と`/dashboard/analytics`という2つの兄弟ルート間を移動する場合、`settings`ページはアンマウントされ、`analytics`ページは新しい状態でマウントされ、共有の`dashboard`レイアウトは保持されます。この動作は、`/blog/[slug]/page`のような同じ動的セグメント上の2つのルート間(`/blog/first`から`/blog/second`への移動など)でも見られます。 - -部分レンダリングの仕組み - -部分レンダリングがない場合、各ナビゲーションでクライアント側でページ全体が再レンダリングされます。変更のあるセグメントのみをレンダリングすることで、転送されるデータ量と実行時間が減少し、パフォーマンスが向上します。 - -### 5. ソフトナビゲーション - -ブラウザはページ間を移動する際に「ハードナビゲーション」を実行します。Next.jsのApp Routerはページ間の「ソフトナビゲーション」を可能にし、変更のあるルートセグメントのみが再レンダリングされる(部分レンダリング)ことを保証します。これにより、ナビゲーション中にクライアントのReact状態が保持されます。 - -### 6. 戻る・進むナビゲーション - -デフォルトでは、Next.jsは戻る・進むナビゲーションでスクロール位置を維持し、[ルーターキャッシュ](/docs/app/deep-dive/caching#client-side-router-cache)内のルートセグメントを再利用します。 - -### 7. `pages/`と`app/`間のルーティング - -`pages/`から`app/`への段階的な移行時、Next.jsルーターは自動的に両者の間のハードナビゲーションを処理します。`pages/`から`app/`への遷移を検出するために、クライアントルーターフィルターがアプリルートの確率的チェックを利用していますが、まれに誤検知が発生する可能性があります。デフォルトでは、このような発生は非常に稀で、誤検知の確率は0.01%に設定されています。この確率は`next.config.js`の`experimental.clientRouterFilterAllowedRate`オプションでカスタマイズできます。誤検知率を下げると、クライアントバンドル内の生成されるフィルターのサイズが増加することに注意してください。 - -あるいは、この処理を完全に無効にして`pages/`と`app/`間のルーティングを手動で管理したい場合は、`next.config.js`で`experimental.clientRouterFilter`をfalseに設定できます。この機能を無効にすると、`pages/`内の動的ルートで`app/`ルートと重複するものは、デフォルトでは適切にナビゲーションされません。 \ No newline at end of file diff --git a/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 1c793fb5..00000000 --- a/apps/docs/content/ja/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:10:09.993Z -title: ローディングUIとストリーミング -description: Suspenseを基盤としたローディングUIにより、特定のルートセグメントのフォールバックを作成し、コンテンツの準備が整い次第自動的にストリーミングできます。 ---- - -特別なファイル`loading.js`を使用すると、[React Suspense](https://react.dev/reference/react/Suspense)を活用して意味のあるローディングUIを作成できます。この規約により、ルートセグメントのコンテンツがロードされている間、サーバーから[即時ローディング状態](#instant-loading-states)を表示できます。レンダリングが完了すると、新しいコンテンツが自動的に切り替わります。 - -ローディングUI - -## 即時ローディング状態 - -即時ローディング状態とは、ナビゲーション時に即座に表示されるフォールバックUIです。スケルトンやスピナーなどのローディングインジケーター、または将来の画面の小さなながらも意味のある部分(カバー写真、タイトルなど)を事前にレンダリングできます。これにより、ユーザーはアプリが反応していることを理解でき、より良いユーザー体験を提供できます。 - -フォルダ内に`loading.js`ファイルを追加することでローディング状態を作成します。 - -loading.js 特別ファイル - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // Loading内に任意のUIを追加可能(スケルトンを含む) - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // Loading内に任意のUIを追加可能(スケルトンを含む) - return -} -``` - -同じフォルダ内では、`loading.js`は`layout.js`内にネストされます。`page.js`ファイルとその下のすべての子を自動的に``境界でラップします。 - -loading.js 概要 - -> **知っておくと良いこと**: -> -> - [サーバー中心のルーティング](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works)でもナビゲーションは即時に行われます -> - ナビゲーションは中断可能で、ルートのコンテンツが完全にロードされる前に別のルートに移動できます -> - 新しいルートセグメントがロードされている間も共有レイアウトはインタラクティブなままです - -> **推奨事項**: Next.jsがこの機能を最適化するため、ルートセグメント(レイアウトとページ)には`loading.js`規約を使用してください - -## Suspenseによるストリーミング - -`loading.js`に加えて、独自のUIコンポーネントに対して手動でSuspense境界を作成することもできます。App Routerは[Suspense](https://react.dev/reference/react/Suspense)によるストリーミングをサポートしています。 - -> **知っておくと良いこと**: -> -> - [一部のブラウザ](https://bugs.webkit.org/show_bug.cgi?id=252413)はストリーミングレスポンスをバッファリングします。レスポンスが1024バイトを超えるまでストリーミングレスポンスが表示されない場合があります。これは通常「Hello World」アプリケーションにのみ影響し、実際のアプリケーションでは問題になりません - -### ストリーミングとは? - -ReactとNext.jsにおけるストリーミングの仕組みを理解するには、**サーバーサイドレンダリング (SSR)** とその制限について知るのが役立ちます。 - -SSRでは、ユーザーがページを表示して操作できるようになる前に完了する必要がある一連のステップがあります: - -1. まず、特定のページのすべてのデータがサーバーでフェッチされます -2. サーバーはページのHTMLをレンダリングします -3. ページのHTML、CSS、JavaScriptがクライアントに送信されます -4. 生成されたHTMLとCSSを使用して非インタラクティブなユーザーインターフェースが表示されます -5. 最後に、Reactがユーザーインターフェースを[ハイドレート](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html)してインタラクティブにします - -ストリーミングなしのサーバーレンダリングを示すチャート - -これらのステップは順次的でブロッキングされるため、サーバーはすべてのデータがフェッチされた後にのみページのHTMLをレンダリングできます。また、クライアント側では、ページ内のすべてのコンポーネントのコードがダウンロードされるまでReactはUIをハイドレートできません。 - -ReactとNext.jsのSSRは、可能な限り早く非インタラクティブなページをユーザーに表示することで、知覚されるローディングパフォーマンスを向上させます。 - -ストリーミングなしのサーバーレンダリング - -しかし、サーバー上のすべてのデータフェッチが完了するまでページをユーザーに表示できないため、まだ遅い可能性があります。 - -**ストリーミング**により、ページのHTMLを小さなチャンクに分割し、それらのチャンクをサーバーからクライアントに段階的に送信できます。 - -ストリーミングを伴うサーバーレンダリングの仕組み - -これにより、すべてのデータがロードされる前にUIをレンダリングできるため、ページの一部をより早く表示できます。 - -ストリーミングはReactのコンポーネントモデルとうまく連携します。各コンポーネントはチャンクと見なすことができます。優先度の高いコンポーネント(製品情報など)やデータに依存しないコンポーネント(レイアウトなど)を最初に送信でき、Reactはより早くハイドレーションを開始できます。優先度の低いコンポーネント(レビュー、関連製品など)は、データがフェッチされた後に同じサーバーリクエストで送信できます。 - -ストリーミングを伴うサーバーレンダリングを示すチャート - -ストリーミングは、長いデータリクエストがページレンダリングをブロックするのを防ぎたい場合に特に有益です。[Time To First Byte (TTFB)](https://web.dev/ttfb/)と[First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/)を削減できるためです。また、特に低速なデバイスでは[Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/)の改善にも役立ちます。 - -### 例 - -``は、非同期アクション(データフェッチなど)を実行するコンポーネントをラップし、実行中にフォールバックUI(スケルトン、スピナーなど)を表示し、アクションが完了したらコンポーネントをスワップインすることで動作します。 - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- フィードをロード中...

}> - -
- 天気情報をロード中...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- フィードをロード中...

}> - -
- 天気情報をロード中...

}> - -
-
- ) -} -``` - -Suspenseを使用することで、以下の利点が得られます: - -1. **ストリーミングサーバーレンダリング** - サーバーからクライアントへHTMLを段階的にレンダリング -2. **選択的ハイドレーション** - Reactはユーザーの操作に基づいて、最初にインタラクティブにするコンポーネントを優先します - -Suspenseのその他の例やユースケースについては、[Reactドキュメント](https://react.dev/reference/react/Suspense)を参照してください。 - -### SEO - -- Next.jsは、UIをクライアントにストリーミングする前に、[`generateMetadata`](/docs/app/api-reference/functions/generate-metadata)内のデータフェッチが完了するのを待機します。これにより、ストリーミングレスポンスの最初の部分に``タグが含まれることが保証されます。 -- ストリーミングはサーバーでレンダリングされるため、SEOに影響しません。Googleの[Rich Results Test](https://search.google.com/test/rich-results)ツールを使用して、ページがGoogleのウェブクローラーにどのように表示されるかを確認し、シリアライズされたHTMLを表示できます([出典](https://web.dev/rendering-on-the-web/#seo-considerations))。 - -### ステータスコード - -ストリーミング時には、リクエストが成功したことを示す`200`ステータスコードが返されます。 - -サーバーは、ストリーミングされたコンテンツ内でエラーや問題をクライアントに伝えることができます([`redirect`](/docs/app/api-reference/functions/redirect)や[`notFound`](/docs/app/api-reference/functions/not-found)を使用する場合など)。レスポンスヘッダーは既にクライアントに送信されているため、レスポンスのステータスコードを更新することはできません。これはSEOに影響しません。 - -## プラットフォームサポート - -| デプロイオプション | サポート状況 | -| ------------------------------------------------------------------- | ---------------- | -| [Node.jsサーバー](/docs/app/getting-started/deploying#nodejs-server) | はい | -| [Dockerコンテナ](/docs/app/getting-started/deploying#docker) | はい | -| [静的エクスポート](/docs/app/getting-started/deploying#static-export) | いいえ | -| [アダプター](/docs/app/getting-started/deploying#adapters) | プラットフォーム依存 | - -Next.jsをセルフホスティングする際の[ストリーミング設定](/docs/app/guides/self-hosting#streaming-and-suspense)方法を学びましょう。 \ No newline at end of file diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/ru/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/05-images.mdx index 042b8c7c..dbe5352c 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T19:58:13.210Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Оптимизация изображений nav_title: Изображения description: Узнайте, как оптимизировать изображения в Next.js diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/ru/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/06-fonts.mdx index b7c75a40..8ab877d0 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:58:04.104Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Использование шрифтов nav_title: Шрифты description: Узнайте, как использовать шрифты в Next.js diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/07-css.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/07-css.mdx index 38b659d1..2324c79f 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-06-02T19:58:30.188Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Использование CSS в вашем приложении nav_title: CSS description: Узнайте о различных способах добавления CSS в ваше приложение, включая CSS Modules, Global CSS, Tailwind CSS и другие методы. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/08-server-and-client-components.mdx index e382cbb4..a8ce8fcb 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-06-02T20:00:09.594Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Использование серверных и клиентских компонентов nav_title: Серверные и клиентские компоненты description: Узнайте, как использовать серверные (Server) и клиентские (Client) компоненты React для рендеринга частей приложения на сервере или клиенте. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/ru/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index cd16cbc1..5ed9bf85 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:58:08.319Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Кэширование и ревалидация данных nav_title: Кэширование и ревалидация description: Узнайте, как кэшировать и обновлять данные в вашем приложении. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/11-updating-data.mdx index 00bfe9ed..26fc06f4 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-06T16:44:10.522Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Как обновлять данные nav_title: Обновление данных description: Узнайте, как обновлять данные в вашем приложении Next.js. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/12-error-handling.mdx index 97549ca1..b023077e 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:58:24.710Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Обработка ошибок nav_title: Обработка ошибок description: Узнайте, как отображать ожидаемые ошибки и обрабатывать неперехваченные исключения. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/13-partial-prerendering.mdx index b01135de..20fca765 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:58:27.067Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Как использовать частичный предварительный рендеринг (Partial Prerendering) nav_title: Partial Prerendering description: Узнайте, как сочетать преимущества статического и динамического рендеринга с помощью частичного предварительного рендеринга (PPR). diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/ru/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index aef4c52f..816bce71 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:58:27.645Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Как добавить метаданные и создавать OG-изображения nav_title: Метаданные и OG-изображения description: Узнайте, как добавлять метаданные на страницы и создавать динамические OG-изображения. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/15-deploying.mdx similarity index 98% rename from apps/docs/content/ru/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/15-deploying.mdx index deeb486f..d0f36fb1 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-05T23:52:35.000Z -translation-updated-at: 2025-06-06T16:43:20.246Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Как развернуть приложение Next.js nav_title: Развертывание description: Узнайте, как развернуть ваше приложение Next.js. diff --git a/apps/docs/content/ru/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/ru/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 96% rename from apps/docs/content/ru/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/ru/docs/01-app/01-getting-started/16-upgrading.mdx index a7d01371..14042ee3 100644 --- a/apps/docs/content/ru/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/ru/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T19:56:48.742Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: Как обновить приложение Next.js nav_title: Обновление description: Узнайте, как обновить ваше приложение Next.js до последней версии. diff --git a/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index acba695d..00000000 --- a/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-02T20:11:31.023Z -title: Связывание и навигация -description: Узнайте, как работает навигация в Next.js, и как использовать компонент Link и хук `useRouter`. -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -В Next.js существует четыре способа навигации между маршрутами: - -- Использование [компонента ``](#link-component) -- Использование [хука `useRouter`](#userouter-hook) ([Клиентские компоненты](/docs/app/getting-started/server-and-client-components)) -- Использование [функции `redirect`](#redirect-function) ([Серверные компоненты](/docs/app/getting-started/server-and-client-components)) -- Использование нативного [History API](#using-the-native-history-api) - -На этой странице мы рассмотрим, как использовать каждый из этих вариантов, и углубимся в принципы работы навигации. - -## Компонент `` - -`` — это встроенный компонент, расширяющий HTML-тег `
` для обеспечения [предварительной загрузки](#2-prefetching) и клиентской навигации между маршрутами. Это основной и рекомендуемый способ навигации в Next.js. - -Его можно использовать, импортировав из `next/link` и передав проп `href`: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -Существуют другие необязательные пропсы, которые можно передать в ``. Подробнее см. в [справочнике API](/docs/app/api-reference/components/link). - -## Хук `useRouter()` - -Хук `useRouter` позволяет программно изменять маршруты из [Клиентских компонентов](/docs/app/getting-started/server-and-client-components). - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -Полный список методов `useRouter` см. в [справочнике API](/docs/app/api-reference/functions/use-router). - -> **Рекомендация:** Используйте компонент `` для навигации между маршрутами, если у вас нет особых причин использовать `useRouter`. - -## Функция `redirect` - -Для [Серверных компонентов](/docs/app/getting-started/server-and-client-components) используйте функцию `redirect`. - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **Полезно знать**: -> -> - По умолчанию `redirect` возвращает код состояния 307 (Временное перенаправление). При использовании в Server Action возвращается код 303 (Смотреть другое), который обычно применяется для перенаправления на страницу успеха после POST-запроса. -> - `redirect` внутренне выбрасывает ошибку, поэтому его следует вызывать вне блоков `try/catch`. -> - `redirect` можно вызывать в Клиентских компонентах во время рендеринга, но не в обработчиках событий. Вместо этого используйте [хук `useRouter`](#userouter-hook). -> - `redirect` также принимает абсолютные URL и может использоваться для перенаправления на внешние ссылки. -> - Если нужно выполнить перенаправление до процесса рендеринга, используйте [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) или [Middleware](/docs/app/guides/redirecting#nextresponseredirect-in-middleware). - -Подробнее см. в [справочнике API `redirect`](/docs/app/api-reference/functions/redirect). - -## Использование нативного History API - -Next.js позволяет использовать нативные методы [`window.history.pushState`](https://developer.mozilla.org/ru/docs/Web/API/History/pushState) и [`window.history.replaceState`](https://developer.mozilla.org/ru/docs/Web/API/History/replaceState) для обновления истории браузера без перезагрузки страницы. - -Вызовы `pushState` и `replaceState` интегрируются с роутером Next.js, позволяя синхронизироваться с [`usePathname`](/docs/app/api-reference/functions/use-pathname) и [`useSearchParams`](/docs/app/api-reference/functions/use-search-params). - -### `window.history.pushState` - -Используется для добавления новой записи в историю браузера. Пользователь может вернуться к предыдущему состоянию. Например, для сортировки списка товаров: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -Используется для замены текущей записи в истории браузера. Пользователь не сможет вернуться к предыдущему состоянию. Например, для переключения локали приложения: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // Например, '/en/about' или '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // Например, '/en/about' или '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## Как работают маршрутизация и навигация - -App Router использует гибридный подход к маршрутизации и навигации. На сервере код вашего приложения автоматически [разделяется на части](#1-code-splitting) по сегментам маршрутов. А на клиенте Next.js [предварительно загружает](#2-prefetching) и [кэширует](#3-caching) сегменты маршрутов. Это означает, что при переходе пользователя на новый маршрут страница не перезагружается, а перерисовываются только изменившиеся сегменты — что улучшает опыт навигации и производительность. - -### 1. Разделение кода (Code Splitting) - -Разделение кода позволяет разбить код приложения на меньшие части для загрузки и выполнения браузером. Это уменьшает объем передаваемых данных и время выполнения каждого запроса, повышая производительность. - -[Серверные компоненты](/docs/app/getting-started/server-and-client-components) позволяют автоматически разделять код приложения по сегментам маршрутов. Это означает, что при навигации загружается только код, необходимый для текущего маршрута. - -### 2. Предварительная загрузка (Prefetching) - -Предварительная загрузка позволяет загружать маршрут в фоновом режиме до того, как пользователь посетит его. - -В Next.js есть два способа предварительной загрузки маршрутов: - -- **Компонент ``**: Маршруты автоматически предзагружаются, когда становятся видимыми в области просмотра пользователя. Это происходит при первой загрузке страницы или при прокрутке. -- **`router.prefetch()`**: Хук `useRouter` можно использовать для программной предзагрузки маршрутов. - -Поведение предзагрузки `` по умолчанию (когда проп `prefetch` не указан или равен `null`) зависит от использования [`loading.js`](/docs/app/api-reference/file-conventions/loading). Предзагружается и кэшируется только общий макет до первого файла `loading.js` в дереве компонентов на `30s`. Это снижает затраты на загрузку динамического маршрута и позволяет показать [мгновенное состояние загрузки](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states) для лучшей визуальной обратной связи. - -Можно отключить предзагрузку, установив проп `prefetch` в `false`. Или загрузить полные данные страницы за пределами границ загрузки, установив `prefetch` в `true`. - -Подробнее см. в [справочнике API ``](/docs/app/api-reference/components/link). - -> **Полезно знать**: -> -> - Предзагрузка работает только в production, а не в development. - -### 3. Кэширование - -Next.js имеет **клиентский кэш в памяти** под названием [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). При навигации по приложению полезная нагрузка React Server Component для [предзагруженных](#2-prefetching) и посещенных сегментов маршрутов сохраняется в кэше. - -Это означает, что при навигации кэш повторно используется вместо нового запроса к серверу — что улучшает производительность, сокращая количество запросов и объем передаваемых данных. - -Узнайте больше о работе [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) и его настройке. - -### 4. Частичный рендеринг (Partial Rendering) - -Частичный рендеринг означает, что на клиенте перерисовываются только изменившиеся сегменты маршрутов, а общие сегменты сохраняются. - -Например, при переходе между двумя родственными маршрутами `/dashboard/settings` и `/dashboard/analytics`, страница `settings` будет размонтирована, страница `analytics` смонтирована с новым состоянием, а общий макет `dashboard` сохранится. Такое же поведение наблюдается между маршрутами с динамическими сегментами, например, `/blog/[slug]/page` при переходе от `/blog/first` к `/blog/second`. - -Как работает частичный рендеринг - -Без частичного рендеринга каждая навигация вызывала бы полную перерисовку страницы на клиенте. Рендеринг только изменяющихся сегментов сокращает объем передаваемых данных и время выполнения, улучшая производительность. - -### 5. Мягкая навигация (Soft Navigation) - -Браузеры выполняют "жесткую навигацию" при переходе между страницами. App Router Next.js обеспечивает "мягкую навигацию", при которой перерисовываются только изменившиеся сегменты маршрутов (частичный рендеринг). Это позволяет сохранять состояние React на клиенте во время навигации. - -### 6. Навигация назад и вперед - -По умолчанию Next.js сохраняет позицию прокрутки при навигации назад и вперед и повторно использует сегменты маршрутов из [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). - -### 7. Маршрутизация между `pages/` и `app/` - -При постепенной миграции с `pages/` на `app/` роутер Next.js автоматически обрабатывает жесткую навигацию между ними. Для обнаружения переходов из `pages/` в `app/` используется клиентский фильтр роутера с вероятностной проверкой маршрутов приложения, что иногда может давать ложные срабатывания. По умолчанию такие случаи должны быть очень редкими, так как вероятность ложного срабатывания установлена на 0.01%. Эту вероятность можно настроить через опцию `experimental.clientRouterFilterAllowedRate` в `next.config.js`. Важно отметить, что снижение вероятности ложных срабатываний увеличит размер фильтра в клиентском бандле. - -Альтернативно, если вы предпочитаете полностью отключить эту обработку и управлять маршрутизацией между `pages/` и `app/` вручную, можно установить `experimental.clientRouterFilter` в `false` в `next.config.js`. При отключении этой функции динамические маршруты в `pages`, пересекающиеся с маршрутами в `app`, по умолчанию не будут обрабатываться корректно. \ No newline at end of file diff --git a/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 65dea861..00000000 --- a/apps/docs/content/ru/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-06-02T20:10:53.012Z -title: Загрузочный интерфейс и потоковая передача -description: На основе Suspense, загрузочный интерфейс позволяет создать резервный вариант для отдельных сегментов маршрута и автоматически передавать контент по мере его готовности. ---- - -Специальный файл `loading.js` помогает создавать информативный загрузочный интерфейс с помощью [React Suspense](https://react.dev/reference/react/Suspense). С этим соглашением вы можете показывать [мгновенное состояние загрузки](#instant-loading-states) с сервера, пока загружается контент сегмента маршрута. Новый контент автоматически заменяется после завершения рендеринга. - -Загрузочный интерфейс - -## Мгновенные состояния загрузки - -Мгновенное состояние загрузки — это резервный интерфейс, который отображается сразу при переходе. Вы можете предварительно отрендерить индикаторы загрузки, такие как скелетоны и спиннеры, или небольшую, но значимую часть будущего экрана, например обложку, заголовок и т.д. Это помогает пользователям понять, что приложение реагирует, и улучшает пользовательский опыт. - -Создайте состояние загрузки, добавив файл `loading.js` в папку. - -Специальный файл loading.js - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // Внутри Loading можно добавить любой интерфейс, включая скелетон. - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // Внутри Loading можно добавить любой интерфейс, включая скелетон. - return -} -``` - -В той же папке `loading.js` будет вложен в `layout.js`. Он автоматически обернет файл `page.js` и все дочерние элементы в границу ``. - -Обзор loading.js - -> **Полезно знать**: -> -> - Навигация происходит мгновенно, даже с [сервероцентричной маршрутизацией](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works). -> - Навигация прерывается, то есть изменение маршрута не требует полной загрузки контента текущего маршрута перед переходом на другой. -> - Общие макеты остаются интерактивными во время загрузки новых сегментов маршрута. - -> **Рекомендация:** Используйте соглашение `loading.js` для сегментов маршрута (макетов и страниц), так как Next.js оптимизирует эту функциональность. - -## Потоковая передача с Suspense - -Помимо `loading.js`, вы также можете вручную создавать границы Suspense для своих компонентов интерфейса. App Router поддерживает потоковую передачу с [Suspense](https://react.dev/reference/react/Suspense). - -> **Полезно знать**: -> -> - [Некоторые браузеры](https://bugs.webkit.org/show_bug.cgi?id=252413) буферизуют потоковый ответ. Вы можете не увидеть потоковый ответ, пока он не превысит 1024 байта. Обычно это затрагивает только простые приложения, но не реальные проекты. - -### Что такое потоковая передача? - -Чтобы понять, как работает потоковая передача в React и Next.js, полезно разобраться в **рендеринге на стороне сервера (SSR)** и его ограничениях. - -При SSR есть ряд шагов, которые необходимо выполнить, прежде чем пользователь сможет увидеть и взаимодействовать со страницей: - -1. Сначала все данные для страницы загружаются на сервере. -2. Затем сервер рендерит HTML для страницы. -3. HTML, CSS и JavaScript для страницы отправляются клиенту. -4. Показывается неинтерактивный интерфейс с использованием сгенерированного HTML и CSS. -5. Наконец, React [гидратирует](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) интерфейс, чтобы сделать его интерактивным. - -Диаграмма серверного рендеринга без потоковой передачи - -Эти шаги выполняются последовательно и блокируют друг друга, то есть сервер может рендерить HTML для страницы только после загрузки всех данных. А на клиенте React может гидратировать интерфейс только после загрузки кода всех компонентов страницы. - -SSR с React и Next.js помогает улучшить воспринимаемую скорость загрузки, показывая пользователю неинтерактивную страницу как можно быстрее. - -Серверный рендеринг без потоковой передачи - -Однако это всё равно может быть медленным, так как все запросы данных на сервере должны завершиться перед показом страницы пользователю. - -**Потоковая передача** позволяет разбить HTML страницы на меньшие части и постепенно отправлять их с сервера на клиент. - -Как работает серверный рендеринг с потоковой передачей - -Это позволяет отображать части страницы раньше, не дожидаясь загрузки всех данных перед рендерингом любого интерфейса. - -Потоковая передача хорошо сочетается с компонентной моделью React, так как каждый компонент можно рассматривать как часть. Компоненты с более высоким приоритетом (например, информация о продукте) или не зависящие от данных могут быть отправлены первыми (например, макет), и React может начать гидратацию раньше. Компоненты с более низким приоритетом (например, отзывы, связанные товары) могут быть отправлены в том же серверном запросе после загрузки их данных. - -Диаграмма серверного рендеринга с потоковой передачей - -Потоковая передача особенно полезна, когда вы хотите предотвратить блокировку рендеринга страницы из-за длительных запросов данных, так как она может уменьшить [Time To First Byte (TTFB)](https://web.dev/ttfb/) и [First Contentful Paint (FCP)](https://web.dev/first-contentful-paint/). Она также помогает улучшить [Time to Interactive (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/), особенно на медленных устройствах. - -### Пример - -`` работает, оборачивая компонент, выполняющий асинхронное действие (например, загрузку данных), показывая резервный интерфейс (например, скелетон, спиннер) во время выполнения действия, а затем заменяя его вашим компонентом после завершения. - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Загрузка ленты...

}> - -
- Загрузка погоды...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- Загрузка ленты...

}> - -
- Загрузка погоды...

}> - -
-
- ) -} -``` - -Используя Suspense, вы получаете преимущества: - -1. **Потоковый серверный рендеринг** — Постепенный рендеринг HTML с сервера на клиент. -2. **Избирательная гидратация** — React приоритезирует, какие компоненты сделать интерактивными первыми, основываясь на взаимодействии пользователя. - -Дополнительные примеры и случаи использования Suspense можно найти в [документации React](https://react.dev/reference/react/Suspense). - -### SEO - -- Next.js будет ждать завершения загрузки данных внутри [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) перед потоковой передачей интерфейса клиенту. Это гарантирует, что первая часть потокового ответа включает теги ``. -- Поскольку потоковая передача выполняется на сервере, она не влияет на SEO. Вы можете использовать [инструмент Rich Results Test](https://search.google.com/test/rich-results) от Google, чтобы увидеть, как ваша страница выглядит для веб-краулеров Google, и просмотреть сериализованный HTML ([источник](https://web.dev/rendering-on-the-web/#seo-considerations)). - -### Коды состояния - -При потоковой передаче возвращается код состояния `200`, указывающий на успешность запроса. - -Сервер всё ещё может сообщать об ошибках или проблемах клиенту внутри самого потокового контента, например, при использовании [`redirect`](/docs/app/api-reference/functions/redirect) или [`notFound`](/docs/app/api-reference/functions/not-found). Поскольку заголовки ответа уже отправлены клиенту, код состояния ответа не может быть обновлён. Это не влияет на SEO. - -## Поддержка платформ - -| Вариант развертывания | Поддерживается | -| ------------------------------------------------------------------- | ------------------ | -| [Сервер Node.js](/docs/app/getting-started/deploying#nodejs-server) | Да | -| [Docker-контейнер](/docs/app/getting-started/deploying#docker) | Да | -| [Статический экспорт](/docs/app/getting-started/deploying#static-export) | Нет | -| [Адаптеры](/docs/app/getting-started/deploying#adapters) | Зависит от платформы | - -Узнайте, как [настроить потоковую передачу](/docs/app/guides/self-hosting#streaming-and-suspense) при самостоятельном хостинге Next.js. \ No newline at end of file diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-images.mdx index e7e2f685..084eafba 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T19:01:22.562Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何优化图片 nav_title: 图片 description: 了解如何在 Next.js 中优化图片 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-fonts.mdx index 06e66a06..f97ea4ee 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:10:32.521Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用字体 nav_title: 字体 description: 学习如何在 Next.js 中使用字体 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-css.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-css.mdx index 9f483d77..7391f856 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-05-25T20:26:25.233Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何在应用中使用 CSS nav_title: CSS description: 了解在应用中添加 CSS 的不同方式,包括 CSS 模块 (CSS Modules)、全局 CSS (Global CSS)、Tailwind CSS 等。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/08-server-and-client-components.mdx index eafa7b12..c94e841f 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-05-23T16:46:15.689Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用服务端组件与客户端组件 nav_title: 服务端与客户端组件 description: 了解如何利用 React 服务端组件 (Server Components) 和客户端组件 (Client Components) 在服务端或客户端渲染应用的不同部分。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index 161b781e..a5b70dad 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:10:00.706Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 数据缓存与重新验证方法 nav_title: 缓存与重新验证 description: 学习如何在应用程序中缓存和重新验证数据。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-updating-data.mdx index 675af726..62585fa4 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-05T23:37:56.407Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何更新数据 nav_title: 数据更新 description: 学习如何在 Next.js 应用中更新数据。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-error-handling.mdx index d978ff35..a467f02c 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:10:12.334Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 错误处理指南 nav_title: 错误处理 description: 了解如何显示预期错误并处理未捕获异常。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 98% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-partial-prerendering.mdx index a5376d16..eac4668b 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用部分预渲染 (Partial Prerendering) nav_title: 部分预渲染 description: 了解如何通过部分预渲染 (Partial Prerendering) 结合静态渲染与动态渲染的优势。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index 798a275c..416965c2 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:10:24.865Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何添加元数据并创建 OG 图片 nav_title: 元数据与 OG 图片 description: 了解如何为页面添加元数据并创建动态 OG 图片。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-deploying.mdx similarity index 97% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-deploying.mdx index f5d521ad..b2901615 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何部署你的 Next.js 应用 nav_title: 部署指南 description: 学习如何部署你的 Next.js 应用。 diff --git a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 94% rename from apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/zh-hans/docs/01-app/01-getting-started/16-upgrading.mdx index 50dba102..e42f83c7 100644 --- a/apps/docs/content/zh-hans/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/zh-hans/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何升级你的 Next.js 应用 nav_title: 升级指南 description: 学习如何将你的 Next.js 应用升级至最新版本。 diff --git a/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index 53906359..00000000 --- a/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:17:50.398Z -title: 链接与导航 -description: 了解 Next.js 中的导航工作原理,以及如何使用 Link 组件和 `useRouter` 钩子。 -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -在 Next.js 中有四种方式实现路由间的导航: - -- 使用 [`` 组件](#link-component) -- 使用 [`useRouter` 钩子](#userouter-hook)([客户端组件](/docs/app/getting-started/server-and-client-components)) -- 使用 [`redirect` 函数](#redirect-function)([服务端组件](/docs/app/getting-started/server-and-client-components)) -- 使用原生 [History API](#using-the-native-history-api) - -本页将介绍如何使用这些选项,并深入探讨导航的工作原理。 - -## `` 组件 - -`` 是一个内置组件,它扩展了 HTML `
` 标签的功能,提供[预加载](#2-prefetching)和客户端路由导航。这是 Next.js 中推荐的主要路由导航方式。 - -你可以从 `next/link` 导入它,并向组件传递 `href` 属性: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -你还可以向 `` 传递其他可选属性。详见 [API 参考文档](/docs/app/api-reference/components/link)。 - -## `useRouter()` 钩子 - -`useRouter` 钩子允许你在[客户端组件](/docs/app/getting-started/server-and-client-components)中以编程方式更改路由。 - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -有关 `useRouter` 方法的完整列表,请参阅 [API 参考文档](/docs/app/api-reference/functions/use-router)。 - -> **推荐:** 除非有特殊需求,否则应优先使用 `` 组件进行路由导航。 - -## `redirect` 函数 - -对于[服务端组件](/docs/app/getting-started/server-and-client-components),请使用 `redirect` 函数。 - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **须知:** -> -> - `redirect` 默认返回 307(临时重定向)状态码。在服务器操作中使用时,它会返回 303(参见其他),通常用于在 POST 请求后重定向到成功页面。 -> - `redirect` 内部会抛出错误,因此应在 `try/catch` 块之外调用。 -> - `redirect` 可以在客户端组件的渲染过程中调用,但不能在事件处理程序中调用。这种情况下应使用 [`useRouter` 钩子](#userouter-hook)。 -> - `redirect` 也接受绝对 URL,可用于重定向到外部链接。 -> - 如果需要在渲染过程之前重定向,请使用 [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) 或 [中间件](/docs/app/guides/redirecting#nextresponseredirect-in-middleware)。 - -更多信息请参阅 [`redirect` API 参考文档](/docs/app/api-reference/functions/redirect)。 - -## 使用原生 History API - -Next.js 允许使用原生的 [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) 和 [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) 方法来更新浏览器的历史记录栈而无需重新加载页面。 - -`pushState` 和 `replaceState` 调用会与 Next.js 路由器集成,使你可以与 [`usePathname`](/docs/app/api-reference/functions/use-pathname) 和 [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) 同步。 - -### `window.history.pushState` - -用于向浏览器的历史记录栈添加新条目。用户可以导航回先前的状态。例如,对产品列表进行排序: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -用于替换浏览器历史记录栈中的当前条目。用户无法导航回先前的状态。例如,切换应用程序的语言环境: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // 例如 '/en/about' 或 '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // 例如 '/en/about' 或 '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## 路由与导航工作原理 - -应用路由器采用混合方法实现路由和导航。在服务器端,你的应用代码会根据路由段自动进行[代码分割](#1-code-splitting)。在客户端,Next.js 会[预加载](#2-prefetching)并[缓存](#3-caching)路由段。这意味着当用户导航到新路由时,浏览器不会重新加载页面,只有发生变化的路由段会重新渲染——从而提升导航体验和性能。 - -### 1. 代码分割 - -代码分割允许你将应用代码拆分为更小的包,由浏览器下载和执行。这减少了每次请求传输的数据量和执行时间,从而提升性能。 - -[服务端组件](/docs/app/getting-started/server-and-client-components)允许你的应用代码按路由段自动进行代码分割。这意味着导航时只加载当前路由所需的代码。 - -### 2. 预加载 - -预加载是一种在用户访问路由前在后台预先加载路由的方式。 - -Next.js 中有两种预加载路由的方式: - -- **`` 组件**:当路由出现在用户视口中时自动预加载。预加载发生在页面首次加载或通过滚动进入视图时。 -- **`router.prefetch()`**:可以使用 `useRouter` 钩子以编程方式预加载路由。 - -`` 的默认预加载行为(即当 `prefetch` 属性未指定或设为 `null` 时)会根据 [`loading.js`](/docs/app/api-reference/file-conventions/loading) 的使用情况而有所不同。只有共享布局,直到第一个 `loading.js` 文件的渲染"树"会被预加载并缓存 `30s`。这降低了获取整个动态路由的成本,意味着你可以显示[即时加载状态](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states)以提供更好的视觉反馈。 - -你可以通过将 `prefetch` 属性设为 `false` 来禁用预加载。或者,也可以通过将 `prefetch` 属性设为 `true` 来预加载超出加载边界的完整页面数据。 - -更多信息请参阅 [`` API 参考文档](/docs/app/api-reference/components/link)。 - -> **须知:** -> -> - 预加载仅在生产环境中启用,开发环境中不启用。 - -### 3. 缓存 - -Next.js 有一个称为[路由器缓存](/docs/app/deep-dive/caching#client-side-router-cache)的**内存客户端缓存**。当用户在应用中导航时,[预加载](#2-prefetching)的路由段和已访问路由的 React 服务端组件负载会被存储在缓存中。 - -这意味着在导航时,会尽可能重用缓存,而不是向服务器发起新请求——通过减少请求次数和传输数据量来提升性能。 - -了解更多关于[路由器缓存](/docs/app/deep-dive/caching#client-side-router-cache)的工作原理及如何配置。 - -### 4. 部分渲染 - -部分渲染意味着在客户端导航时,只有发生变化的路由段会重新渲染,任何共享段都会被保留。 - -例如,当在两个同级路由 `/dashboard/settings` 和 `/dashboard/analytics` 之间导航时,`settings` 页面会被卸载,`analytics` 页面会以新状态挂载,而共享的 `dashboard` 布局会被保留。这种行为也存在于同一动态段上的两个路由之间,例如 `/blog/[slug]/page` 和从 `/blog/first` 导航到 `/blog/second`。 - -部分渲染工作原理 - -如果没有部分渲染,每次导航都会导致客户端重新渲染整个页面。仅渲染发生变化的部分减少了传输的数据量和执行时间,从而提升性能。 - -### 5. 软导航 - -浏览器在页面间导航时会执行"硬导航"。Next.js 应用路由器实现了页面间的"软导航",确保只有发生变化的路由段会重新渲染(部分渲染)。这使得客户端 React 状态在导航过程中得以保留。 - -### 6. 前进和后退导航 - -默认情况下,Next.js 会为前进和后退导航保持滚动位置,并重用[路由器缓存](/docs/app/deep-dive/caching#client-side-router-cache)中的路由段。 - -### 7. `pages/` 和 `app/` 之间的路由 - -当从 `pages/` 逐步迁移到 `app/` 时,Next.js 路由器会自动处理两者之间的硬导航。为了检测从 `pages/` 到 `app/` 的转换,有一个客户端路由器过滤器利用概率检查应用路由,偶尔可能会出现误报。默认情况下,这种情况应该非常罕见,因为我们将误报可能性配置为 0.01%。可以通过 `next.config.js` 中的 `experimental.clientRouterFilterAllowedRate` 选项自定义此可能性。需要注意的是,降低误报率会增加客户端包中生成的过滤器大小。 - -或者,如果你希望完全禁用此处理并手动管理 `pages/` 和 `app/` 之间的路由,可以在 `next.config.js` 中将 `experimental.clientRouterFilter` 设为 false。禁用此功能后,任何与 app 路由重叠的 pages 动态路由默认将无法正确导航。 \ No newline at end of file diff --git a/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index 453bcce9..00000000 --- a/apps/docs/content/zh-hans/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-05-20T22:53:02.748Z -title: 加载界面与流式传输 -description: 基于 Suspense 构建的加载界面允许您为特定路由段创建备用界面,并在内容准备就绪时自动进行流式传输。 ---- - -特殊文件 `loading.js` 可帮助您利用 [React Suspense](https://react.dev/reference/react/Suspense) 创建有意义的加载界面。通过此约定,您可以在路由段内容加载时展示来自服务器的[即时加载状态](#instant-loading-states)。渲染完成后,新内容会自动替换显示。 - -加载界面 - -## 即时加载状态 - -即时加载状态是导航时立即显示的备用界面。您可以预渲染加载指示器(如骨架屏和旋转器),或未来屏幕中有意义的小部分内容(如封面图、标题等)。这有助于用户理解应用正在响应,并提供更好的用户体验。 - -通过在文件夹内添加 `loading.js` 文件来创建加载状态。 - -loading.js 特殊文件 - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // 您可以在 Loading 中添加任何界面,包括骨架屏 - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // 您可以在 Loading 中添加任何界面,包括骨架屏 - return -} -``` - -在同一文件夹中,`loading.js` 会被嵌套在 `layout.js` 内。它会自动将 `page.js` 文件及其子内容包裹在 `` 边界中。 - -loading.js 概览 - -> **须知**: -> -> - 即使采用[以服务端为中心的路由](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works),导航也是即时的。 -> - 导航可被中断,这意味着切换路由时无需等待当前路由内容完全加载。 -> - 共享布局在新路由段加载时仍保持可交互状态。 - -> **推荐**: 对路由段(布局和页面)使用 `loading.js` 约定,因为 Next.js 对此功能进行了优化。 - -## 使用 Suspense 进行流式传输 - -除了 `loading.js`,您还可以为自己的界面组件手动创建 Suspense 边界。应用路由支持通过 [Suspense](https://react.dev/reference/react/Suspense) 进行流式传输。 - -> **须知**: -> -> - [某些浏览器](https://bugs.webkit.org/show_bug.cgi?id=252413)会缓冲流式响应。如果响应小于 1024 字节,您可能看不到流式响应。这通常只影响 "hello world" 示例应用,而非实际应用。 - -### 什么是流式传输? - -要理解流式传输在 React 和 Next.js 中的工作原理,首先需要了解**服务端渲染 (SSR)** 及其局限性。 - -使用 SSR 时,用户看到页面并与之交互前需要完成以下步骤: - -1. 首先,在服务端获取页面的所有数据。 -2. 服务端渲染页面的 HTML。 -3. 将页面的 HTML、CSS 和 JavaScript 发送到客户端。 -4. 使用生成的 HTML 和 CSS 展示非交互式界面。 -5. 最后,React [注水 (hydrate)](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) 界面使其可交互。 - -未使用流式传输的服务端渲染示意图 - -这些步骤是顺序且阻塞的,意味着服务端只有在所有数据获取完成后才能渲染页面 HTML。而在客户端,React 只有在页面所有组件的代码下载完成后才能进行注水。 - -React 和 Next.js 的 SSR 通过尽快向用户展示非交互式页面,提升了感知加载性能。 - -未使用流式传输的服务端渲染 - -然而,由于服务端所有数据获取完成后才能向用户展示页面,这种方式仍然可能较慢。 - -**流式传输**允许将页面的 HTML 拆分为较小的块,并逐步从服务端发送到客户端。 - -使用流式传输的服务端渲染工作原理 - -这样可以在不等待所有数据加载的情况下,尽早显示页面的部分内容。 - -流式传输与 React 的组件模型配合良好,因为每个组件可视为一个块。优先级较高的组件(如产品信息)或不依赖数据的组件(如布局)可以优先发送,React 可以更早开始注水。优先级较低的组件(如评论、相关产品)可以在同一服务端请求中,在其数据获取完成后发送。 - -使用流式传输的服务端渲染示意图 - -流式传输特别有助于防止长时间的数据请求阻塞页面渲染,可减少[首字节时间 (TTFB)](https://web.dev/ttfb/) 和[首次内容绘制 (FCP)](https://web.dev/first-contentful-paint/),还能改善[可交互时间 (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/),尤其是在较慢的设备上。 - -### 示例 - -`` 的工作原理是包裹执行异步操作(如获取数据)的组件,在操作期间显示备用界面(如骨架屏、旋转器),操作完成后替换为您的组件。 - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- 加载动态中...

}> - -
- 加载天气中...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- 加载动态中...

}> - -
- 加载天气中...

}> - -
-
- ) -} -``` - -使用 Suspense 可获得以下优势: - -1. **流式服务端渲染** - 逐步从服务端向客户端渲染 HTML。 -2. **选择性注水** - React 根据用户交互优先处理需要先交互的组件。 - -更多 Suspense 示例和用例,请参阅 [React 文档](https://react.dev/reference/react/Suspense)。 - -### SEO - -- Next.js 会等待 [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) 内的数据获取完成后再向客户端流式传输界面。这确保流式响应的第一部分包含 `` 标签。 -- 由于流式传输是服务端渲染的,不会影响 SEO。您可以使用 Google 的[富媒体搜索结果测试](https://search.google.com/test/rich-results)工具查看页面在 Google 网络爬虫中的呈现方式,并查看序列化后的 HTML([来源](https://web.dev/rendering-on-the-web/#seo-considerations))。 - -### 状态码 - -流式传输时会返回 `200` 状态码表示请求成功。 - -服务端仍可通过流式内容本身向客户端传达错误或问题,例如使用 [`redirect`](/docs/app/api-reference/functions/redirect) 或 [`notFound`](/docs/app/api-reference/functions/not-found) 时。由于响应头已发送给客户端,无法更新响应状态码。这不影响 SEO。 - -## 平台支持 - -| 部署方式 | 是否支持 | -| ------------------------------------------------------------ | ----------------- | -| [Node.js 服务端](/docs/app/getting-started/deploying#nodejs-server) | 是 | -| [Docker 容器](/docs/app/getting-started/deploying#docker) | 是 | -| [静态导出](/docs/app/getting-started/deploying#static-export) | 否 | -| [适配器](/docs/app/getting-started/deploying#adapters) | 取决于具体平台 | - -了解如何[配置流式传输](/docs/app/guides/self-hosting#streaming-and-suspense)以自托管 Next.js。 \ No newline at end of file diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/04-images.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-images.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/04-images.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-images.mdx index 5407a15d..cfa38fe7 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/04-images.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-02T15:30:01.000Z -translation-updated-at: 2025-06-02T19:01:25.908Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何優化圖片 nav_title: 圖片 description: 學習如何在 Next.js 中優化圖片 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-fonts.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-fonts.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-fonts.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-fonts.mdx index 11e8ac99..af7ec295 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/05-fonts.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-fonts.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:26:21.518Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用字體 nav_title: 字體 description: 了解如何在 Next.js 中使用字體 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-css.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-css.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-css.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-css.mdx index e975aa04..afcf7069 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/06-css.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-css.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-25T15:16:02.000Z -translation-updated-at: 2025-05-25T20:43:08.402Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何在應用程式中使用 CSS nav_title: CSS description: 了解在應用程式中添加 CSS 的各種方法,包括 CSS 模組 (CSS Modules)、全域 CSS (Global CSS)、Tailwind CSS 等。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-server-and-client-components.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/08-server-and-client-components.mdx similarity index 99% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-server-and-client-components.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/08-server-and-client-components.mdx index d195ebf4..ac0b2d33 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/07-server-and-client-components.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/08-server-and-client-components.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-05-22T15:18:56.000Z -translation-updated-at: 2025-05-25T20:44:18.830Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用伺服器與客戶端元件 nav_title: 伺服器與客戶端元件 description: 了解如何透過 React 伺服器元件 (Server Components) 與客戶端元件 (Client Components) 在伺服器或客戶端渲染應用程式的不同部分。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/08-fetching-data.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/09-fetching-data.mdx similarity index 100% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/08-fetching-data.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/09-fetching-data.mdx diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx index 6ca90f3b..ba4c3c95 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/09-caching-and-revalidating.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-caching-and-revalidating.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:25:56.727Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何快取與重新驗證資料 nav_title: 快取與重新驗證 description: 學習如何在應用程式中快取與重新驗證資料。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-updating-data.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-updating-data.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-updating-data.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-updating-data.mdx index e9771cc5..e24e92a1 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/10-updating-data.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-updating-data.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-03T15:30:49.000Z -translation-updated-at: 2025-06-05T23:40:14.407Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何更新資料 nav_title: 更新資料 description: 了解如何在您的 Next.js 應用程式中更新資料。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-error-handling.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-error-handling.mdx similarity index 98% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-error-handling.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-error-handling.mdx index a4453787..9bc476ac 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/11-error-handling.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-error-handling.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:26:06.037Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 錯誤處理指南 nav_title: 錯誤處理 description: 學習如何顯示預期錯誤並處理未捕獲的異常。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-partial-prerendering.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-partial-prerendering.mdx similarity index 99% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-partial-prerendering.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-partial-prerendering.mdx index 1c65e856..f0594b08 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/12-partial-prerendering.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-partial-prerendering.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何使用部分預渲染 (Partial Prerendering) nav_title: 部分預渲染 description: 了解如何透過部分預渲染 (Partial Prerendering) 結合靜態與動態渲染的優勢。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx similarity index 99% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx index b080aee5..40e70eb2 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/13-metadata-and-og-images.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-metadata-and-og-images.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:26:21.817Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何添加元數據與建立 OG 圖片 nav_title: 元數據與 OG 圖片 description: 了解如何為頁面添加元數據並建立動態 OG 圖片。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-deploying.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-deploying.mdx similarity index 97% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-deploying.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-deploying.mdx index 343a1d43..29492e47 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/14-deploying.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-deploying.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何部署你的 Next.js 應用程式 nav_title: 部署 description: 學習如何部署你的 Next.js 應用程式。 diff --git a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-upgrading.mdx b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/16-upgrading.mdx similarity index 94% rename from apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-upgrading.mdx rename to apps/docs/content/zh-hant/docs/01-app/01-getting-started/16-upgrading.mdx index 0641fd6c..6e1009d7 100644 --- a/apps/docs/content/zh-hant/docs/01-app/01-getting-started/15-upgrading.mdx +++ b/apps/docs/content/zh-hant/docs/01-app/01-getting-started/16-upgrading.mdx @@ -1,6 +1,6 @@ --- -source-updated-at: 2025-06-01T01:32:19.000Z -translation-updated-at: 2025-06-01T01:32:19.000Z +source-updated-at: 2025-06-08T05:18:03.000Z +translation-updated-at: 2025-06-08T05:18:03.000Z title: 如何升級你的 Next.js 應用程式 nav_title: 升級指南 description: 學習如何將你的 Next.js 應用程式升級至最新版本。 diff --git a/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx deleted file mode 100644 index fbfc0609..00000000 --- a/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -source-updated-at: 2025-06-01T01:32:20.000Z -translation-updated-at: 2025-06-01T22:33:47.570Z -title: 連結與導航 -description: 了解 Next.js 中的導航運作方式,以及如何使用 Link 元件和 `useRouter` 鉤子。 -related: - links: - - app/deep-dive/caching - - app/api-reference/config/typescript ---- - -在 Next.js 中有四種方式可以在路由之間進行導航: - -- 使用 [`` 元件](#link-component) -- 使用 [`useRouter` 鉤子](#userouter-hook) ([客戶端元件](/docs/app/getting-started/server-and-client-components)) -- 使用 [`redirect` 函式](#redirect-function) ([伺服器元件](/docs/app/getting-started/server-and-client-components)) -- 使用原生的 [History API](#using-the-native-history-api) - -本頁將介紹如何使用這些選項,並深入探討導航的運作原理。 - -## `` 元件 - -`` 是一個內建元件,它擴展了 HTML 的 `
` 標籤,提供 [預取 (prefetching)](#2-prefetching) 和客戶端路由導航功能。這是 Next.js 中推薦的主要路由導航方式。 - -您可以從 `next/link` 導入它,並向元件傳遞 `href` 屬性: - -```tsx filename="app/page.tsx" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -```jsx filename="app/page.js" switcher -import Link from 'next/link' - -export default function Page() { - return Dashboard -} -``` - -您還可以傳遞其他可選屬性給 ``。詳見 [API 參考文件](/docs/app/api-reference/components/link)。 - -## `useRouter()` 鉤子 - -`useRouter` 鉤子允許您從 [客戶端元件](/docs/app/getting-started/server-and-client-components) 中以程式方式變更路由。 - -```tsx filename="app/page.tsx" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -```jsx filename="app/page.js" switcher -'use client' - -import { useRouter } from 'next/navigation' - -export default function Page() { - const router = useRouter() - - return ( - - ) -} -``` - -完整的 `useRouter` 方法列表,請參閱 [API 參考文件](/docs/app/api-reference/functions/use-router)。 - -> **建議:** 除非有特殊需求需要使用 `useRouter`,否則建議使用 `` 元件進行路由導航。 - -## `redirect` 函式 - -對於 [伺服器元件](/docs/app/getting-started/server-and-client-components),請改用 `redirect` 函式。 - -```tsx filename="app/team/[id]/page.tsx" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id: string) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ - params, -}: { - params: Promise<{ id: string }> -}) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -```jsx filename="app/team/[id]/page.js" switcher -import { redirect } from 'next/navigation' - -async function fetchTeam(id) { - const res = await fetch('https://...') - if (!res.ok) return undefined - return res.json() -} - -export default async function Profile({ params }) { - const { id } = await params - if (!id) { - redirect('/login') - } - - const team = await fetchTeam(id) - if (!team) { - redirect('/join') - } - - // ... -} -``` - -> **重要須知:** -> -> - `redirect` 預設返回 307 (臨時重定向) 狀態碼。在伺服器動作 (Server Action) 中使用時,它會返回 303 (查看其他),這通常用於在 POST 請求後重定向到成功頁面。 -> - `redirect` 內部會拋出錯誤,因此應在 `try/catch` 區塊外呼叫。 -> - `redirect` 可以在客戶端元件的渲染過程中被呼叫,但不能在事件處理程序中呼叫。這種情況下應改用 [`useRouter` 鉤子](#userouter-hook)。 -> - `redirect` 也接受絕對 URL,可用於重定向到外部連結。 -> - 如果您希望在渲染過程之前進行重定向,請使用 [`next.config.js`](/docs/app/guides/redirecting#redirects-in-nextconfigjs) 或 [中介軟體 (Middleware)](/docs/app/guides/redirecting#nextresponseredirect-in-middleware)。 - -更多資訊請參閱 [`redirect` API 參考文件](/docs/app/api-reference/functions/redirect)。 - -## 使用原生 History API - -Next.js 允許您使用原生的 [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) 和 [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) 方法來更新瀏覽器的歷史記錄堆疊,而無需重新載入頁面。 - -`pushState` 和 `replaceState` 的呼叫會與 Next.js 路由器整合,使您可以與 [`usePathname`](/docs/app/api-reference/functions/use-pathname) 和 [`useSearchParams`](/docs/app/api-reference/functions/use-search-params) 同步。 - -### `window.history.pushState` - -用於向瀏覽器的歷史記錄堆疊添加新條目。使用者可以導航回先前的狀態。例如,用於對產品列表進行排序: - -```tsx fileName="app/ui/sort-products.tsx" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder: string) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/sort-products.js" switcher -'use client' - -import { useSearchParams } from 'next/navigation' - -export default function SortProducts() { - const searchParams = useSearchParams() - - function updateSorting(sortOrder) { - const params = new URLSearchParams(searchParams.toString()) - params.set('sort', sortOrder) - window.history.pushState(null, '', `?${params.toString()}`) - } - - return ( - <> - - - - ) -} -``` - -### `window.history.replaceState` - -用於替換瀏覽器歷史記錄堆疊中的當前條目。使用者無法導航回先前的狀態。例如,用於切換應用程式的語言環境: - -```tsx fileName="app/ui/locale-switcher.tsx" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale: string) { - // 例如 '/en/about' 或 '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -```jsx fileName="app/ui/locale-switcher.js" switcher -'use client' - -import { usePathname } from 'next/navigation' - -export function LocaleSwitcher() { - const pathname = usePathname() - - function switchLocale(locale) { - // 例如 '/en/about' 或 '/fr/contact' - const newPath = `/${locale}${pathname}` - window.history.replaceState(null, '', newPath) - } - - return ( - <> - - - - ) -} -``` - -## 路由與導航的運作原理 - -應用程式路由器 (App Router) 使用混合方法來處理路由和導航。在伺服器端,您的應用程式代碼會按路由區段自動進行 [代碼分割 (code-splitting)](#1-code-splitting)。在客戶端,Next.js 會 [預取 (prefetch)](#2-prefetching) 並 [快取 (cache)](#3-caching) 路由區段。這意味著當使用者導航到新路由時,瀏覽器不會重新載入頁面,只有變更的路由區段會重新渲染,從而提升導航體驗和效能。 - -### 1. 代碼分割 (Code Splitting) - -代碼分割允許您將應用程式代碼拆分為較小的套件,供瀏覽器下載和執行。這減少了每次請求傳輸的數據量和執行時間,從而提高效能。 - -[伺服器元件](/docs/app/getting-started/server-and-client-components) 允許您的應用程式代碼按路由區段自動進行代碼分割。這意味著導航時只會載入當前路由所需的代碼。 - -### 2. 預取 (Prefetching) - -預取是一種在使用者訪問路由前,在背景預先載入路由的方式。 - -Next.js 中有兩種預取路由的方式: - -- **`` 元件**:當路由出現在使用者的視野中時,會自動進行預取。預取發生在頁面首次載入或通過滾動進入視野時。 -- **`router.prefetch()`**:可以使用 `useRouter` 鉤子以程式方式預取路由。 - -`` 的預設預取行為(即當 `prefetch` 屬性未指定或設為 `null` 時)會根據您是否使用 [`loading.js`](/docs/app/api-reference/file-conventions/loading) 而有所不同。只有共享的佈局,直到第一個 `loading.js` 檔案為止的元件「樹」會被預取並快取 30 秒。這減少了獲取整個動態路由的成本,意味著您可以顯示 [即時載入狀態](/docs/app/building-your-application/routing/loading-ui-and-streaming#instant-loading-states),為使用者提供更好的視覺反饋。 - -您可以通過將 `prefetch` 屬性設為 `false` 來禁用預取。或者,您可以通過將 `prefetch` 屬性設為 `true` 來預取超出載入邊界的完整頁面數據。 - -更多資訊請參閱 [`` API 參考文件](/docs/app/api-reference/components/link)。 - -> **重要須知:** -> -> - 預取功能在開發環境中不會啟用,僅在生產環境中有效。 - -### 3. 快取 (Caching) - -Next.js 有一個稱為 [路由器快取 (Router Cache)](/docs/app/deep-dive/caching#client-side-router-cache) 的 **記憶體客戶端快取**。當使用者在應用程式中導航時,[預取](#2-prefetching) 的路由區段和已訪問路由的 React 伺服器元件負載 (Payload) 會被儲存在快取中。 - -這意味著在導航時,會盡可能重用快取,而不是向伺服器發送新請求,從而通過減少請求和傳輸的數據量來提高效能。 - -了解更多關於 [路由器快取](/docs/app/deep-dive/caching#client-side-router-cache) 的運作方式和如何配置它。 - -### 4. 部分渲染 (Partial Rendering) - -部分渲染意味著在導航時,只有變更的路由區段會在客戶端重新渲染,任何共享的區段都會被保留。 - -例如,在導航兩個兄弟路由 `/dashboard/settings` 和 `/dashboard/analytics` 之間時,`settings` 頁面會被卸載,`analytics` 頁面會以新狀態掛載,而共享的 `dashboard` 佈局會被保留。這種行為也存在於同一動態區段的兩個路由之間,例如 `/blog/[slug]/page` 和從 `/blog/first` 導航到 `/blog/second`。 - -部分渲染的運作方式 - -如果沒有部分渲染,每次導航都會導致整個頁面在客戶端重新渲染。只渲染變更的區段減少了傳輸的數據量和執行時間,從而提高效能。 - -### 5. 軟導航 (Soft Navigation) - -瀏覽器在頁面之間導航時會執行「硬導航」。Next.js 應用程式路由器實現了頁面之間的「軟導航」,確保只有變更的路由區段會重新渲染(部分渲染)。這使得客戶端 React 狀態在導航期間得以保留。 - -### 6. 前進和後退導航 - -預設情況下,Next.js 會為前進和後退導航保持滾動位置,並重用 [路由器快取](/docs/app/deep-dive/caching#client-side-router-cache) 中的路由區段。 - -### 7. `pages/` 和 `app/` 之間的路由 - -當從 `pages/` 逐步遷移到 `app/` 時,Next.js 路由器會自動處理兩者之間的硬導航。為了檢測從 `pages/` 到 `app/` 的轉換,有一個客戶端路由器過濾器會利用應用路由的機率性檢查,這偶爾會導致誤判。預設情況下,這種情況應該非常罕見,因為我們將誤判機率配置為 0.01%。這個機率可以通過 `next.config.js` 中的 `experimental.clientRouterFilterAllowedRate` 選項進行自訂。需要注意的是,降低誤判率會增加客戶端套件中生成的過濾器的大小。 - -或者,如果您希望完全禁用此處理並手動管理 `pages/` 和 `app/` 之間的路由,可以在 `next.config.js` 中將 `experimental.clientRouterFilter` 設為 false。當此功能被禁用時,任何與應用路由重疊的頁面動態路由預設將無法正確導航。 \ No newline at end of file diff --git a/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx b/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx deleted file mode 100644 index bdf9ecff..00000000 --- a/apps/docs/content/zh-hant/docs/01-app/03-building-your-application/01-routing/06-loading-ui-and-streaming.mdx +++ /dev/null @@ -1,198 +0,0 @@ ---- -source-updated-at: 2025-05-16T04:52:11.000Z -translation-updated-at: 2025-05-25T21:00:51.069Z -title: 載入 UI 與串流 -description: 基於 Suspense 構建的載入 UI 可讓您為特定路由區段建立備用內容,並在內容準備就緒時自動串流傳輸。 - ---- - -特殊檔案 `loading.js` 可協助您使用 [React Suspense](https://react.dev/reference/react/Suspense) 建立有意義的載入 UI。透過此約定,您可以在路由區段內容載入時,從伺服器顯示 [即時載入狀態](#instant-loading-states)。一旦渲染完成,新內容會自動替換顯示。 - -載入 UI - -## 即時載入狀態 - -即時載入狀態是在導航時立即顯示的備用 UI。您可以預先渲染載入指示器,例如骨架屏和旋轉圖示,或是未來畫面的小部分但有意義的內容,例如封面圖片、標題等。這有助於使用者理解應用程式正在回應,並提供更好的使用者體驗。 - -透過在資料夾內新增 `loading.js` 檔案來建立載入狀態。 - -loading.js 特殊檔案 - -```tsx filename="app/dashboard/loading.tsx" switcher -export default function Loading() { - // 您可以在 Loading 內新增任何 UI,包括骨架屏。 - return -} -``` - -```jsx filename="app/dashboard/loading.js" switcher -export default function Loading() { - // 您可以在 Loading 內新增任何 UI,包括骨架屏。 - return -} -``` - -在同一個資料夾中,`loading.js` 會嵌套在 `layout.js` 內。它會自動將 `page.js` 檔案及其下方的任何子項目包裹在 `` 邊界中。 - -loading.js 概覽 - -> **須知事項**: -> -> - 導航是即時的,即使使用 [以伺服器為中心的路由](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works)。 -> - 導航是可中斷的,這表示變更路由時無需等待路由內容完全載入即可導航至其他路由。 -> - 共享佈局在新路由區段載入時仍保持互動性。 - -> **建議:** 為路由區段(佈局和頁面)使用 `loading.js` 約定,因為 Next.js 會優化此功能。 - -## 使用 Suspense 串流 - -除了 `loading.js`,您也可以手動為自己的 UI 元件建立 Suspense 邊界。App Router 支援使用 [Suspense](https://react.dev/reference/react/Suspense) 進行串流。 - -> **須知事項**: -> -> - [某些瀏覽器](https://bugs.webkit.org/show_bug.cgi?id=252413) 會緩衝串流回應。在回應超過 1024 位元組之前,您可能看不到串流回應。這通常僅影響「hello world」應用程式,而不影響實際應用程式。 - -### 什麼是串流? - -要了解串流在 React 和 Next.js 中的運作方式,有助於理解 **伺服器端渲染 (SSR)** 及其限制。 - -使用 SSR 時,在使用者可以看到並與頁面互動之前,需要完成一系列步驟: - -1. 首先,在伺服器上擷取給定頁面的所有資料。 -2. 接著,伺服器渲染頁面的 HTML。 -3. 頁面的 HTML、CSS 和 JavaScript 會傳送至客戶端。 -4. 使用生成的 HTML 和 CSS 顯示非互動式使用者介面。 -5. 最後,React [水合 (hydrate)](https://react.dev/reference/react-dom/client/hydrateRoot#hydrating-server-rendered-html) 使用者介面以使其可互動。 - -圖表顯示無串流的伺服器渲染 - -這些步驟是順序且阻塞的,這表示伺服器只能在所有資料擷取完成後才能渲染頁面的 HTML。並且,在客戶端上,React 只有在頁面中所有元件的程式碼都已下載後才能水合 UI。 - -使用 React 和 Next.js 的 SSR 有助於透過盡快向使用者顯示非互動式頁面來改善感知載入效能。 - -無串流的伺服器渲染 - -然而,由於在伺服器上擷取所有資料需要完成後才能向使用者顯示頁面,因此仍然可能很慢。 - -**串流** 允許您將頁面的 HTML 分解為較小的區塊,並逐步將這些區塊從伺服器傳送至客戶端。 - -帶串流的伺服器渲染運作方式 - -這使得頁面的部分內容可以更快顯示,而無需等待所有資料載入後才能渲染任何 UI。 - -串流與 React 的元件模型配合良好,因為每個元件可以被視為一個區塊。具有較高優先級(例如產品資訊)或不依賴資料的元件(例如佈局)可以先傳送,React 可以更早開始水合。具有較低優先級的元件(例如評論、相關產品)可以在其資料擷取完成後,在同一個伺服器請求中傳送。 - -圖表顯示帶串流的伺服器渲染 - -當您希望防止長時間的資料請求阻擋頁面渲染時,串流特別有益,因為它可以減少 [首次位元組時間 (TTFB)](https://web.dev/ttfb/) 和 [首次內容繪製 (FCP)](https://web.dev/first-contentful-paint/)。它還有助於改善 [互動時間 (TTI)](https://developer.chrome.com/en/docs/lighthouse/performance/interactive/),特別是在較慢的裝置上。 - -### 範例 - -`` 的運作方式是包裹執行非同步動作(例如擷取資料)的元件,在動作進行時顯示備用 UI(例如骨架屏、旋轉圖示),並在動作完成後替換為您的元件。 - -```tsx filename="app/dashboard/page.tsx" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- 載入動態消息中...

}> - -
- 載入天氣資訊中...

}> - -
-
- ) -} -``` - -```jsx filename="app/dashboard/page.js" switcher -import { Suspense } from 'react' -import { PostFeed, Weather } from './Components' - -export default function Posts() { - return ( -
- 載入動態消息中...

}> - -
- 載入天氣資訊中...

}> - -
-
- ) -} -``` - -透過使用 Suspense,您可以獲得以下好處: - -1. **串流伺服器渲染** - 從伺服器逐步渲染 HTML 至客戶端。 -2. **選擇性水合** - React 會根據使用者互動優先處理哪些元件先進行互動。 - -有關 Suspense 的更多範例和使用案例,請參閱 [React 文件](https://react.dev/reference/react/Suspense)。 - -### SEO - -- Next.js 會在將 UI 串流至客戶端之前,等待 [`generateMetadata`](/docs/app/api-reference/functions/generate-metadata) 內的資料擷取完成。這保證串流回應的第一部分包含 `` 標籤。 -- 由於串流是伺服器渲染的,因此不會影響 SEO。您可以使用 Google 的 [Rich Results Test](https://search.google.com/test/rich-results) 工具來查看您的頁面在 Google 網路爬蟲中的顯示方式,並查看序列化的 HTML ([來源](https://web.dev/rendering-on-the-web/#seo-considerations))。 - -### 狀態碼 - -串流時,將返回 `200` 狀態碼以表示請求成功。 - -伺服器仍可以在串流內容本身中向客戶端傳達錯誤或問題,例如使用 [`redirect`](/docs/app/api-reference/functions/redirect) 或 [`notFound`](/docs/app/api-reference/functions/not-found) 時。由於回應標頭已傳送至客戶端,因此無法更新回應的狀態碼。這不會影響 SEO。 - -## 平台支援 - -| 部署選項 | 支援情況 | -| ------------------------------------------------------------------- | ----------------- | -| [Node.js 伺服器](/docs/app/getting-started/deploying#nodejs-server) | 是 | -| [Docker 容器](/docs/app/getting-started/deploying#docker) | 是 | -| [靜態匯出](/docs/app/getting-started/deploying#static-export) | 否 | -| [轉接器](/docs/app/getting-started/deploying#adapters) | 依平台而定 | - -了解如何在自行託管 Next.js 時 [設定串流](/docs/app/guides/self-hosting#streaming-and-suspense)。 \ No newline at end of file