@nuxt/docs-nightly 5.0.0-29556898.efe4498a → 5.0.0-29558424.9dad7f28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,6 +62,7 @@ When you set your `future.compatibilityVersion` to `5`, defaults throughout your
62
62
  - **Normalized Page Names**: Page component names will [match their route names](/docs/4.x/getting-started/upgrade#normalized-page-component-names) for consistent `<KeepAlive>` behavior
63
63
  - **`clearNuxtState` resets to defaults**: `clearNuxtState` will [reset state to its initial value](/docs/4.x/getting-started/upgrade#respect-defaults-when-clearing-usestate) instead of setting it to `undefined`
64
64
  - **Non-async `callHook`**: [`callHook` may return `void`](/docs/4.x/getting-started/upgrade#non-async-callhook) instead of always returning a `Promise`
65
+ - **Comment node placeholders**: Client-only components use [comment nodes instead of `<div>`](/docs/4.x/getting-started/upgrade#client-only-comment-placeholders) as SSR placeholders, fixing a scoped styles hydration issue
65
66
  - Other Nuxt 5 improvements and changes as they become available
66
67
 
67
68
  ::note
@@ -410,1297 +411,42 @@ export default defineNuxtConfig({
410
411
  })
411
412
  ```
412
413
 
413
- ## Migrating to Nuxt 4
414
-
415
- Nuxt 4 includes significant improvements and changes. This guide will help you migrate your existing Nuxt 3 application to Nuxt 4.
416
-
417
- First, upgrade to Nuxt 4:
418
-
419
- ::code-group{sync="pm"}
420
-
421
- ```bash [npm]
422
- npm install nuxt@^4.0.0
423
- ```
424
-
425
- ```bash [yarn]
426
- yarn add nuxt@^4.0.0
427
- ```
428
-
429
- ```bash [pnpm]
430
- pnpm add nuxt@^4.0.0
431
- ```
432
-
433
- ```bash [bun]
434
- bun add nuxt@^4.0.0
435
- ```
436
-
437
- ```bash [deno]
438
- deno add npm:nuxt@^4.0.0
439
- ```
440
-
441
- ::
442
-
443
- After upgrading, most Nuxt 4 behaviors are now the default. However, some features can still be configured if you need to maintain backward compatibility during your migration.
444
-
445
- The following sections detail the key changes and migrations needed when upgrading to Nuxt 4.
446
-
447
- Breaking or significant changes are documented below along with migration steps and available configuration options.
448
-
449
- ### Migrating Using Codemods
450
-
451
- To facilitate the upgrade process, we have collaborated with the [Codemod](https://github.com/codemod/codemod) team to automate many migration steps with some open-source codemods.
452
-
453
- ::note
454
- If you encounter any issues, please report them to the Codemod team with `npx codemod feedback` 🙏
455
- ::
456
-
457
- For a complete list of Nuxt 4 codemods, detailed information on each, their source, and various ways to run them, visit the [Codemod Registry](https://app.codemod.com/registry).
458
-
459
- You can run all the codemods mentioned in this guide using the following `codemod` recipe:
460
-
461
- ::code-group
462
-
463
- ```bash [npm]
464
- # Using pinned version due to https://github.com/codemod/codemod/issues/1710
465
- npx codemod@0.18.7 nuxt/4/migration-recipe
466
- ```
467
-
468
- ```bash [yarn]
469
- # Using pinned version due to https://github.com/codemod/codemod/issues/1710
470
- yarn dlx codemod@0.18.7 nuxt/4/migration-recipe
471
- ```
472
-
473
- ```bash [pnpm]
474
- # Using pinned version due to https://github.com/codemod/codemod/issues/1710
475
- pnpm dlx codemod@0.18.7 nuxt/4/migration-recipe
476
- ```
477
-
478
- ```bash [bun]
479
- # Using pinned version due to https://github.com/codemod/codemod/issues/1710
480
- bun x codemod@0.18.7 nuxt/4/migration-recipe
481
- ```
482
-
483
- ```bash [deno]
484
- # Using pinned version due to https://github.com/codemod/codemod/issues/1710
485
- deno x codemod@0.18.7 nuxt/4/migration-recipe
486
- ```
487
-
488
- ::
489
-
490
- This command will execute all codemods in sequence, with the option to deselect any that you do not wish to run. Each codemod is also listed below alongside its respective change and can be executed independently.
491
-
492
- ### New Directory Structure
493
-
494
- 🚦 **Impact Level**: Significant
495
-
496
- Nuxt now defaults to a new directory structure, with backwards compatibility (so if Nuxt detects you are using the old structure, such as with a top-level `app/pages/` directory, this new structure will not apply).
497
-
498
- 👉 [See full RFC](https://github.com/nuxt/nuxt/issues/26444)
499
-
500
- #### What Changed
501
-
502
- - the new Nuxt default `srcDir` is `app/` by default, and most things are resolved from there.
503
- - `serverDir` now defaults to `<rootDir>/server` rather than `<srcDir>/server`
504
- - `layers/`, `modules/` and `public/` are resolved relative to `<rootDir>` by default
505
- - if using [Nuxt Content v2.13+](https://github.com/nuxt/content/pull/2649), `content/` is resolved relative to `<rootDir>`
506
- - a new `dir.app` is added, which is the directory we look for `router.options.ts` and `spa-loading-template.html` - this defaults to `<srcDir>/`
507
- - a new [`shared/`](/docs/4.x/directory-structure/shared) directory is available for code shared between the Vue app and the Nitro server, with auto-imports for `shared/utils/` and `shared/types/`
508
-
509
- <details>
510
-
511
- <summary>An example v4 folder structure.</summary>
512
-
513
- ```sh
514
- .output/
515
- .nuxt/
516
- app/
517
- assets/
518
- components/
519
- composables/
520
- layouts/
521
- middleware/
522
- pages/
523
- plugins/
524
- utils/
525
- app.config.ts
526
- app.vue
527
- router.options.ts
528
- content/
529
- layers/
530
- modules/
531
- node_modules/
532
- public/
533
- shared/
534
- types/
535
- utils/
536
- server/
537
- api/
538
- middleware/
539
- plugins/
540
- routes/
541
- utils/
542
- nuxt.config.ts
543
- ```
544
-
545
- ::note
546
- With this new structure, the `~` alias now points to the `app/` directory by default (your `srcDir`). This means `~/components` resolves to `app/components/`, `~/pages` to `app/pages/`, etc.
547
- ::
548
-
549
- </details>
550
-
551
- 👉 For more details, see the [PR implementing this change](https://github.com/nuxt/nuxt/pull/27029).
552
-
553
- #### Reasons for Change
554
-
555
- 1. **Performance** - placing all your code in the root of your repo causes issues with `.git/` and `node_modules/` folders being scanned/included by FS watchers which can significantly delay startup on non-Mac OSes.
556
- 1. **IDE type-safety** - `server/` and the rest of your app are running in two entirely different contexts with different global imports available, and making sure `server/` isn't _inside_ the same folder as the rest of your app is a big first step to ensuring you get good auto-completes in your IDE.
557
-
558
- :video-accordion{title="Watch a video from Vue School on the new directory structure" videoId="1031028378" platform="vimeo"}
559
-
560
- #### Migration Steps
561
-
562
- 1. Create a new directory called `app/`.
563
- 1. Move your `assets/`, `components/`, `composables/`, `app/layouts/`, `app/middleware/`, `app/pages/`, `app/plugins/` and `utils/` folders under it, as well as `app.vue`, `error.vue`, `app.config.ts`. If you have an `app/router-options.ts` or `app/spa-loading-template.html`, these paths remain the same.
564
- 1. Make sure your `nuxt.config.ts`, `content/`, `layers/`, `modules/`, `public/`, `shared/` and `server/` folders remain outside the `app/` folder, in the root of your project.
565
- 1. Remember to update any third-party configuration files to work with the new directory structure, such as your `tailwindcss` or `eslint` configuration (if required - `@nuxtjs/tailwindcss` should automatically configure `tailwindcss` correctly).
566
-
567
- ::tip
568
- You can automate this migration by running `npx codemod@latest nuxt/4/file-structure`
569
- ::
570
-
571
- However, migration is _not required_. If you wish to keep your current folder structure, Nuxt should auto-detect it. (If it does not, please raise an issue.) The one exception is that if you _already_ have a custom `srcDir`. In this case, you should be aware that your `modules/`, `public/`, `shared/` and `server/` folders will be resolved from your `rootDir` rather than from your custom `srcDir`. You can override this by configuring `dir.modules`, `dir.public` and `serverDir` if you need to.
572
-
573
- You can also force a v3 folder structure with the following configuration:
574
-
575
- ```ts [nuxt.config.ts]
576
- export default defineNuxtConfig({
577
- // This reverts the new srcDir default from `app` back to your root directory
578
- srcDir: '.',
579
- // This specifies the directory prefix for `router.options.ts` and `spa-loading-template.html`
580
- dir: {
581
- app: 'app',
582
- },
583
- })
584
- ```
585
-
586
- ### Singleton Data Fetching Layer
587
-
588
- 🚦 **Impact Level**: Moderate
589
-
590
- #### What Changed
591
-
592
- Nuxt's data fetching system (`useAsyncData` and `useFetch`) has been significantly reorganized for better performance and consistency:
593
-
594
- 1. **Shared refs for the same key**: All calls to `useAsyncData` or `useFetch` with the same key now share the same `data`, `error` and `status` refs. This means that it is important that all calls with an explicit key must not have conflicting `deep`, `transform`, `pick`, `getCachedData` or `default` options.
595
-
596
- 2. **More control over `getCachedData`**: The `getCachedData` function is now called every time data is fetched, even if this is caused by a watcher or calling `refreshNuxtData`. (Previously, new data was always fetched and this function was not called in these cases.) To allow more control over when to use cached data and when to refetch, the function now receives a context object with the cause of the request.
597
-
598
- 3. **Reactive key support**: You can now use computed refs, plain refs or getter functions as keys, which enables automatic data refetching (and stores data separately).
599
-
600
- 4. **Data cleanup**: When the last component using data fetched with `useAsyncData` is unmounted, Nuxt will remove that data to avoid ever-growing memory usage.
601
-
602
- #### Reasons for Change
603
-
604
- These changes have been made to improve memory usage and increase consistency with loading states across calls of `useAsyncData`.
605
-
606
- #### Migration Steps
607
-
608
- 1. **Check for inconsistent options**: Review any components using the same key with different options or fetch functions.
609
-
610
- ```ts
611
- // This will now trigger a warning
612
- const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { deep: false })
613
- const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { deep: true })
614
- ```
615
-
616
- It may be beneficial to extract any calls to `useAsyncData` that share an explicit key (and have custom options) into their own composable:
617
-
618
- ```ts [app/composables/useUserData.ts]
619
- export function useUserData (userId: string) {
620
- return useAsyncData(
621
- `user-${userId}`,
622
- () => fetchUser(userId),
623
- {
624
- deep: true,
625
- transform: user => ({ ...user, lastAccessed: new Date() }),
626
- },
627
- )
628
- }
629
- ```
630
-
631
- 2. **Update `getCachedData` implementations**:
632
-
633
- ```diff
634
- useAsyncData('key', fetchFunction, {
635
- - getCachedData: (key, nuxtApp) => {
636
- - return cachedData[key]
637
- - }
638
- + getCachedData: (key, nuxtApp, ctx) => {
639
- + // ctx.cause - can be 'initial' | 'refresh:hook' | 'refresh:manual' | 'watch'
640
- +
641
- + // Example: Don't use cache on manual refresh
642
- + if (ctx.cause === 'refresh:manual') return undefined
643
- +
644
- + return cachedData[key]
645
- + }
646
- })
647
- ```
648
-
649
- Alternatively, for now, you can disable this behaviour with:
650
-
651
- ```ts twoslash [nuxt.config.ts]
652
- export default defineNuxtConfig({
653
- experimental: {
654
- granularCachedData: false,
655
- purgeCachedData: false,
656
- },
657
- })
658
- ```
659
-
660
- ### Corrected Module Loading Order in Layers
661
-
662
- 🚦 **Impact Level**: Minimal
663
-
664
- #### What Changed
665
-
666
- The order in which modules are loaded when using [Nuxt layers](/docs/4.x/guide/going-further/layers) has been corrected. Previously, modules from the project root were loaded before modules from extended layers, which was the reverse of the expected behavior.
667
-
668
- Now modules are loaded in the correct order:
669
-
670
- 1. **Layer modules first** (in extend order - deeper layers first)
671
- 2. **Project modules last** (highest priority)
672
-
673
- This affects both:
674
- - Modules defined in the `modules` array in `nuxt.config.ts`
675
- - Auto-discovered modules from the `modules/` directory
676
-
677
- #### Reasons for Change
678
-
679
- This change ensures that:
680
- - Extended layers have lower priority than the consuming project
681
- - Module execution order matches the intuitive layer inheritance pattern
682
- - Module configuration and hooks work as expected in multi-layer setups
683
-
684
- #### Migration Steps
685
-
686
- **Most projects will not need changes**, as this corrects the loading order to match expected behavior.
687
-
688
- However, if your project was relying on the previous incorrect order, you may need to:
689
-
690
- 1. **Review module dependencies**: Check if any modules depend on specific loading order
691
- 2. **Adjust module configuration**: If modules were configured to work around the incorrect order
692
- 3. **Test thoroughly**: Ensure all functionality works as expected with the corrected order
693
-
694
- Example of the new correct order:
695
- ```ts
696
- // Layer: my-layer/nuxt.config.ts
697
- export default defineNuxtConfig({
698
- modules: ['layer-module-1', 'layer-module-2'],
699
- })
700
-
701
- // Project: nuxt.config.ts
702
- export default defineNuxtConfig({
703
- extends: ['./my-layer'],
704
- modules: ['project-module-1', 'project-module-2'],
705
- })
706
-
707
- // Loading order (corrected):
708
- // 1. layer-module-1
709
- // 2. layer-module-2
710
- // 3. project-module-1 (can override layer modules)
711
- // 4. project-module-2 (can override layer modules)
712
- ```
713
-
714
- If you encounter issues with module order dependencies due to needing to register a hook, consider using the [`modules:done` hook](/docs/4.x/guide/modules/recipes-advanced) for modules that need to call a hook. This is run after all other modules have been loaded, which means it is safe to use.
715
-
716
- 👉 See [PR #31507](https://github.com/nuxt/nuxt/pull/31507) and [issue #25719](https://github.com/nuxt/nuxt/issues/25719) for more details.
717
-
718
- ### Deduplication of Route Metadata
719
-
720
- 🚦 **Impact Level**: Minimal
721
-
722
- #### What Changed
723
-
724
- It's possible to set some route metadata using `definePageMeta`, such as the `name`, `path`, and so on. Previously these were available both on the route and on route metadata (for example, `route.name` and `route.meta.name`).
725
-
726
- Now, they are only accessible on the route object.
727
-
728
- #### Reasons for Change
729
-
730
- This is a result of enabling `experimental.scanPageMeta` by default, and is a performance optimization.
731
-
732
- #### Migration Steps
733
-
734
- The migration should be straightforward:
735
-
736
- ```diff
737
- const route = useRoute()
738
-
739
- - console.log(route.meta.name)
740
- + console.log(route.name)
741
- ```
742
-
743
- ### Normalized Component Names
744
-
745
- 🚦 **Impact Level**: Moderate
746
-
747
- Vue will now generate component names that match the Nuxt pattern for component naming.
748
-
749
- #### What Changed
750
-
751
- By default, if you haven't set it manually, Vue will assign a component name that matches
752
- the filename of the component.
753
-
754
- ```bash [Directory structure]
755
- ├─ components/
756
- ├─── SomeFolder/
757
- ├───── MyComponent.vue
758
- ```
759
-
760
- In this case, the component name would be `MyComponent`, as far as Vue is concerned. If you wanted to use `<KeepAlive>` with it, or identify it in the Vue DevTools, you would need to use this name.
761
-
762
- But in order to auto-import it, you would need to use `SomeFolderMyComponent`.
763
-
764
- With this change, these two values will match, and Vue will generate a component name that matches the Nuxt pattern for component naming.
765
-
766
- #### Migration Steps
767
-
768
- Ensure that you use the updated name in any tests which use `findComponent` from `@vue/test-utils` and in any `<KeepAlive>` which depends on the name of your component.
769
-
770
- Alternatively, for now, you can disable this behaviour with:
771
-
772
- ```ts twoslash [nuxt.config.ts]
773
- export default defineNuxtConfig({
774
- experimental: {
775
- normalizeComponentNames: false,
776
- },
777
- })
778
- ```
779
-
780
- ### Unhead v2
781
-
782
- 🚦 **Impact Level**: Minimal
783
-
784
- #### What Changed
785
-
786
- [Unhead](https://unhead.unjs.io/), used to generate `<head>` tags, has been updated to version 2. While mostly compatible it includes several breaking changes
787
- for lower-level APIs.
788
-
789
- - Removed props: `vmid`, `hid`, `children`, `body`.
790
- - Promise input no longer supported.
791
- - Tags are now sorted using Capo.js by default.
792
-
793
- #### Migration Steps
794
-
795
- The above changes should have minimal impact on your app.
796
-
797
- If you have issues you should verify:
798
-
799
- - You're not using any of the removed props.
800
-
801
- ```diff
802
- useHead({
803
- meta: [{
804
- name: 'description',
805
- // meta tags don't need a vmid, or a key
806
- - vmid: 'description'
807
- - hid: 'description'
808
- }]
809
- })
810
- ```
811
-
812
- - If you're using [Template Params](https://unhead.unjs.io/docs/head/guides/plugins/template-params) or [Alias Tag Sorting](https://unhead.unjs.io/docs/head/guides/plugins/alias-sorting), you will need to explicitly opt in to these features now.
813
-
814
- ```ts
815
- import { AliasSortingPlugin, TemplateParamsPlugin } from '@unhead/vue/plugins'
816
-
817
- export default defineNuxtPlugin({
818
- setup () {
819
- const unhead = injectHead()
820
- unhead.use(TemplateParamsPlugin)
821
- unhead.use(AliasSortingPlugin)
822
- },
823
- })
824
- ```
825
-
826
- While not required it's recommended to update any imports from `@unhead/vue` to `#imports` or `nuxt/app`.
827
-
828
- ```diff
829
- -import { useHead } from '@unhead/vue'
830
- +import { useHead } from '#imports'
831
- ```
832
-
833
- If you still have issues you may revert to the v1 behavior by enabling the `head.legacy` config.
834
-
835
- ```ts
836
- export default defineNuxtConfig({
837
- unhead: {
838
- legacy: true,
839
- },
840
- })
841
- ```
842
-
843
- ### New DOM Location for SPA Loading Screen
844
-
845
- 🚦 **Impact Level**: Minimal
846
-
847
- #### What Changed
848
-
849
- When rendering a client-only page (with `ssr: false`), we optionally render a loading screen (from `~/app/spa-loading-template.html` - note that this has also changed to `~/spa-loading-template.html` in Nuxt 4), within the Nuxt app root:
850
-
851
- ```html
852
- <div id="__nuxt">
853
- <!-- spa loading template -->
854
- </div>
855
- ```
856
-
857
- Now, we default to rendering the template alongside the Nuxt app root:
858
-
859
- ```html
860
- <div id="__nuxt"></div>
861
- <!-- spa loading template -->
862
- ```
863
-
864
- #### Reasons for Change
865
-
866
- This allows the spa loading template to remain in the DOM until the Vue app suspense resolves, preventing a flash of white.
867
-
868
- #### Migration Steps
869
-
870
- If you were targeting the spa loading template with CSS or `document.queryElement` you will need to update your selectors. For this purpose you can use the new `app.spaLoaderTag` and `app.spaLoaderAttrs` configuration options.
871
-
872
- Alternatively, you can revert to the previous behaviour with:
873
-
874
- ```ts twoslash [nuxt.config.ts]
875
- export default defineNuxtConfig({
876
- experimental: {
877
- spaLoadingTemplateLocation: 'within',
878
- },
879
- })
880
- ```
881
-
882
- ### Parsed `error.data`
883
-
884
- 🚦 **Impact Level**: Minimal
885
-
886
- It was possible to throw an error with a `data` property, but this was not parsed. Now, it is parsed and made available in the `error` object. Although a fix, this is technically a breaking change if you were relying on the previous behavior and parsing it manually.
887
-
888
- #### Migration Steps
889
-
890
- Update your custom `error.vue` to remove any additional parsing of `error.data`:
891
-
892
- ```diff
893
- <script setup lang="ts">
894
- import type { NuxtError } from '#app'
895
-
896
- const props = defineProps({
897
- error: Object as () => NuxtError
898
- })
899
-
900
- - const data = JSON.parse(error.data)
901
- + const data = error.data
902
- </script>
903
- ```
904
-
905
- ### More Granular Inline Styles
906
-
907
- 🚦 **Impact Level**: Moderate
908
-
909
- Nuxt will now only inline styles for Vue components, not global CSS.
910
-
911
- #### What Changed
912
-
913
- Previously, Nuxt would inline all CSS, including global styles, and remove `<link>` elements to separate CSS files. Now, Nuxt will only do this for Vue components (which previously produced separate chunks of CSS). We think this is a better balance of reducing separate network requests (just as before, there will not be separate requests for individual `.css` files per-page or per-component on the initial load), as well as allowing caching of a single global CSS file and reducing the document download size of the initial request.
914
-
915
- #### Migration Steps
916
-
917
- This feature is fully configurable and you can revert to the previous behavior by setting `inlineStyles: true` to inline global CSS as well as per-component CSS.
918
-
919
- ```ts twoslash [nuxt.config.ts]
920
- export default defineNuxtConfig({
921
- features: {
922
- inlineStyles: true,
923
- },
924
- })
925
- ```
926
-
927
- ### Scan Page Meta After Resolution
928
-
929
- 🚦 **Impact Level**: Minimal
930
-
931
- #### What Changed
932
-
933
- We now scan page metadata (defined in `definePageMeta`) _after_ calling the `pages:extend` hook rather than before.
934
-
935
- #### Reasons for Change
936
-
937
- This was to allow scanning metadata for pages that users wanted to add in `pages:extend`. We still offer an opportunity to change or override page metadata in a new `pages:resolved` hook.
938
-
939
- #### Migration Steps
940
-
941
- If you want to override page metadata, do that in `pages:resolved` rather than in `pages:extend`.
942
-
943
- ```diff
944
- export default defineNuxtConfig({
945
- hooks: {
946
- - 'pages:extend'(pages) {
947
- + 'pages:resolved'(pages) {
948
- const myPage = pages.find(page => page.path === '/')
949
- myPage.meta ||= {}
950
- myPage.meta.layout = 'overridden-layout'
951
- }
952
- }
953
- })
954
- ```
955
-
956
- Alternatively, you can revert to the previous behaviour with:
957
-
958
- ```ts twoslash [nuxt.config.ts]
959
- export default defineNuxtConfig({
960
- experimental: {
961
- scanPageMeta: true,
962
- },
963
- })
964
- ```
965
-
966
- ### Shared Prerender Data
967
-
968
- 🚦 **Impact Level**: Medium
969
-
970
- #### What Changed
971
-
972
- We enabled a previously experimental feature to share data from `useAsyncData` and `useFetch` calls, across different pages. See [original PR](https://github.com/nuxt/nuxt/pull/24894).
973
-
974
- #### Reasons for Change
975
-
976
- This feature automatically shares payload _data_ between pages that are prerendered. This can result in a significant performance improvement when prerendering sites that use `useAsyncData` or `useFetch` and fetch the same data in different pages.
977
-
978
- For example, if your site requires a `useFetch` call for every page (for example, to get navigation data for a menu, or site settings from a CMS), this data would only be fetched once when prerendering the first page that uses it, and then cached for use when prerendering other pages.
979
-
980
- #### Migration Steps
981
-
982
- Make sure that any unique key of your data is always resolvable to the same data. For example, if you are using `useAsyncData` to fetch data related to a particular page, you should provide a key that uniquely matches that data. (`useFetch` should do this automatically for you.)
983
-
984
- ```ts [app/pages/test/[slug\\].vue]
985
- // This would be unsafe in a dynamic page (e.g. `[slug].vue`) because the route slug makes a difference
986
- // to the data fetched, but Nuxt can't know that because it's not reflected in the key.
987
- const route = useRoute()
988
- const { data } = await useAsyncData(async () => {
989
- return await $fetch(`/api/my-page/${route.params.slug}`)
990
- })
991
- // Instead, you should use a key that uniquely identifies the data fetched.
992
- const { data } = await useAsyncData(route.params.slug, async () => {
993
- return await $fetch(`/api/my-page/${route.params.slug}`)
994
- })
995
- ```
996
-
997
- Alternatively, you can disable this feature with:
998
-
999
- ```ts twoslash [nuxt.config.ts]
1000
- export default defineNuxtConfig({
1001
- experimental: {
1002
- sharedPrerenderData: false,
1003
- },
1004
- })
1005
- ```
1006
-
1007
- ### Default `data` and `error` values in `useAsyncData` and `useFetch`
1008
-
1009
- 🚦 **Impact Level**: Minimal
1010
-
1011
- #### What Changed
1012
-
1013
- `data` and `error` objects returned from `useAsyncData` will now default to `undefined`.
1014
-
1015
- #### Reasons for Change
1016
-
1017
- Previously `data` was initialized to `null` but reset in `clearNuxtData` to `undefined`. `error` was initialized to `null`. This change is to bring greater consistency.
1018
-
1019
- #### Migration Steps
1020
-
1021
- If you were checking if `data.value` or `error.value` were `null`, you can update these checks to check for `undefined` instead.
1022
-
1023
- ::tip
1024
- You can automate this step by running `npx codemod@latest nuxt/4/default-data-error-value`
1025
- ::
1026
-
1027
- ### Removal of deprecated `boolean` values for `dedupe` option when calling `refresh` in `useAsyncData` and `useFetch`
1028
-
1029
- 🚦 **Impact Level**: Minimal
1030
-
1031
- #### What Changed
1032
-
1033
- Previously it was possible to pass `dedupe: boolean` to `refresh`. These were aliases of `cancel` (`true`) and `defer` (`false`).
1034
-
1035
- ```ts twoslash [app/app.vue]
1036
- // @errors: 2322
1037
- const { refresh } = await useAsyncData(() => Promise.resolve({ message: 'Hello, Nuxt!' }))
1038
-
1039
- async function refreshData () {
1040
- await refresh({ dedupe: true })
1041
- }
1042
- ```
1043
-
1044
- #### Reasons for Change
1045
-
1046
- These aliases were removed, for greater clarity.
1047
-
1048
- The issue came up when adding `dedupe` as an option to `useAsyncData`, and we removed the boolean values as they ended up being _opposites_.
1049
-
1050
- `refresh({ dedupe: false })` meant **do not _cancel_ existing requests in favour of this new one**. But passing `dedupe: true` within the options of `useAsyncData` means **do not make any new requests if there is an existing pending request.** (See [PR](https://github.com/nuxt/nuxt/pull/24564#pullrequestreview-1764584361).)
1051
-
1052
- #### Migration Steps
1053
-
1054
- The migration should be straightforward:
1055
-
1056
- ```diff
1057
- const { refresh } = await useAsyncData(async () => ({ message: 'Hello, Nuxt 3!' }))
1058
-
1059
- async function refreshData () {
1060
- - await refresh({ dedupe: true })
1061
- + await refresh({ dedupe: 'cancel' })
1062
-
1063
- - await refresh({ dedupe: false })
1064
- + await refresh({ dedupe: 'defer' })
1065
- }
1066
- ```
1067
-
1068
- ::tip
1069
- You can automate this step by running `npx codemod@latest nuxt/4/deprecated-dedupe-value`
1070
- ::
1071
-
1072
- ### Respect defaults when clearing `data` in `useAsyncData` and `useFetch`
1073
-
1074
- 🚦 **Impact Level**: Minimal
1075
-
1076
- #### What Changed
1077
-
1078
- If you provide a custom `default` value for `useAsyncData`, this will now be used when calling `clear` or `clearNuxtData` and it will be reset to its default value rather than simply unset.
1079
-
1080
- #### Reasons for Change
1081
-
1082
- Often users set an appropriately empty value, such as an empty array, to avoid the need to check for `null`/`undefined` when iterating over it. This should be respected when resetting/clearing the data.
1083
-
1084
- ### Respect defaults when clearing `useState`
1085
-
1086
- 🚦 **Impact Level**: Minimal
1087
-
1088
- #### What Changed
1089
-
1090
- With `compatibilityVersion: 5`, `clearNuxtState` will reset state to its initial value (provided by the `init` function of `useState`) instead of setting it to `undefined`. This aligns `clearNuxtState` behavior with `clearNuxtData`, which already resets to defaults.
1091
-
1092
- #### Reasons for Change
1093
-
1094
- When `clearNuxtState` sets state to `undefined`, composables that depend on that state can crash because they expect the state to always have a valid shape (e.g., accessing properties on `undefined`). Resetting to the `init` value ensures state always has a usable default.
1095
-
1096
- #### Migration Steps
1097
-
1098
- If you rely on `clearNuxtState` setting state to `undefined`, you can explicitly pass `{ reset: false }`:
1099
-
1100
- ```diff
1101
- - clearNuxtState('myKey')
1102
- + clearNuxtState('myKey', { reset: false })
1103
- ```
1104
-
1105
- Alternatively, you can revert to the previous behavior with:
1106
-
1107
- ```ts twoslash [nuxt.config.ts]
1108
- export default defineNuxtConfig({
1109
- experimental: {
1110
- defaults: {
1111
- useState: {
1112
- resetOnClear: false,
1113
- },
1114
- },
1115
- },
1116
- })
1117
- ```
1118
-
1119
- You can also opt in to this behavior today without setting `compatibilityVersion: 5`:
1120
-
1121
- ```ts twoslash [nuxt.config.ts]
1122
- export default defineNuxtConfig({
1123
- experimental: {
1124
- defaults: {
1125
- useState: {
1126
- resetOnClear: true,
1127
- },
1128
- },
1129
- },
1130
- })
1131
- ```
1132
-
1133
- ### Alignment of `pending` value in `useAsyncData` and `useFetch`
1134
-
1135
- 🚦 **Impact Level**: Medium
1136
-
1137
- The `pending` object returned from `useAsyncData`, `useFetch`, `useLazyAsyncData` and `useLazyFetch` is now a computed property that is `true` only when `status` is also pending.
1138
-
1139
- #### What Changed
1140
-
1141
- Now, when `immediate: false` is passed, `pending` will be `false` until the first request is made. This is a change from the previous behavior, where `pending` was always `true` until the first request was made.
1142
-
1143
- #### Reasons for Change
1144
-
1145
- This aligns the meaning of `pending` with the `status` property, which is also `pending` when the request is in progress.
1146
-
1147
- #### Migration Steps
1148
-
1149
- If you rely on the `pending` property, ensure that your logic accounts for the new behavior where `pending` will only be `true` when the status is also pending.
1150
-
1151
- ```diff
1152
- <template>
1153
- - <div v-if="!pending">
1154
- + <div v-if="status === 'success'">
1155
- <p>Data: {{ data }}</p>
1156
- </div>
1157
- <div v-else>
1158
- <p>Loading...</p>
1159
- </div>
1160
- </template>
1161
- <script setup lang="ts">
1162
- const { data, pending, execute, status } = await useAsyncData(() => fetch('/api/data'), {
1163
- immediate: false
1164
- })
1165
- onMounted(() => execute())
1166
- </script>
1167
- ```
1168
-
1169
- Alternatively, you can temporarily revert to the previous behavior with:
1170
-
1171
- ```ts twoslash [nuxt.config.ts]
1172
- export default defineNuxtConfig({
1173
- experimental: {
1174
- pendingWhenIdle: true,
1175
- },
1176
- })
1177
- ```
1178
-
1179
- ### Key Change Behavior in `useAsyncData` and `useFetch`
1180
-
1181
- 🚦 **Impact Level**: Medium
1182
-
1183
- #### What Changed
1184
-
1185
- When using reactive keys in `useAsyncData` or `useFetch`, Nuxt automatically refetches data when the key changes. When `immediate: false` is set, `useAsyncData` will only fetch data when the key changes if the data has already been fetched once.
1186
-
1187
- Previously, `useFetch` had slightly different behavior. It would always fetch data when the key changed.
1188
-
1189
- Now, `useFetch` and `useAsyncData` behave consistently - by only fetch data when the key changes if the data has already been fetched once.
1190
-
1191
- #### Reasons for Change
1192
-
1193
- This ensures consistent behavior between `useAsyncData` and `useFetch`, and prevents unexpected fetches. If you have set `immediate: false`, then you must call `refresh` or `execute` or data will never be fetched in `useFetch` or `useAsyncData`.
1194
-
1195
- #### Migration Steps
1196
-
1197
- This change should generally improve the expected behavior, but if you were expecting changing the key or options of a non-immediate `useFetch`, you now will need to trigger it manually the first time.
1198
-
1199
- ```diff
1200
- const id = ref('123')
1201
- const { data, execute } = await useFetch('/api/test', {
1202
- query: { id },
1203
- immediate: false
1204
- )
1205
- + watch(id, () => execute(), { once: true })
1206
- ```
1207
-
1208
- To opt out of this behavior:
1209
-
1210
- ```ts
1211
- // Or globally in your Nuxt config
1212
- export default defineNuxtConfig({
1213
- experimental: {
1214
- alwaysRunFetchOnKeyChange: true,
1215
- },
1216
- })
1217
- ```
1218
-
1219
- ### Shallow Data Reactivity in `useAsyncData` and `useFetch`
1220
-
1221
- 🚦 **Impact Level**: Minimal
1222
-
1223
- The `data` object returned from `useAsyncData`, `useFetch`, `useLazyAsyncData` and `useLazyFetch` is now a `shallowRef` rather than a `ref`.
1224
-
1225
- #### What Changed
1226
-
1227
- When new data is fetched, anything depending on `data` will still be reactive because the entire object is replaced. But if your code changes a property _within_ that data structure, this will not trigger any reactivity in your app.
1228
-
1229
- #### Reasons for Change
1230
-
1231
- This brings a **significant** performance improvement for deeply nested objects and arrays because Vue does not need to watch every single property/array for modification. In most cases, `data` should also be immutable.
1232
-
1233
- #### Migration Steps
1234
-
1235
- In most cases, no migration steps are required, but if you rely on the reactivity of the data object then you have two options:
1236
-
1237
- 1. You can granularly opt in to deep reactivity on a per-composable basis:
1238
- ```diff
1239
- - const { data } = useFetch('/api/test')
1240
- + const { data } = useFetch('/api/test', { deep: true })
1241
- ```
1242
- 1. You can change the default behavior on a project-wide basis (not recommended):
1243
- ```ts twoslash [nuxt.config.ts]
1244
- export default defineNuxtConfig({
1245
- experimental: {
1246
- defaults: {
1247
- useAsyncData: {
1248
- deep: true,
1249
- },
1250
- },
1251
- },
1252
- })
1253
- ```
1254
-
1255
- ::tip
1256
- If you need to, you can automate this step by running `npx codemod@latest nuxt/4/shallow-function-reactivity`
1257
- ::
1258
-
1259
- ### Absolute Watch Paths in `builder:watch`
1260
-
1261
- 🚦 **Impact Level**: Minimal
1262
-
1263
- #### What Changed
1264
-
1265
- The Nuxt `builder:watch` hook now emits a path which is absolute rather than relative to your project `srcDir`.
1266
-
1267
- #### Reasons for Change
1268
-
1269
- This allows us to support watching paths which are outside your `srcDir`, and offers better support for layers and other more complex patterns.
1270
-
1271
- #### Migration Steps
1272
-
1273
- We have already proactively migrated the public Nuxt modules which we are aware use this hook. See [issue #25339](https://github.com/nuxt/nuxt/issues/25339).
1274
-
1275
- However, if you are a module author using the `builder:watch` hook and wishing to remain backwards/forwards compatible, you can use the following code to ensure that your code works the same in both Nuxt v3 and Nuxt v4:
1276
-
1277
- ```diff
1278
- + import { relative, resolve } from 'node:fs'
1279
- // ...
1280
- nuxt.hook('builder:watch', async (event, path) => {
1281
- + path = relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, path))
1282
- // ...
1283
- })
1284
- ```
1285
-
1286
- ::tip
1287
- You can automate this step by running `npx codemod@latest nuxt/4/absolute-watch-path`
1288
- ::
1289
-
1290
- ### Removal of `window.__NUXT__` object
1291
-
1292
- #### What Changed
1293
-
1294
- We are removing the global `window.__NUXT__` object after the app finishes hydration.
1295
-
1296
- #### Reasons for Change
1297
-
1298
- This opens the way to multi-app patterns ([#21635](https://github.com/nuxt/nuxt/issues/21635)) and enables us to focus on a single way to access Nuxt app data - `useNuxtApp()`.
1299
-
1300
- #### Migration Steps
1301
-
1302
- The data is still available, but can be accessed with `useNuxtApp().payload`:
1303
-
1304
- ```diff
1305
- - console.log(window.__NUXT__)
1306
- + console.log(useNuxtApp().payload)
1307
- ```
1308
-
1309
- ### Directory index scanning
1310
-
1311
- 🚦 **Impact Level**: Medium
1312
-
1313
- #### What Changed
1314
-
1315
- Child folders in your `app/middleware/` folder are also scanned for `index` files and these are now also registered as middleware in your project.
1316
-
1317
- #### Reasons for Change
1318
-
1319
- Nuxt scans a number of folders automatically, including `app/middleware/` and `app/plugins/`.
1320
-
1321
- Child folders in your `app/plugins/` folder are scanned for `index` files and we wanted to make this behavior consistent between scanned directories.
1322
-
1323
- #### Migration Steps
1324
-
1325
- Probably no migration is necessary but if you wish to revert to previous behavior you can add a hook to filter out these middleware:
1326
-
1327
- ```ts
1328
- export default defineNuxtConfig({
1329
- hooks: {
1330
- 'app:resolve' (app) {
1331
- app.middleware = app.middleware.filter(mw => !/\/index\.[^/]+$/.test(mw.path))
1332
- },
1333
- },
1334
- })
1335
- ```
1336
-
1337
- ### Template Compilation Changes
414
+ ### Client-Only Comment Placeholders
1338
415
 
1339
416
  🚦 **Impact Level**: Minimal
1340
417
 
1341
418
  #### What Changed
1342
419
 
1343
- Previously, Nuxt used `lodash/template` to compile templates located on the file system using the `.ejs` file format/syntax.
1344
-
1345
- In addition, we provided some template utilities (`serialize`, `importName`, `importSources`) which could be used for code-generation within these templates, which are now being removed.
420
+ With `compatibilityVersion: 5`, client-only components (`.client.vue` files and `createClientOnly()` wrappers) now render an HTML comment (`<!--placeholder-->`) on the server instead of an empty `<div>` element.
1346
421
 
1347
422
  #### Reasons for Change
1348
423
 
1349
- In Nuxt v3 we moved to a 'virtual' syntax with a `getContents()` function which is much more flexible and performant.
1350
-
1351
- In addition, `lodash/template` has had a succession of security issues. These do not really apply to Nuxt projects because it is being used at build-time, not runtime, and by trusted code. However, they still appear in security audits. Moreover, `lodash` is a hefty dependency and is unused by most projects.
1352
-
1353
- Finally, providing code serialization functions directly within Nuxt is not ideal. Instead, we maintain projects like [unjs/knitwork](https://github.com/unjs/knitwork) which can be dependencies of your project, and where security issues can be reported/resolved directly without requiring an upgrade of Nuxt itself.
424
+ When the placeholder `<div>` and the actual component root share the same tag name, Vue's runtime skips re-applying `setScopeId` during hydration. This causes scoped styles to be missing after the component mounts. Using a comment node avoids the tag name collision entirely.
1354
425
 
1355
426
  #### Migration Steps
1356
427
 
1357
- We have raised PRs to update modules using EJS syntax, but if you need to do this yourself, you have three backwards/forwards-compatible alternatives:
1358
-
1359
- - Moving your string interpolation logic directly into `getContents()`.
1360
- - Using a custom function to handle the replacement, such as in https://github.com/nuxt-modules/color-mode/pull/240.
1361
- - Use `es-toolkit/compat` (a drop-in replacement for lodash template), as a dependency of _your_ project rather than Nuxt:
428
+ If you rely on the placeholder `<div>` to inherit attributes (`class`, `style`, etc.) for layout purposes (e.g., reserving space to prevent layout shift), wrap the component in `<ClientOnly>` with a `#fallback` slot instead:
1362
429
 
1363
430
  ```diff
1364
- + import { readFileSync } from 'node:fs'
1365
- + import { template } from 'es-toolkit/compat'
1366
- // ...
1367
- addTemplate({
1368
- fileName: 'appinsights-vue.js'
1369
- options: { /* some options */ },
1370
- - src: resolver.resolve('./runtime/plugin.ejs'),
1371
- + getContents({ options }) {
1372
- + const contents = readFileSync(resolver.resolve('./runtime/plugin.ejs'), 'utf-8')
1373
- + return template(contents)({ options })
1374
- + },
1375
- })
1376
- ```
1377
-
1378
- Finally, if you are using the template utilities (`serialize`, `importName`, `importSources`), you can replace them as follows with utilities from `knitwork`:
1379
-
1380
- ```ts
1381
- import { genDynamicImport, genImport, genSafeVariableName } from 'knitwork'
1382
-
1383
- const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"\{(.+)\}"(?=,?$)/gm, r => JSON.parse(r).replace(/^\{(.*)\}$/, '$1'))
1384
-
1385
- const importSources = (sources: string | string[], { lazy = false } = {}) => {
1386
- return toArray(sources).map((src) => {
1387
- if (lazy) {
1388
- return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`
1389
- }
1390
- return genImport(src, genSafeVariableName(src))
1391
- }).join('\n')
1392
- }
1393
-
1394
- const importName = genSafeVariableName
431
+ - <MyComponent class="placeholder" style="min-height: 200px" />
432
+ + <ClientOnly>
433
+ + <MyComponent />
434
+ + <template #fallback>
435
+ + <div class="placeholder" style="min-height: 200px"></div>
436
+ + </template>
437
+ + </ClientOnly>
1395
438
  ```
1396
439
 
1397
440
  ::tip
1398
- You can automate this step by running `npx codemod@latest nuxt/4/template-compilation-changes`
1399
- ::
1400
-
1401
- ### Default TypeScript Configuration Changes
1402
-
1403
- 🚦 **Impact Level**: Minimal
1404
-
1405
- #### What Changed
1406
-
1407
- `compilerOptions.noUncheckedIndexedAccess` is now `true` instead of `false`.
1408
-
1409
- #### Reasons for Change
1410
-
1411
- This change is a follow up to a prior [3.12 config update](https://github.com/nuxt/nuxt/pull/27485) where we improved our defaults, mostly adhering to [TotalTypeScript's recommendations](https://www.totaltypescript.com/tsconfig-cheat-sheet).
1412
-
1413
- #### Migration Steps
1414
-
1415
- There are two approaches:
1416
-
1417
- 1. Run a typecheck on your app and fix any new errors (recommended).
1418
-
1419
- 2. Override the new default in your `nuxt.config.ts`:
1420
-
1421
- <!-- @case-police-ignore tsConfig -->
1422
-
1423
- ```ts
1424
- export default defineNuxtConfig({
1425
- typescript: {
1426
- tsConfig: {
1427
- compilerOptions: {
1428
- noUncheckedIndexedAccess: false,
1429
- },
1430
- },
1431
- },
1432
- })
1433
- ```
1434
-
1435
- ### TypeScript Configuration Splitting
1436
-
1437
- 🚦 **Impact Level**: Minimal
1438
-
1439
- #### What Changed
1440
-
1441
- Nuxt now generates separate TypeScript configurations for different contexts to provide better type-checking experiences:
1442
-
1443
- 1. **New TypeScript configuration files**: Nuxt now generates additional TypeScript configurations:
1444
- - `.nuxt/tsconfig.app.json` - For your app code (Vue components, composables, etc.)
1445
- - `.nuxt/tsconfig.server.json` - For your server-side code (Nitro/server directory)
1446
- - `.nuxt/tsconfig.node.json` - For your build-time code (modules, `nuxt.config.ts`, etc.)
1447
- - `.nuxt/tsconfig.shared.json` - For code shared between app and server contexts (like types and non-environment specific utilities)
1448
- - `.nuxt/tsconfig.json` - Legacy configuration for backward compatibility
1449
-
1450
- 2. **Backward compatibility**: Existing projects that extend `.nuxt/tsconfig.json` will continue to work as before.
1451
-
1452
- 3. **Opt-in project references**: New projects or those wanting better type checking can adopt TypeScript's project references feature.
1453
-
1454
- 4. **Context-specific type checking**: Each context now has appropriate compiler options and includes/excludes for its specific environment.
1455
-
1456
- 5. **New `typescript.nodeTsConfig` option**: You can now customize the TypeScript configuration for Node.js build-time code.
1457
-
1458
- #### Reasons for Change
1459
-
1460
- This change provides several benefits:
1461
-
1462
- 1. **Better type safety**: Each context (app, server, build-time) gets appropriate type checking with context-specific globals and APIs.
1463
- 2. **Improved IDE experience**: Better IntelliSense and error reporting for different parts of your codebase.
1464
- 3. **Cleaner separation**: Server code won't incorrectly suggest client-side APIs and vice versa.
1465
- 4. **Performance**: TypeScript can more efficiently check code with properly scoped configurations.
1466
-
1467
- For example, auto-imports are not available in your `nuxt.config.ts` (but previously this was not flagged by TypeScript). And while IDEs recognized the separate context hinted by `tsconfig.json` in your `server/` directory, this was not reflected in type-checking (requiring a separate step).
1468
-
1469
- #### Migration Steps
1470
-
1471
- **No migration is required** - existing projects will continue to work as before.
1472
-
1473
- However, to take advantage of improved type checking, you can opt in to the new project references approach:
1474
-
1475
- 1. **Update your root `tsconfig.json`** to use project references:
1476
-
1477
- ::note
1478
- If your `tsconfig.json` currently has an `"extends": "./.nuxt/tsconfig.json"` line, **remove it** before adding the references. Project references and extends are mutually exclusive.
1479
- ::
1480
-
1481
- ```json
1482
- {
1483
- // Remove "extends": "./.nuxt/tsconfig.json" if present
1484
- "files": [],
1485
- "references": [
1486
- { "path": "./.nuxt/tsconfig.app.json" },
1487
- { "path": "./.nuxt/tsconfig.server.json" },
1488
- { "path": "./.nuxt/tsconfig.shared.json" },
1489
- { "path": "./.nuxt/tsconfig.node.json" }
1490
- ]
1491
- }
1492
- ```
1493
-
1494
- 2. **Remove any manual server `tsconfig.json`** files (like `server/tsconfig.json`) that extended `.nuxt/tsconfig.server.json`.
1495
-
1496
- 3. **Update your type checking scripts** to use the build flag for project references:
1497
-
1498
- ```diff
1499
- - "typecheck": "nuxt prepare && vue-tsc --noEmit"
1500
- + "typecheck": "nuxt prepare && vue-tsc -b --noEmit"
1501
- ```
1502
-
1503
- 4. **Move all type augmentations into their appropriate context**:
1504
- - If you are augmenting types for the app context, move the files to the `app/` directory.
1505
- - If you are augmenting types for the server context, move the files to the `server/` directory.
1506
- - If you are augmenting types that are **shared between the app and server**, move the files to the `shared/` directory.
1507
-
1508
- ::warning
1509
- Augmenting types from outside the `app/`, `server/`, or `shared/` directories will not work with the new project references setup.
1510
- ::
1511
-
1512
- 5. **Configure TypeScript options** if needed:
1513
- <!-- @case-police-ignore tsConfig -->
1514
-
1515
- ```ts
1516
- export default defineNuxtConfig({
1517
- typescript: {
1518
- // customize tsconfig.app.json
1519
- tsConfig: {
1520
- // ...
1521
- },
1522
- // customize tsconfig.shared.json
1523
- sharedTsConfig: {
1524
- // ...
1525
- },
1526
- // customize tsconfig.node.json
1527
- nodeTsConfig: {
1528
- // ...
1529
- },
1530
- },
1531
- nitro: {
1532
- typescript: {
1533
- // customize tsconfig.server.json
1534
- tsConfig: {
1535
- // ...
1536
- },
1537
- },
1538
- },
1539
- })
1540
- ```
1541
-
1542
- 6. **Update any CI/build scripts** that run TypeScript checking to ensure they use the new project references approach.
1543
-
1544
- The new configuration provides better type safety and IntelliSense for projects that opt in, while maintaining full backward compatibility for existing setups.
1545
-
1546
- ### Removal of Script-Type Payloads
1547
-
1548
- 🚦 **Impact Level**: Minimal
1549
-
1550
- #### What Changed
1551
-
1552
- The `experimental.renderJsonPayloads` option has been removed. JSON payloads (`_payload.json`) are now the only supported payload format. Script-type payloads (`_payload.js`) are no longer available, and the `@nuxt/devalue` dependency has been removed.
1553
-
1554
- #### Reasons for Change
1555
-
1556
- JSON payloads have been the default since Nuxt 3.4 and offer better performance and security characteristics. Maintaining two payload formats added unnecessary complexity.
1557
-
1558
- #### Migration Steps
1559
-
1560
- If you had `experimental.renderJsonPayloads` set in your `nuxt.config.ts`, remove it:
1561
-
1562
- ```diff
1563
- export default defineNuxtConfig({
1564
- experimental: {
1565
- - renderJsonPayloads: false,
1566
- },
1567
- })
1568
- ```
1569
-
1570
- If your application relied on script-type payloads (`_payload.js`), it will now automatically use JSON payloads (`_payload.json`) instead. No other changes should be required.
1571
-
1572
- ### Removal of Experimental Features
1573
-
1574
- 🚦 **Impact Level**: Minimal
1575
-
1576
- #### What Changed
1577
-
1578
- Four experimental features are no longer configurable in Nuxt 4:
1579
-
1580
- - `experimental.treeshakeClientOnly` will be `true` (default since v3.0)
1581
- - `experimental.configSchema` will be `true` (default since v3.3)
1582
- - `experimental.polyfillVueUseHead` will be `false` (default since v3.4)
1583
- - `experimental.respectNoSSRHeader` will be `false` (default since v3.4)
1584
- - `experimental.viteEnvironmentApi` is now always enabled and cannot be disabled
1585
- - `experimental.renderJsonPayloads` has been removed (see [Removal of Script-Type Payloads](/docs/5.x/getting-started/upgrade#removal-of-script-type-payloads))
1586
-
1587
- #### Reasons for Change
1588
-
1589
- These options have been set to their current values for some time and we do not have a reason to believe that they need to remain configurable.
1590
-
1591
- #### Migration Steps
1592
-
1593
- - `polyfillVueUseHead` is implementable in user-land with [this plugin](https://github.com/nuxt/nuxt/blob/f209158352b09d1986aa320e29ff36353b91c358/packages/nuxt/src/head/runtime/plugins/vueuse-head-polyfill.ts#L10-L11)
1594
-
1595
- - `respectNoSSRHeader`is implementable in user-land with [server middleware](https://github.com/nuxt/nuxt/blob/c660b39447f0d5b8790c0826092638d321cd6821/packages/nuxt/src/core/runtime/nitro/no-ssr.ts#L8-L9)
1596
-
1597
- ### Removal of Top-Level `generate` Configuration
1598
-
1599
- 🚦 **Impact Level**: Minimal
1600
-
1601
- #### What Changed
1602
-
1603
- The top-level `generate` configuration option is no longer available in Nuxt 4. This includes all of its properties:
1604
-
1605
- - `generate.exclude` - for excluding routes from prerendering
1606
- - `generate.routes` - for specifying routes to prerender
1607
-
1608
- #### Reasons for Change
1609
-
1610
- The top level `generate` configuration was a holdover from Nuxt 2. We've supported `nitro.prerender` for a while now, and it is the preferred way to configure prerendering in Nuxt 3+.
1611
-
1612
- #### Migration Steps
1613
-
1614
- Replace `generate` configuration with the corresponding `nitro.prerender` options:
1615
-
1616
- ```diff
1617
- export default defineNuxtConfig({
1618
- - generate: {
1619
- - exclude: ['/admin', '/private'],
1620
- - routes: ['/sitemap.xml', '/robots.txt']
1621
- - }
1622
- + nitro: {
1623
- + prerender: {
1624
- + ignore: ['/admin', '/private'],
1625
- + routes: ['/sitemap.xml', '/robots.txt']
1626
- + }
1627
- + }
1628
- })
1629
- ```
1630
-
1631
- ::read-more{to="https://nitro.build/config#prerender"}
1632
- Read more about Nitro's prerender configuration options.
441
+ You can test this feature early by setting `future.compatibilityVersion: 5` (see [Testing Nuxt 5](/docs/4.x/getting-started/upgrade#testing-nuxt-5)) or by enabling it explicitly with `experimental.clientNodePlaceholder: true`.
1633
442
  ::
1634
443
 
1635
- ### Normalized Page Component Names
1636
-
1637
- 🚦 **Impact Level**: Minimal
1638
-
1639
- #### What Changed
1640
-
1641
- When `future.compatibilityVersion` is set to `5` (or `experimental.normalizePageNames` is enabled), page component names match their route names instead of using the filename. For example, `pages/foo/index.vue` will have the component name `foo` instead of `index`.
1642
-
1643
- #### Reasons for Change
1644
-
1645
- Previously, Vue assigned component names based on the filename. This meant multiple pages like `pages/foo/index.vue` and `pages/bar/index.vue` would both have the component name `index`. This made `<KeepAlive>` with `include`/`exclude` filters unreliable and required manually adding `defineOptions({ name: '...' })` to each page.
1646
-
1647
- #### Migration Steps
1648
-
1649
- If you rely on the current component names (e.g. in `<KeepAlive>` `include`/`exclude` lists), update them to use route names instead of filenames.
1650
-
1651
- ```diff
1652
- <template>
1653
- <NuxtPage :keepalive="{
1654
- - include: ['index']
1655
- + include: ['foo']
1656
- }" />
1657
- </template>
1658
- ```
1659
-
1660
- To disable this behavior:
444
+ Alternatively, you can revert to the previous `<div>` placeholder behavior with:
1661
445
 
1662
446
  ```ts twoslash [nuxt.config.ts]
1663
447
  export default defineNuxtConfig({
1664
448
  experimental: {
1665
- normalizePageNames: false,
449
+ clientNodePlaceholder: false,
1666
450
  },
1667
451
  })
1668
452
  ```
1669
-
1670
- ## Nuxt 2 vs. Nuxt 3+
1671
-
1672
- In the table below, there is a quick comparison between 3 versions of Nuxt:
1673
-
1674
- | Feature / Version | Nuxt 2 | Nuxt Bridge | Nuxt 3+ |
1675
- |-------------------------|------------|-------------|------------|
1676
- | Vue | 2 | 2 | 3 |
1677
- | Stability | 😊 Stable | 😊 Stable | 😊 Stable |
1678
- | Performance | 🏎 Fast | ✈️ Faster | 🚀 Fastest |
1679
- | Nitro Engine | ❌ | ✅ | ✅ |
1680
- | ESM support | 🌙 Partial | 👍 Better | ✅ |
1681
- | TypeScript | ☑️ Opt-in | 🚧 Partial | ✅ |
1682
- | Composition API | ❌ | 🚧 Partial | ✅ |
1683
- | Options API | ✅ | ✅ | ✅ |
1684
- | Components Auto Import | ✅ | ✅ | ✅ |
1685
- | `<script setup>` syntax | ❌ | 🚧 Partial | ✅ |
1686
- | Auto Imports | ❌ | ✅ | ✅ |
1687
- | webpack | 4 | 4 | 5 |
1688
- | Vite | ⚠️ Partial | 🚧 Partial | ✅ |
1689
- | Nuxt CLI | ❌ Old | ✅ nuxt | ✅ nuxt |
1690
- | Static sites | ✅ | ✅ | ✅ |
1691
-
1692
- ## Nuxt 2 to Nuxt 3+
1693
-
1694
- The migration guide provides a step-by-step comparison of Nuxt 2 features to Nuxt 3+ features and guidance to adapt your current application.
1695
-
1696
- ::read-more{to="/docs/4.x/migration/overview"}
1697
- Check out the **guide to migrating from Nuxt 2 to Nuxt 3**.
1698
- ::
1699
-
1700
- ## Nuxt 2 to Nuxt Bridge
1701
-
1702
- If you prefer to progressively migrate your Nuxt 2 application to Nuxt 3, you can use Nuxt Bridge. Nuxt Bridge is a compatibility layer that allows you to use Nuxt 3+ features in Nuxt 2 with an opt-in mechanism.
1703
-
1704
- ::read-more{to="/docs/4.x/bridge/overview"}
1705
- **Migrate from Nuxt 2 to Nuxt Bridge**
1706
- ::
@@ -256,6 +256,26 @@ export default defineNuxtConfig({
256
256
  })
257
257
  ```
258
258
 
259
+ ## clientNodePlaceholder
260
+
261
+ Uses comment nodes (`<!--placeholder-->`) instead of `<div>` elements as placeholders for client-only components during server-side rendering.
262
+
263
+ When enabled, `.client.vue` components and `createClientOnly()` wrappers render an HTML comment on the server instead of an empty `<div>`. This fixes a Vue hydration issue where scoped styles may not be applied when the placeholder `<div>` and the actual component root share the same tag name.
264
+
265
+ ::warning
266
+ Enabling this means attributes (`class`, `style`, etc.) passed to `.client.vue` components will not appear in the SSR HTML. If you need styled placeholders to prevent layout shift, use `<ClientOnly>` with a `#fallback` slot instead.
267
+ ::
268
+
269
+ This flag is enabled when `future.compatibilityVersion` is set to `5` or higher, but you can also enable it explicitly:
270
+
271
+ ```ts twoslash [nuxt.config.ts]
272
+ export default defineNuxtConfig({
273
+ experimental: {
274
+ clientNodePlaceholder: true,
275
+ },
276
+ })
277
+ ```
278
+
259
279
  ## clientFallback
260
280
 
261
281
  Enables the experimental [`<NuxtClientFallback>`](/docs/4.x/api/components/nuxt-client-fallback) component for rendering content on the client if there's an error in SSR.
@@ -87,11 +87,16 @@ This is useful for enforcing settings like authentication headers or a specific
87
87
  You can pass a custom `$fetch` instance to `createUseFetch`:
88
88
 
89
89
  ```ts [app/composables/useAPI.ts]
90
- export const useAPI = createUseFetch({
90
+ export const useAPI = createUseFetch(callerOptions => ({
91
91
  $fetch: useNuxtApp().$api as typeof $fetch,
92
- })
92
+ ...callerOptions,
93
+ }))
93
94
  ```
94
95
 
96
+ ::important
97
+ The **function signature** (override mode) is required here so that [`useNuxtApp()`](/docs/4.x/api/composables/use-nuxt-app) is called in the setup context (at the composable call site) rather than in the module scope, where no Nuxt instance is available.
98
+ ::
99
+
95
100
  :read-more{to="/docs/4.x/guide/recipes/custom-usefetch"}
96
101
 
97
102
  :read-more{to="/docs/4.x/api/composables/use-fetch"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuxt/docs-nightly",
3
- "version": "5.0.0-29556898.efe4498a",
3
+ "version": "5.0.0-29558424.9dad7f28",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/nuxt/nuxt.git",