From 5f664546cf419fbd99937690ebe1f6ecea2d27cc Mon Sep 17 00:00:00 2001 From: gil Date: Wed, 13 May 2026 00:31:51 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=9C=84=ED=82=A4=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=EC=86=8C=20=EC=B4=88=EA=B8=B0=20=EC=BB=A4=EB=B0=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - CLAUDE.md 운영 규칙 - wiki/ 정리된 지식 페이지 (Nuxt + Claude Code) - raw/ 원본 자료 - reference/ Nuxt 4.x 공식 문서 Co-authored-by: Cursor --- .gitignore | 4 + CLAUDE.md | 159 ++ README.md | 11 + docs/4.x/api/composables/use-nuxt-data.md | 0 docs/4.x/directory-structure/app/plugins.md | 0 package.json | 20 + raw/.gitkeep | 0 raw/claude-agent-sdk-overview.md | 85 + ...claude-code-5-agentic-workflow-patterns.md | 147 + raw/claude-code-best-practices-official.md | 212 ++ ...e-full-stack-mcp-skills-subagents-hooks.md | 106 + raw/claude-code-hooks-cicd-patterns.md | 154 ++ ...laude-code-long-running-agent-harnesses.md | 75 + reference/00_Index.md | 27 + reference/1.getting-started/.navigation.yml | 3 + .../1.getting-started/01.introduction.md | 81 + .../1.getting-started/02.installation.md | 116 + .../1.getting-started/03.configuration.md | 226 ++ reference/1.getting-started/04.views.md | 167 ++ reference/1.getting-started/05.assets.md | 54 + reference/1.getting-started/06.styling.md | 583 ++++ reference/1.getting-started/07.routing.md | 153 ++ reference/1.getting-started/08.seo-meta.md | 377 +++ reference/1.getting-started/09.transitions.md | 578 ++++ .../1.getting-started/10.data-fetching.md | 817 ++++++ .../1.getting-started/11.state-management.md | 230 ++ .../1.getting-started/12.error-handling.md | 241 ++ reference/1.getting-started/13.server.md | 96 + reference/1.getting-started/14.layers.md | 172 ++ .../1.getting-started/15.prerendering.md | 208 ++ reference/1.getting-started/16.deployment.md | 137 + reference/1.getting-started/17.testing.md | 877 ++++++ reference/1.getting-started/18.upgrade.md | 526 ++++ .../2.directory-structure/.navigation.yml | 3 + reference/2.directory-structure/0.nuxt.md | 20 + reference/2.directory-structure/0.output.md | 18 + .../1.app/.navigation.yml | 5 + .../2.directory-structure/1.app/1.assets.md | 16 + .../1.app/1.components.md | 639 +++++ .../1.app/1.composables.md | 121 + .../2.directory-structure/1.app/1.layouts.md | 275 ++ .../1.app/1.middleware.md | 253 ++ .../2.directory-structure/1.app/1.pages.md | 467 ++++ .../2.directory-structure/1.app/1.plugins.md | 298 ++ .../2.directory-structure/1.app/1.utils.md | 49 + .../1.app/3.app-config.md | 177 ++ .../2.directory-structure/1.app/3.app.md | 72 + .../2.directory-structure/1.app/3.error.md | 53 + reference/2.directory-structure/1.content.md | 67 + reference/2.directory-structure/1.layers.md | 87 + reference/2.directory-structure/1.modules.md | 78 + .../2.directory-structure/1.node_modules.md | 12 + reference/2.directory-structure/1.public.md | 27 + reference/2.directory-structure/1.server.md | 561 ++++ reference/2.directory-structure/1.shared.md | 98 + reference/2.directory-structure/2.env.md | 79 + .../2.directory-structure/2.gitignore.md | 37 + .../2.directory-structure/2.nuxtignore.md | 37 + reference/2.directory-structure/2.nuxtrc.md | 57 + .../2.directory-structure/3.nuxt-config.md | 34 + reference/2.directory-structure/3.package.md | 32 + reference/2.directory-structure/3.tsconfig.md | 70 + reference/2.directory-structure/index.md | 65 + reference/3.guide/.navigation.yml | 2 + reference/3.guide/0.index.md | 28 + reference/3.guide/1.concepts/.navigation.yml | 3 + reference/3.guide/1.concepts/1.rendering.md | 236 ++ .../1.concepts/10.vuejs-development.md | 104 + .../3.guide/1.concepts/2.nuxt-lifecycle.md | 158 ++ .../3.guide/1.concepts/3.auto-imports.md | 205 ++ .../3.guide/1.concepts/4.server-engine.md | 62 + reference/3.guide/1.concepts/5.modules.md | 61 + reference/3.guide/1.concepts/7.esm.md | 306 +++ reference/3.guide/1.concepts/8.typescript.md | 120 + reference/3.guide/1.concepts/9.code-style.md | 22 + .../3.guide/2.best-practices/.navigation.yml | 3 + .../3.guide/2.best-practices/hydration.md | 188 ++ .../3.guide/2.best-practices/performance.md | 307 +++ reference/3.guide/2.best-practices/plugins.md | 20 + reference/3.guide/3.ai/.navigation.yml | 3 + reference/3.guide/3.ai/1.mcp.md | 277 ++ reference/3.guide/3.ai/2.llms-txt.md | 65 + reference/3.guide/4.modules/.navigation.yml | 3 + .../3.guide/4.modules/1.getting-started.md | 103 + .../3.guide/4.modules/2.module-anatomy.md | 138 + .../3.guide/4.modules/3.recipes-basics.md | 439 +++ .../3.guide/4.modules/4.recipes-advanced.md | 243 ++ reference/3.guide/4.modules/5.testing.md | 76 + .../3.guide/4.modules/6.best-practices.md | 104 + reference/3.guide/4.modules/7.ecosystem.md | 32 + reference/3.guide/4.modules/index.md | 36 + reference/3.guide/5.recipes/.navigation.yml | 3 + .../3.guide/5.recipes/1.custom-routing.md | 181 ++ reference/3.guide/5.recipes/2.vite-plugin.md | 110 + .../3.guide/5.recipes/3.custom-usefetch.md | 94 + .../4.sessions-and-authentication.md | 217 ++ .../3.guide/6.going-further/.navigation.yml | 3 + reference/3.guide/6.going-further/1.events.md | 62 + .../1.experimental-features.md | 968 +++++++ .../3.guide/6.going-further/1.features.md | 108 + .../3.guide/6.going-further/1.internals.md | 82 + .../6.going-further/10.runtime-config.md | 174 ++ .../11.nightly-release-channel.md | 62 + reference/3.guide/6.going-further/2.hooks.md | 100 + reference/3.guide/6.going-further/4.kit.md | 51 + .../3.guide/6.going-further/6.nuxt-app.md | 64 + reference/3.guide/6.going-further/7.layers.md | 311 +++ .../3.guide/6.going-further/9.debugging.md | 112 + reference/3.guide/6.going-further/index.md | 4 + reference/4.api/.navigation.yml | 3 + reference/4.api/1.components/.navigation.yml | 3 + reference/4.api/1.components/1.client-only.md | 79 + reference/4.api/1.components/1.dev-only.md | 51 + .../1.components/1.nuxt-client-fallback.md | 87 + .../4.api/1.components/10.nuxt-picture.md | 27 + reference/4.api/1.components/11.teleports.md | 43 + .../1.components/12.nuxt-route-announcer.md | 58 + reference/4.api/1.components/13.nuxt-time.md | 202 ++ .../4.api/1.components/14.nuxt-announcer.md | 81 + reference/4.api/1.components/2.nuxt-page.md | 154 ++ reference/4.api/1.components/3.nuxt-layout.md | 190 ++ reference/4.api/1.components/4.nuxt-link.md | 346 +++ .../1.components/5.nuxt-loading-indicator.md | 50 + .../1.components/6.nuxt-error-boundary.md | 67 + .../4.api/1.components/7.nuxt-welcome.md | 25 + reference/4.api/1.components/8.nuxt-island.md | 81 + reference/4.api/1.components/9.nuxt-img.md | 43 + reference/4.api/2.composables/.navigation.yml | 3 + .../2.composables/create-use-async-data.md | 90 + .../4.api/2.composables/create-use-fetch.md | 102 + .../4.api/2.composables/on-prehydrate.md | 69 + .../4.api/2.composables/use-announcer.md | 128 + .../4.api/2.composables/use-app-config.md | 19 + .../4.api/2.composables/use-async-data.md | 283 ++ reference/4.api/2.composables/use-cookie.md | 207 ++ reference/4.api/2.composables/use-error.md | 55 + reference/4.api/2.composables/use-fetch.md | 250 ++ .../4.api/2.composables/use-head-safe.md | 72 + reference/4.api/2.composables/use-head.md | 184 ++ .../4.api/2.composables/use-hydration.md | 74 + .../2.composables/use-lazy-async-data.md | 96 + .../4.api/2.composables/use-lazy-fetch.md | 112 + .../2.composables/use-loading-indicator.md | 77 + reference/4.api/2.composables/use-nuxt-app.md | 296 ++ .../4.api/2.composables/use-nuxt-data.md | 112 + .../4.api/2.composables/use-preview-mode.md | 115 + .../4.api/2.composables/use-request-event.md | 23 + .../4.api/2.composables/use-request-fetch.md | 52 + .../4.api/2.composables/use-request-header.md | 34 + .../2.composables/use-request-headers.md | 37 + .../4.api/2.composables/use-request-url.md | 41 + .../2.composables/use-response-header.md | 47 + .../2.composables/use-route-announcer.md | 62 + reference/4.api/2.composables/use-route.md | 87 + reference/4.api/2.composables/use-router.md | 94 + .../4.api/2.composables/use-runtime-config.md | 142 + .../4.api/2.composables/use-runtime-hook.md | 43 + reference/4.api/2.composables/use-seo-meta.md | 80 + .../2.composables/use-server-seo-meta.md | 33 + reference/4.api/2.composables/use-state.md | 58 + reference/4.api/3.utils/$fetch.md | 100 + reference/4.api/3.utils/.navigation.yml | 3 + reference/4.api/3.utils/abort-navigation.md | 73 + .../4.api/3.utils/add-route-middleware.md | 88 + reference/4.api/3.utils/call-once.md | 90 + reference/4.api/3.utils/clear-error.md | 29 + reference/4.api/3.utils/clear-nuxt-data.md | 23 + reference/4.api/3.utils/clear-nuxt-state.md | 25 + reference/4.api/3.utils/create-error.md | 55 + .../define-lazy-hydration-component.md | 261 ++ .../4.api/3.utils/define-nuxt-component.md | 53 + reference/4.api/3.utils/define-nuxt-plugin.md | 102 + .../3.utils/define-nuxt-route-middleware.md | 67 + reference/4.api/3.utils/define-page-meta.md | 298 ++ reference/4.api/3.utils/define-route-rules.md | 52 + reference/4.api/3.utils/navigate-to.md | 230 ++ .../4.api/3.utils/on-before-route-leave.md | 11 + .../4.api/3.utils/on-before-route-update.md | 11 + reference/4.api/3.utils/on-nuxt-ready.md | 25 + .../4.api/3.utils/prefetch-components.md | 28 + reference/4.api/3.utils/preload-components.md | 23 + .../4.api/3.utils/preload-route-components.md | 41 + reference/4.api/3.utils/prerender-routes.md | 46 + reference/4.api/3.utils/refresh-cookie.md | 44 + reference/4.api/3.utils/refresh-nuxt-data.md | 96 + reference/4.api/3.utils/reload-nuxt-app.md | 74 + reference/4.api/3.utils/set-page-layout.md | 60 + .../4.api/3.utils/set-response-status.md | 36 + reference/4.api/3.utils/show-error.md | 31 + reference/4.api/3.utils/update-app-config.md | 28 + reference/4.api/4.commands/.navigation.yml | 3 + reference/4.api/4.commands/add.md | 112 + reference/4.api/4.commands/analyze.md | 42 + reference/4.api/4.commands/build-module.md | 42 + reference/4.api/4.commands/build.md | 48 + reference/4.api/4.commands/cleanup.md | 38 + reference/4.api/4.commands/dev.md | 61 + reference/4.api/4.commands/devtools.md | 38 + reference/4.api/4.commands/generate.md | 43 + reference/4.api/4.commands/info.md | 33 + reference/4.api/4.commands/init.md | 50 + reference/4.api/4.commands/module.md | 84 + reference/4.api/4.commands/prepare.md | 41 + reference/4.api/4.commands/preview.md | 44 + reference/4.api/4.commands/test.md | 40 + reference/4.api/4.commands/typecheck.md | 44 + reference/4.api/4.commands/upgrade.md | 37 + reference/4.api/5.kit/.navigation.yml | 3 + reference/4.api/5.kit/1.modules.md | 401 +++ reference/4.api/5.kit/10.runtime-config.md | 29 + reference/4.api/5.kit/10.templates.md | 309 +++ reference/4.api/5.kit/11.nitro.md | 507 ++++ reference/4.api/5.kit/12.resolving.md | 214 ++ reference/4.api/5.kit/13.logging.md | 55 + reference/4.api/5.kit/14.builder.md | 327 +++ reference/4.api/5.kit/15.examples.md | 39 + reference/4.api/5.kit/16.layers.md | 220 ++ reference/4.api/5.kit/2.programmatic.md | 72 + reference/4.api/5.kit/3.compatibility.md | 183 ++ reference/4.api/5.kit/4.autoimports.md | 159 ++ reference/4.api/5.kit/5.components.md | 146 + reference/4.api/5.kit/6.context.md | 174 ++ reference/4.api/5.kit/7.pages.md | 193 ++ reference/4.api/5.kit/8.layout.md | 99 + reference/4.api/5.kit/9.head.md | 132 + reference/4.api/5.kit/9.plugins.md | 217 ++ reference/4.api/6.advanced/.navigation.yml | 1 + reference/4.api/6.advanced/1.hooks.md | 105 + reference/4.api/6.advanced/2.import-meta.md | 60 + reference/4.api/6.nuxt-config.md | 2438 +++++++++++++++++ reference/4.api/index.md | 31 + reference/5.community/.navigation.yml | 3 + reference/5.community/2.getting-help.md | 48 + reference/5.community/3.reporting-bugs.md | 50 + reference/5.community/4.contribution.md | 223 ++ .../5.community/5.framework-contribution.md | 142 + reference/5.community/6.roadmap.md | 82 + reference/5.community/7.changelog.md | 112 + reference/6.bridge/.navigation.yml | 3 + reference/6.bridge/1.overview.md | 145 + reference/6.bridge/10.configuration.md | 97 + reference/6.bridge/2.typescript.md | 48 + .../6.bridge/3.bridge-composition-api.md | 132 + .../6.bridge/4.plugins-and-middleware.md | 65 + reference/6.bridge/5.nuxt3-compatible-api.md | 207 ++ reference/6.bridge/6.meta.md | 118 + reference/6.bridge/7.runtime-config.md | 38 + reference/6.bridge/8.nitro.md | 106 + reference/6.bridge/9.vite.md | 37 + reference/7.migration/.navigation.yml | 3 + reference/7.migration/1.overview.md | 24 + reference/7.migration/10.bundling.md | 28 + reference/7.migration/11.server.md | 17 + reference/7.migration/2.configuration.md | 256 ++ reference/7.migration/20.module-authors.md | 94 + reference/7.migration/3.auto-imports.md | 18 + reference/7.migration/4.meta.md | 130 + .../7.migration/5.plugins-and-middleware.md | 80 + reference/7.migration/6.pages-and-layouts.md | 237 ++ reference/7.migration/7.component-options.md | 156 ++ reference/7.migration/8.runtime-config.md | 58 + wiki/claude-code-hooks.md | 149 + wiki/claude-code-overview.md | 105 + wiki/claude-code-project-setup.md | 164 ++ wiki/claude-code-workflow-patterns.md | 185 ++ wiki/index.md | 75 + wiki/log.md | 49 + wiki/nuxt-auto-imports.md | 133 + wiki/nuxt-data-fetching.md | 236 ++ wiki/nuxt-layers.md | 118 + wiki/nuxt-lifecycle.md | 131 + wiki/nuxt-performance.md | 256 ++ wiki/nuxt-rendering-modes.md | 166 ++ wiki/nuxt-routing.md | 195 ++ wiki/nuxt-state-management.md | 152 + 275 files changed, 35154 insertions(+) create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 README.md create mode 100644 docs/4.x/api/composables/use-nuxt-data.md create mode 100644 docs/4.x/directory-structure/app/plugins.md create mode 100644 package.json create mode 100644 raw/.gitkeep create mode 100644 raw/claude-agent-sdk-overview.md create mode 100644 raw/claude-code-5-agentic-workflow-patterns.md create mode 100644 raw/claude-code-best-practices-official.md create mode 100644 raw/claude-code-full-stack-mcp-skills-subagents-hooks.md create mode 100644 raw/claude-code-hooks-cicd-patterns.md create mode 100644 raw/claude-code-long-running-agent-harnesses.md create mode 100644 reference/00_Index.md create mode 100644 reference/1.getting-started/.navigation.yml create mode 100644 reference/1.getting-started/01.introduction.md create mode 100644 reference/1.getting-started/02.installation.md create mode 100644 reference/1.getting-started/03.configuration.md create mode 100644 reference/1.getting-started/04.views.md create mode 100644 reference/1.getting-started/05.assets.md create mode 100644 reference/1.getting-started/06.styling.md create mode 100644 reference/1.getting-started/07.routing.md create mode 100644 reference/1.getting-started/08.seo-meta.md create mode 100644 reference/1.getting-started/09.transitions.md create mode 100644 reference/1.getting-started/10.data-fetching.md create mode 100644 reference/1.getting-started/11.state-management.md create mode 100644 reference/1.getting-started/12.error-handling.md create mode 100644 reference/1.getting-started/13.server.md create mode 100644 reference/1.getting-started/14.layers.md create mode 100644 reference/1.getting-started/15.prerendering.md create mode 100644 reference/1.getting-started/16.deployment.md create mode 100644 reference/1.getting-started/17.testing.md create mode 100644 reference/1.getting-started/18.upgrade.md create mode 100644 reference/2.directory-structure/.navigation.yml create mode 100644 reference/2.directory-structure/0.nuxt.md create mode 100644 reference/2.directory-structure/0.output.md create mode 100644 reference/2.directory-structure/1.app/.navigation.yml create mode 100644 reference/2.directory-structure/1.app/1.assets.md create mode 100644 reference/2.directory-structure/1.app/1.components.md create mode 100644 reference/2.directory-structure/1.app/1.composables.md create mode 100644 reference/2.directory-structure/1.app/1.layouts.md create mode 100644 reference/2.directory-structure/1.app/1.middleware.md create mode 100644 reference/2.directory-structure/1.app/1.pages.md create mode 100644 reference/2.directory-structure/1.app/1.plugins.md create mode 100644 reference/2.directory-structure/1.app/1.utils.md create mode 100644 reference/2.directory-structure/1.app/3.app-config.md create mode 100644 reference/2.directory-structure/1.app/3.app.md create mode 100644 reference/2.directory-structure/1.app/3.error.md create mode 100644 reference/2.directory-structure/1.content.md create mode 100644 reference/2.directory-structure/1.layers.md create mode 100644 reference/2.directory-structure/1.modules.md create mode 100644 reference/2.directory-structure/1.node_modules.md create mode 100644 reference/2.directory-structure/1.public.md create mode 100644 reference/2.directory-structure/1.server.md create mode 100644 reference/2.directory-structure/1.shared.md create mode 100644 reference/2.directory-structure/2.env.md create mode 100644 reference/2.directory-structure/2.gitignore.md create mode 100644 reference/2.directory-structure/2.nuxtignore.md create mode 100644 reference/2.directory-structure/2.nuxtrc.md create mode 100644 reference/2.directory-structure/3.nuxt-config.md create mode 100644 reference/2.directory-structure/3.package.md create mode 100644 reference/2.directory-structure/3.tsconfig.md create mode 100644 reference/2.directory-structure/index.md create mode 100644 reference/3.guide/.navigation.yml create mode 100644 reference/3.guide/0.index.md create mode 100644 reference/3.guide/1.concepts/.navigation.yml create mode 100644 reference/3.guide/1.concepts/1.rendering.md create mode 100644 reference/3.guide/1.concepts/10.vuejs-development.md create mode 100644 reference/3.guide/1.concepts/2.nuxt-lifecycle.md create mode 100644 reference/3.guide/1.concepts/3.auto-imports.md create mode 100644 reference/3.guide/1.concepts/4.server-engine.md create mode 100644 reference/3.guide/1.concepts/5.modules.md create mode 100644 reference/3.guide/1.concepts/7.esm.md create mode 100644 reference/3.guide/1.concepts/8.typescript.md create mode 100644 reference/3.guide/1.concepts/9.code-style.md create mode 100644 reference/3.guide/2.best-practices/.navigation.yml create mode 100644 reference/3.guide/2.best-practices/hydration.md create mode 100644 reference/3.guide/2.best-practices/performance.md create mode 100644 reference/3.guide/2.best-practices/plugins.md create mode 100644 reference/3.guide/3.ai/.navigation.yml create mode 100644 reference/3.guide/3.ai/1.mcp.md create mode 100644 reference/3.guide/3.ai/2.llms-txt.md create mode 100644 reference/3.guide/4.modules/.navigation.yml create mode 100644 reference/3.guide/4.modules/1.getting-started.md create mode 100644 reference/3.guide/4.modules/2.module-anatomy.md create mode 100644 reference/3.guide/4.modules/3.recipes-basics.md create mode 100644 reference/3.guide/4.modules/4.recipes-advanced.md create mode 100644 reference/3.guide/4.modules/5.testing.md create mode 100644 reference/3.guide/4.modules/6.best-practices.md create mode 100644 reference/3.guide/4.modules/7.ecosystem.md create mode 100644 reference/3.guide/4.modules/index.md create mode 100644 reference/3.guide/5.recipes/.navigation.yml create mode 100644 reference/3.guide/5.recipes/1.custom-routing.md create mode 100644 reference/3.guide/5.recipes/2.vite-plugin.md create mode 100644 reference/3.guide/5.recipes/3.custom-usefetch.md create mode 100644 reference/3.guide/5.recipes/4.sessions-and-authentication.md create mode 100644 reference/3.guide/6.going-further/.navigation.yml create mode 100644 reference/3.guide/6.going-further/1.events.md create mode 100644 reference/3.guide/6.going-further/1.experimental-features.md create mode 100644 reference/3.guide/6.going-further/1.features.md create mode 100644 reference/3.guide/6.going-further/1.internals.md create mode 100644 reference/3.guide/6.going-further/10.runtime-config.md create mode 100644 reference/3.guide/6.going-further/11.nightly-release-channel.md create mode 100644 reference/3.guide/6.going-further/2.hooks.md create mode 100644 reference/3.guide/6.going-further/4.kit.md create mode 100644 reference/3.guide/6.going-further/6.nuxt-app.md create mode 100644 reference/3.guide/6.going-further/7.layers.md create mode 100644 reference/3.guide/6.going-further/9.debugging.md create mode 100644 reference/3.guide/6.going-further/index.md create mode 100644 reference/4.api/.navigation.yml create mode 100644 reference/4.api/1.components/.navigation.yml create mode 100644 reference/4.api/1.components/1.client-only.md create mode 100644 reference/4.api/1.components/1.dev-only.md create mode 100644 reference/4.api/1.components/1.nuxt-client-fallback.md create mode 100644 reference/4.api/1.components/10.nuxt-picture.md create mode 100644 reference/4.api/1.components/11.teleports.md create mode 100644 reference/4.api/1.components/12.nuxt-route-announcer.md create mode 100644 reference/4.api/1.components/13.nuxt-time.md create mode 100644 reference/4.api/1.components/14.nuxt-announcer.md create mode 100644 reference/4.api/1.components/2.nuxt-page.md create mode 100644 reference/4.api/1.components/3.nuxt-layout.md create mode 100644 reference/4.api/1.components/4.nuxt-link.md create mode 100644 reference/4.api/1.components/5.nuxt-loading-indicator.md create mode 100644 reference/4.api/1.components/6.nuxt-error-boundary.md create mode 100644 reference/4.api/1.components/7.nuxt-welcome.md create mode 100644 reference/4.api/1.components/8.nuxt-island.md create mode 100644 reference/4.api/1.components/9.nuxt-img.md create mode 100644 reference/4.api/2.composables/.navigation.yml create mode 100644 reference/4.api/2.composables/create-use-async-data.md create mode 100644 reference/4.api/2.composables/create-use-fetch.md create mode 100644 reference/4.api/2.composables/on-prehydrate.md create mode 100644 reference/4.api/2.composables/use-announcer.md create mode 100644 reference/4.api/2.composables/use-app-config.md create mode 100644 reference/4.api/2.composables/use-async-data.md create mode 100644 reference/4.api/2.composables/use-cookie.md create mode 100644 reference/4.api/2.composables/use-error.md create mode 100644 reference/4.api/2.composables/use-fetch.md create mode 100644 reference/4.api/2.composables/use-head-safe.md create mode 100644 reference/4.api/2.composables/use-head.md create mode 100644 reference/4.api/2.composables/use-hydration.md create mode 100644 reference/4.api/2.composables/use-lazy-async-data.md create mode 100644 reference/4.api/2.composables/use-lazy-fetch.md create mode 100644 reference/4.api/2.composables/use-loading-indicator.md create mode 100644 reference/4.api/2.composables/use-nuxt-app.md create mode 100644 reference/4.api/2.composables/use-nuxt-data.md create mode 100644 reference/4.api/2.composables/use-preview-mode.md create mode 100644 reference/4.api/2.composables/use-request-event.md create mode 100644 reference/4.api/2.composables/use-request-fetch.md create mode 100644 reference/4.api/2.composables/use-request-header.md create mode 100644 reference/4.api/2.composables/use-request-headers.md create mode 100644 reference/4.api/2.composables/use-request-url.md create mode 100644 reference/4.api/2.composables/use-response-header.md create mode 100644 reference/4.api/2.composables/use-route-announcer.md create mode 100644 reference/4.api/2.composables/use-route.md create mode 100644 reference/4.api/2.composables/use-router.md create mode 100644 reference/4.api/2.composables/use-runtime-config.md create mode 100644 reference/4.api/2.composables/use-runtime-hook.md create mode 100644 reference/4.api/2.composables/use-seo-meta.md create mode 100644 reference/4.api/2.composables/use-server-seo-meta.md create mode 100644 reference/4.api/2.composables/use-state.md create mode 100644 reference/4.api/3.utils/$fetch.md create mode 100644 reference/4.api/3.utils/.navigation.yml create mode 100644 reference/4.api/3.utils/abort-navigation.md create mode 100644 reference/4.api/3.utils/add-route-middleware.md create mode 100644 reference/4.api/3.utils/call-once.md create mode 100644 reference/4.api/3.utils/clear-error.md create mode 100644 reference/4.api/3.utils/clear-nuxt-data.md create mode 100644 reference/4.api/3.utils/clear-nuxt-state.md create mode 100644 reference/4.api/3.utils/create-error.md create mode 100644 reference/4.api/3.utils/define-lazy-hydration-component.md create mode 100644 reference/4.api/3.utils/define-nuxt-component.md create mode 100644 reference/4.api/3.utils/define-nuxt-plugin.md create mode 100644 reference/4.api/3.utils/define-nuxt-route-middleware.md create mode 100644 reference/4.api/3.utils/define-page-meta.md create mode 100644 reference/4.api/3.utils/define-route-rules.md create mode 100644 reference/4.api/3.utils/navigate-to.md create mode 100644 reference/4.api/3.utils/on-before-route-leave.md create mode 100644 reference/4.api/3.utils/on-before-route-update.md create mode 100644 reference/4.api/3.utils/on-nuxt-ready.md create mode 100644 reference/4.api/3.utils/prefetch-components.md create mode 100644 reference/4.api/3.utils/preload-components.md create mode 100644 reference/4.api/3.utils/preload-route-components.md create mode 100644 reference/4.api/3.utils/prerender-routes.md create mode 100644 reference/4.api/3.utils/refresh-cookie.md create mode 100644 reference/4.api/3.utils/refresh-nuxt-data.md create mode 100644 reference/4.api/3.utils/reload-nuxt-app.md create mode 100644 reference/4.api/3.utils/set-page-layout.md create mode 100644 reference/4.api/3.utils/set-response-status.md create mode 100644 reference/4.api/3.utils/show-error.md create mode 100644 reference/4.api/3.utils/update-app-config.md create mode 100644 reference/4.api/4.commands/.navigation.yml create mode 100644 reference/4.api/4.commands/add.md create mode 100644 reference/4.api/4.commands/analyze.md create mode 100644 reference/4.api/4.commands/build-module.md create mode 100644 reference/4.api/4.commands/build.md create mode 100644 reference/4.api/4.commands/cleanup.md create mode 100644 reference/4.api/4.commands/dev.md create mode 100644 reference/4.api/4.commands/devtools.md create mode 100644 reference/4.api/4.commands/generate.md create mode 100644 reference/4.api/4.commands/info.md create mode 100644 reference/4.api/4.commands/init.md create mode 100644 reference/4.api/4.commands/module.md create mode 100644 reference/4.api/4.commands/prepare.md create mode 100644 reference/4.api/4.commands/preview.md create mode 100644 reference/4.api/4.commands/test.md create mode 100644 reference/4.api/4.commands/typecheck.md create mode 100644 reference/4.api/4.commands/upgrade.md create mode 100644 reference/4.api/5.kit/.navigation.yml create mode 100644 reference/4.api/5.kit/1.modules.md create mode 100644 reference/4.api/5.kit/10.runtime-config.md create mode 100644 reference/4.api/5.kit/10.templates.md create mode 100644 reference/4.api/5.kit/11.nitro.md create mode 100644 reference/4.api/5.kit/12.resolving.md create mode 100644 reference/4.api/5.kit/13.logging.md create mode 100644 reference/4.api/5.kit/14.builder.md create mode 100644 reference/4.api/5.kit/15.examples.md create mode 100644 reference/4.api/5.kit/16.layers.md create mode 100644 reference/4.api/5.kit/2.programmatic.md create mode 100644 reference/4.api/5.kit/3.compatibility.md create mode 100644 reference/4.api/5.kit/4.autoimports.md create mode 100644 reference/4.api/5.kit/5.components.md create mode 100644 reference/4.api/5.kit/6.context.md create mode 100644 reference/4.api/5.kit/7.pages.md create mode 100644 reference/4.api/5.kit/8.layout.md create mode 100644 reference/4.api/5.kit/9.head.md create mode 100644 reference/4.api/5.kit/9.plugins.md create mode 100644 reference/4.api/6.advanced/.navigation.yml create mode 100644 reference/4.api/6.advanced/1.hooks.md create mode 100644 reference/4.api/6.advanced/2.import-meta.md create mode 100644 reference/4.api/6.nuxt-config.md create mode 100644 reference/4.api/index.md create mode 100644 reference/5.community/.navigation.yml create mode 100644 reference/5.community/2.getting-help.md create mode 100644 reference/5.community/3.reporting-bugs.md create mode 100644 reference/5.community/4.contribution.md create mode 100644 reference/5.community/5.framework-contribution.md create mode 100644 reference/5.community/6.roadmap.md create mode 100644 reference/5.community/7.changelog.md create mode 100644 reference/6.bridge/.navigation.yml create mode 100644 reference/6.bridge/1.overview.md create mode 100644 reference/6.bridge/10.configuration.md create mode 100644 reference/6.bridge/2.typescript.md create mode 100644 reference/6.bridge/3.bridge-composition-api.md create mode 100644 reference/6.bridge/4.plugins-and-middleware.md create mode 100644 reference/6.bridge/5.nuxt3-compatible-api.md create mode 100644 reference/6.bridge/6.meta.md create mode 100644 reference/6.bridge/7.runtime-config.md create mode 100644 reference/6.bridge/8.nitro.md create mode 100644 reference/6.bridge/9.vite.md create mode 100644 reference/7.migration/.navigation.yml create mode 100644 reference/7.migration/1.overview.md create mode 100644 reference/7.migration/10.bundling.md create mode 100644 reference/7.migration/11.server.md create mode 100644 reference/7.migration/2.configuration.md create mode 100644 reference/7.migration/20.module-authors.md create mode 100644 reference/7.migration/3.auto-imports.md create mode 100644 reference/7.migration/4.meta.md create mode 100644 reference/7.migration/5.plugins-and-middleware.md create mode 100644 reference/7.migration/6.pages-and-layouts.md create mode 100644 reference/7.migration/7.component-options.md create mode 100644 reference/7.migration/8.runtime-config.md create mode 100644 wiki/claude-code-hooks.md create mode 100644 wiki/claude-code-overview.md create mode 100644 wiki/claude-code-project-setup.md create mode 100644 wiki/claude-code-workflow-patterns.md create mode 100644 wiki/index.md create mode 100644 wiki/log.md create mode 100644 wiki/nuxt-auto-imports.md create mode 100644 wiki/nuxt-data-fetching.md create mode 100644 wiki/nuxt-layers.md create mode 100644 wiki/nuxt-lifecycle.md create mode 100644 wiki/nuxt-performance.md create mode 100644 wiki/nuxt-rendering-modes.md create mode 100644 wiki/nuxt-routing.md create mode 100644 wiki/nuxt-state-management.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0e7bddc --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +node_modules/ +.obsidian/ +.claude/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2771f98 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,159 @@ +# Nuxt 개발 지식 위키 — 운영 규칙 (Schema) + +이 저장소는 Nuxt(Vue 3) 개발 경험을 축적하는 개인 지식 위키다. +**Raw** → 원본 자료 보관, **Wiki** → 정리된 지식 저장, **CLAUDE.md** → 운영 규칙. + +--- + +## 디렉토리 구조 + +``` +nuxt-wiki/ +├── CLAUDE.md # 이 파일. 위키 운영 규칙 +├── raw/ # 개인 원본 자료 (플랫, Claude는 수정하지 않음) +├── wiki/ # 정리된 지식 (Claude가 작성·관리, 플랫) +│ ├── index.md # 전체 목차 (카테고리별 분류) +│ └── log.md # 작업 이력 +└── reference/ # Nuxt 4.x 공식 문서 (트리 구조 유지, 읽기 전용) +``` + +**플랫 구조 원칙:** `raw/`와 `wiki/` 내부에는 하위 폴더를 만들지 않는다. 분류는 `wiki/index.md`에서만 한다. `reference/`는 예외 — 공식 문서의 원래 트리 구조를 유지한다. + +--- + +## 카테고리 정의 + +| 카테고리 | 내용 | +|---|---| +| **핵심 개념** | Nuxt 라이프사이클, 렌더링 모드(SSR/SSG/ISR/SPA), 라우팅, 레이어, 모듈 시스템 | +| **패턴 & 레시피** | Composable 패턴, 상태관리(Pinia), 폼 처리, 인증 패턴 등 재사용 가능한 솔루션 | +| **모듈 & 에코시스템** | Nuxt 공식·서드파티 모듈, Nitro, UnJS 계열(H3, ofetch, defu 등) | +| **트러블슈팅** | 에러 사례, 삽질 기록, 버전별 Breaking Change, 해결책 | +| **성능 & 배포** | 번들 최적화, 캐싱 전략, CI/CD, Vercel·Netlify·Node 환경별 설정 | +| **아키텍처 결정** | ADR, 설계 고민, 트레이드오프 기록, 패턴 선택 근거 | + +--- + +## 운영 방법 3가지 + +### 1. 자료 넣기 (Ingest) + +**트리거:** 사용자가 `raw/`에 파일을 추가하거나, 텍스트/URL을 메시지로 붙여넣을 때. + +**Claude가 할 일:** +1. 원본 자료 읽기 (raw 파일이면 그대로, 텍스트면 `raw/`에 파일로 저장) +2. 관련 위키 페이지 파악 — 기존 페이지 업데이트 or 새 페이지 생성 +3. 각 위키 페이지 작성/갱신 (아래 페이지 형식 참고) +4. `wiki/index.md` 목차 업데이트 +5. `wiki/log.md`에 작업 이력 추가 + +**판단 기준:** +- 기존 페이지와 70% 이상 주제가 겹치면 → 해당 페이지에 병합 +- 새로운 주제면 → 새 페이지 생성 +- 한 자료에서 여러 주제가 나오면 → 여러 페이지에 분산하고 서로 [[교차참조]] + +--- + +### 2. 질문하기 (Query) + +**트리거:** 사용자가 Nuxt 관련 질문을 할 때. + +**Claude가 할 일:** +1. `wiki/index.md`와 관련 위키 페이지를 먼저 확인 +2. 위키 기반으로 답변 (어느 페이지를 참고했는지 명시) +3. 위키에 없는 내용이면 → 솔직하게 "위키에 없음"을 밝히고 일반 지식으로 보완 +4. 답변 과정에서 새로 정리할 가치가 있는 내용이 나오면 → 사용자에게 위키 추가 여부 제안 + +--- + +### 3. 건강검진 (Lint) + +**트리거:** 사용자가 "건강검진", "lint", "위키 점검"을 요청할 때. + +**Claude가 할 일:** +1. 모든 위키 페이지 스캔 +2. 아래 항목 체크: + - 끊긴 [[위키링크]] (참조 대상 페이지가 없는 것) + - 내용 충돌 (두 페이지에서 상반된 내용) + - 고아 페이지 (index.md에 없는 페이지) + - 업데이트 필요 (Nuxt 버전과 맞지 않는 낡은 내용) + - 빈 섹션 또는 TODO로만 채워진 페이지 +3. 문제 목록을 리포트하고, 수정 여부를 사용자에게 확인 후 처리 +4. `wiki/log.md`에 건강검진 결과 기록 + +--- + +## 위키 페이지 형식 + +```markdown +# 페이지 제목 + +> **카테고리:** 핵심 개념 | 패턴 & 레시피 | 모듈 & 에코시스템 | 트러블슈팅 | 성능 & 배포 | 아키텍처 결정 +> **최종 수정:** YYYY-MM-DD +> **관련:** [[페이지명]], [[페이지명]] + +## 요약 +한두 문장으로 이 페이지가 무엇을 다루는지. + +## 본문 +... + +## 참고 / 출처 +- raw/파일명 (원본 자료) +- 외부 링크 +``` + +**작성 규칙:** +- 제목은 `wiki/페이지명.md` 형태로 저장. 영문 소문자 + 하이픈 (예: `nuxt-rendering-modes.md`) +- 페이지 간 참조는 반드시 `[[페이지명]]` 형식 사용 (확장자 제외) +- 코드 예시는 언어 지정 코드블록으로 작성 +- 의견·추측은 `> ⚠️ 주의:` 또는 `> 💡 경험:` 인용 블록으로 구분 +- Nuxt 버전 의존적인 내용은 버전을 명시 (예: `Nuxt 3.x`, `Nuxt 4.x`) + +--- + +## 파일 네이밍 규칙 + +| 종류 | 형식 | 예시 | +|---|---|---| +| raw 원본 | 자유 (원본 이름 유지 권장) | `nuxt-4-migration-guide.md`, `adr-auth-strategy.txt` | +| wiki 페이지 | `kebab-case.md` | `nuxt-rendering-modes.md`, `usefetch-pattern.md` | +| 트러블슈팅 | `ts-{짧은 설명}.md` | `ts-hydration-mismatch.md` | +| ADR | `adr-{주제}.md` | `adr-state-management.md` | + +--- + +## 참조 라이브러리 (Reference) + +`reference/`는 Nuxt 4.x 공식 문서 클론이다. 읽기 전용 — 절대 수정하지 않는다. + +**언제 사용하나:** +- 사용자 질문에 위키(`wiki/`)만으로 답이 부족할 때 `reference/`를 먼저 검색 +- 위키 페이지 작성 시 공식 문서 내용을 인용·발췌할 때 + +**검색 방법:** +```bash +grep -r "키워드" reference/ +# 또는 폴더 구조로 직접 탐색: +# reference/1.getting-started/ → 시작하기, 설치, 설정 +# reference/2.directory-structure/ → 파일 구조 +# reference/3.guide/ → 개념 가이드 (라우팅, 상태관리 등) +# reference/4.api/ → 컴포저블, 유틸리티, 컴포넌트 API +# reference/5.community/ → 기여 가이드 +# reference/6.bridge/ → Nuxt 2→3 브릿지 +# reference/7.migration/ → 마이그레이션 가이드 +``` + +**출처 표기:** `reference/` 내용을 위키에 쓸 때는 `reference/{경로}` 형태로 명시한다. + +`raw/`와의 차이: `raw/`는 "내가 정리할 개인 자료", `reference/`는 "필요할 때 찾아볼 공식 자료". + +--- + +## 중요한 제약 + +- `raw/` 파일은 절대 수정하지 않는다. +- `reference/` 파일도 절대 수정하지 않는다. +- 위키 페이지를 삭제할 때는 사용자에게 먼저 확인한다. +- `wiki/log.md`는 항상 최신 상태로 유지한다. +- 위키 내용이 raw 원본과 충돌하면 raw 원본을 우선하되, 충돌 사실을 페이지에 명시한다. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6f7943c --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +--- +navigation: false +--- + +# Nuxt Docs + +This repository contains the documentation of Nuxt, hosted on + +## Contributing + +Have a look at to run the website locally. diff --git a/docs/4.x/api/composables/use-nuxt-data.md b/docs/4.x/api/composables/use-nuxt-data.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/4.x/directory-structure/app/plugins.md b/docs/4.x/directory-structure/app/plugins.md new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json new file mode 100644 index 0000000..c11a492 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "@nuxt/docs", + "version": "4.3.1", + "repository": { + "type": "git", + "url": "git+https://github.com/nuxt/nuxt.git", + "directory": "docs" + }, + "homepage": "https://nuxt.com", + "description": "Documentation for Nuxt in raw markdown", + "license": "MIT", + "type": "module", + "exports": { + "./*": "./*" + }, + "files": [ + "**/*.md", + "**/*.yml" + ] +} diff --git a/raw/.gitkeep b/raw/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/raw/claude-agent-sdk-overview.md b/raw/claude-agent-sdk-overview.md new file mode 100644 index 0000000..878d700 --- /dev/null +++ b/raw/claude-agent-sdk-overview.md @@ -0,0 +1,85 @@ +# Claude Agent SDK: 에이전트 구축 가이드 + +> 출처: https://claude.com/blog/building-agents-with-the-claude-agent-sdk +> 수집일: 2026-05-13 + +--- + +## 개요 + +Anthropic이 Claude Code SDK를 **Claude Agent SDK**로 이름 변경. 코딩을 넘어 더 광범위한 에이전트 응용에 대한 반영. + +핵심 설계 원칙: +> "에이전트에게 컴퓨터를 주어라. 인간처럼 작동하게 하라." + +bash 명령, 파일 작업, 코드 실행 접근 권한을 주면 Claude는 프로그래밍뿐만 아니라 데이터 분석, 리서치 등 다양한 작업을 처리할 수 있다. + +--- + +## 에이전트 루프 아키텍처 + +효과적인 에이전트는 반복 가능한 피드백 사이클로 동작한다: + +``` +1. Gather Context → 관련 정보 수집 +2. Take Action → 도구로 작업 실행 +3. Verify Work → 출력 평가 및 개선 +4. Iterate → 목표 달성까지 반복 +``` + +--- + +## 핵심 기능별 분류 + +### 컨텍스트 수집 (Gather Context) + +| 방법 | 설명 | 사용 시점 | +|---|---|---| +| Agentic Search | bash 스크립트(grep, tail)로 파일시스템 탐색 | **기본값** | +| Semantic Search | 벡터 기반 탐색 | agentic search가 부족할 때만 | +| Subagents | 병렬 작업 + 독립 컨텍스트 | 대규모·복잡 작업 | +| Compaction | 대화 히스토리 자동 요약 | 컨텍스트 오버플로우 방지 | + +### 액션 실행 (Take Action) + +- **Tools**: 주요 실행 메커니즘 (효율 위해 의식적으로 설계해야 함) +- **Bash & Scripts**: 유연한 범용 실행 (파일 변환, 웹 스크래핑) +- **Code Generation**: 복잡한 작업의 정밀하고 조합 가능한 출력 +- **MCPs**: 외부 서비스(Slack, GitHub, Asana) 표준화 통합 + +### 작업 검증 (Verify Work) + +| 방법 | 설명 | +|---|---| +| Rules-Based Feedback | 정의된 검증 기준 (린팅 등) | +| Visual Feedback | UI 작업용 스크린샷·렌더링 | +| LLM as Judge | 보조 모델 평가 (지연 비용 고려) | + +--- + +## 유스케이스 예시 + +- 포트폴리오·투자 분석 Finance 에이전트 +- 일정·여행 관리 Personal 어시스턴트 +- 복잡한 요청 처리 Customer Support 에이전트 +- 문서 종합 분석 Research 에이전트 + +--- + +## 에이전트 테스트 및 개선 + +실패 사례 분석 시 확인 포인트: +1. 실패 케이스와 근본 원인 검토 +2. 에이전트에게 적절한 도구가 있는지 평가 +3. 더 나은 정보 탐색 메커니즘 개선 +4. 공식적인 검증 규칙 추가 +5. 프로그래밍 방식 평가를 위한 대표 테스트 셋 구축 + +--- + +## 핵심 인사이트 + +> "semantic search는 agentic search가 부족할 때만 사용하라." +> 대부분의 경우 bash 기반 탐색이 더 효율적. + +> 도구는 **의식적으로 설계**해야 한다. 에이전트 효율성의 핵심. diff --git a/raw/claude-code-5-agentic-workflow-patterns.md b/raw/claude-code-5-agentic-workflow-patterns.md new file mode 100644 index 0000000..b842306 --- /dev/null +++ b/raw/claude-code-5-agentic-workflow-patterns.md @@ -0,0 +1,147 @@ +# Claude Code: 5가지 에이전틱 워크플로우 패턴 + +> 출처: https://www.mindstudio.ai/blog/claude-code-agentic-workflow-patterns +> 수집일: 2026-05-13 + +--- + +## 패턴 선택 원칙 + +> "단순한 것부터 시작하라 — Sequential — 더 단순한 패턴이 무너질 때만 복잡성을 추가하라." + +--- + +## 패턴 1: Sequential (순차) + +### 동작 방식 +각 단계가 순서대로 실행. 이전 출력이 다음 단계의 입력. +"파이프라인: A 완료 → 결과가 B로 전달" + +### 적합한 상황 +- 명확하고 예측 가능한 작업 순서 +- 각 단계 출력이 다음 단계 입력이 되는 경우 +- 1~2개 컨텍스트 윈도우 안에 들어오는 작업 + +### 예시 +``` +1. 명세 문서 읽기 +2. 함수 구현 생성 +3. 단위 테스트 작성 +4. 테스트 실행 후 결과 보고 +``` + +### 트레이드오프 +- ✅ 최대 단순성, 예측 가능성 +- ❌ 독립 작업 시 낮은 처리량 +- ❌ 긴 작업에서 컨텍스트 윈도우 한계 + +--- + +## 패턴 2: Operator (오케스트레이터) + +### 동작 방식 +제어 에이전트가 계획을 세우고 다른 에이전트나 특화된 도구 호출을 지시. +"하나가 두뇌, 특화된 subagent나 도구가 실행" + +### 적합한 상황 +- 전체 작업이 단일 컨텍스트 윈도우를 초과 +- 컴포넌트마다 다른 전문적 집중이 필요 +- 작업 우선순위에 대한 중앙 제어 필요 +- 계획과 실행의 명확한 분리가 필요 + +### 예시 (보안 감사) +오케스트레이터가 3개 subagent에 위임: +- 인증 스캔 담당 +- DB 쿼리 스캔 담당 +- 입력 검증 스캔 담당 +→ 결과를 종합해서 최종 리포트 + +### 트레이드오프 +- ✅ 뛰어난 확장성 +- ❌ 오케스트레이팅 에이전트가 병목 +- ❌ 명확한 인터페이스를 위한 세심한 프롬프트 엔지니어링 필요 + +--- + +## 패턴 3: Split-and-Merge (병렬) + +### 동작 방식 +코디네이터가 작업을 독립 청크로 분할 → 여러 인스턴스가 동시 작업 → 결과 수집 및 합성 + +### 적합한 상황 +- 상호 의존성 없이 깔끔하게 분리되는 작업 +- 속도가 중요할 때 (wall-clock time 단축) +- 대량의 유사 항목 처리 +- 격리에 적합한 독립적인 서브태스크 + +### 예시 +함수 50개 문서화 → 5개씩 10 배치로 분할 → 병렬 실행 → docstring 합산 + +### 트레이드오프 +- ✅ 병렬성으로 극적인 성능 향상 +- ❌ 합병 단계의 복잡성 +- ❌ 불일관한 출력, 부분 실패 처리 +- ❌ 동시 실행으로 비용 상승 + +--- + +## 패턴 4: Agent Teams (다중 에이전트 팀) + +### 동작 방식 +여러 특화된 에이전트가 지속적인 워크플로우에서 협업. 각 에이전트는 정의된 역할, 특정 범위, 고유 컨텍스트·도구 세트를 갖는다. + +### 적합한 상황 +- 여러 세션에 걸친 장기 프로젝트 +- 작업의 다양한 측면에서 진정한 전문화 필요 +- 범위 분산 없는 집중된 에이전트 작업 +- 기존 소프트웨어 개발 파이프라인과 유사한 구조 + +### 예시 팀 구조 +- **Planning agent**: 전체 목표 유지 +- **Code agent**: 구현 작성·수정 +- **Testing agent**: 동작 검증 +- **Review agent**: 품질 검사 +- **Documentation agent**: 문서 업데이트 + +### 트레이드오프 +- ✅ 에이전트당 집중된 컨텍스트로 복잡한 지속 작업에 강력 +- ❌ 조율 오버헤드 +- ❌ 오류 전파 — 신중한 설계와 커뮤니케이션 프로토콜 필요 + +--- + +## 패턴 5: Headless Autonomous (자율 자동화) + +### 동작 방식 +인간 개입 없이 이벤트, 스케줄, 외부 신호로 트리거. 작업 완료까지 독립 실행. + +### 적합한 상황 +- 잘 정의된 반복·이벤트 기반 작업 +- 알려진 실패 모드 + 복구 경로 +- 실행 후 출력 검증 가능 +- 반복 작업의 완전 자동화 + +### 예시 +- 야간 저장소 스캔 → 의존성 업데이트 → 자동 PR 생성 +- CI/CD 트리거 → 실패 진단 → 버그 리포트 +- 스케줄 실행 → API 사용 로그 감사 → 주간 요약 생성 + +### 트레이드오프 +- ✅ 반복 작업에서 최대 자동화 수익 +- ❌ 엄격한 안전장치 필요: + - 최소 권한 원칙 + - 가역적 작업 우선 + - 명확한 종료 조건 + - 인간 검토 체크포인트 + +--- + +## 패턴 선택 매트릭스 + +| 시나리오 | 최적 패턴 | +|---|---| +| 명확한 단계의 선형 작업 | Sequential | +| 서브 위임 필요한 대규모 작업 | Operator | +| 독립적 항목 다량 처리 | Split-and-merge | +| 다중 도메인 장기 프로젝트 | Agent teams | +| 반복·이벤트 트리거 자동화 | Headless | diff --git a/raw/claude-code-best-practices-official.md b/raw/claude-code-best-practices-official.md new file mode 100644 index 0000000..a6bd485 --- /dev/null +++ b/raw/claude-code-best-practices-official.md @@ -0,0 +1,212 @@ +# Best Practices for Claude Code (공식 문서) + +> 출처: https://code.claude.com/docs/en/best-practices +> 수집일: 2026-05-13 + +--- + +## 개요 + +Claude Code는 에이전틱 코딩 환경이다. 챗봇처럼 답하고 기다리는 게 아니라 파일 읽기, 명령 실행, 변경, 자율적 문제 해결이 가능하다. + +핵심 제약: **컨텍스트 윈도우가 빠르게 채워지고, 채워질수록 성능이 저하된다.** +- 컨텍스트 20~40% 채워지면 품질 저하 시작 +- 실제 실무에서 검증된 임계치: 60% 이상 채우지 말 것 + +--- + +## 1. 검증 수단을 항상 제공할 것 + +Claude는 스스로 검증할 수 있을 때 극적으로 성능이 올라간다. 테스트, 스크린샷, 기대 출력을 함께 제공하라. + +| 전략 | Before | After | +|---|---|---| +| 검증 기준 제공 | "이메일 검증 함수 구현해줘" | "validateEmail 작성. 테스트 케이스: user@example.com → true, invalid → false. 구현 후 테스트 실행해" | +| UI 변경 시각 검증 | "대시보드 보기 좋게 만들어줘" | "[스크린샷 붙여넣기] 이 디자인 구현하고, 결과 스크린샷 찍어서 원본과 비교해. 차이점 나열하고 수정해" | +| 증상이 아닌 근본 원인 | "빌드가 실패해" | "빌드 오류: [오류 붙여넣기]. 수정 후 빌드 성공 확인. 에러 억제 말고 근본 원인 해결해" | + +--- + +## 2. 탐색 → 계획 → 코딩 순서 + +곧바로 코딩하면 잘못된 문제를 풀 위험이 있다. Plan mode로 탐색과 실행을 분리하라. + +``` +1. Explore (Plan mode): 파일 읽기, 질문 — 수정 없음 +2. Plan (Plan mode): 상세 구현 계획 작성 +3. Implement: Plan mode 해제 후 코딩 + 테스트 +4. Commit: 설명적인 메시지 + PR 생성 +``` + +> 단, 작은 수정(오타, 변수명 변경)은 계획 없이 바로 실행해도 됨. 계획은 오버헤드. + +--- + +## 3. 구체적인 컨텍스트 제공 + +| 전략 | Before | After | +|---|---|---| +| 작업 범위 지정 | "foo.py 테스트 추가해줘" | "foo.py에서 로그아웃 상태 엣지 케이스 테스트 작성해줘. mock 사용 피해줘" | +| 소스 지시 | "왜 ExecutionFactory API가 이상해?" | "ExecutionFactory git 히스토리 보고 API가 어떻게 형성됐는지 요약해줘" | +| 기존 패턴 참조 | "캘린더 위젯 추가해줘" | "홈 페이지 기존 위젯(HotDogWidget.php 참고) 패턴 따라서, 월 선택 + 연도 페이지네이션 캘린더 위젯 만들어줘. 이미 쓰는 라이브러리만 사용해" | +| 증상 설명 | "로그인 버그 고쳐줘" | "세션 만료 후 로그인 실패 보고됨. src/auth/ auth flow, 특히 token refresh 확인해. 실패 재현 테스트 먼저 작성 후 수정해" | + +### Rich Content 제공 방법 +- `@` 파일 참조: `@src/auth.ts` 처럼 경로 직접 참조 +- 이미지 붙여넣기: 직접 복붙 or 드래그앤드롭 +- URL 제공: API 문서, 레퍼런스 +- 파이프: `cat error.log | claude` + +--- + +## 4. 환경 설정 + +### CLAUDE.md 효과적으로 작성 + +`/init` 명령으로 현재 프로젝트 구조 기반 초안 생성. + +**포함해야 할 것:** +- Claude가 추측할 수 없는 bash 명령 +- 기본값과 다른 코드 스타일 규칙 +- 테스트 실행 방법 +- 레포 규칙 (브랜치 네이밍, PR 컨벤션) +- 프로젝트 아키텍처 결정 사항 +- 흔한 gotcha / 비직관적 동작 + +**포함하면 안 되는 것:** +- 코드 읽으면 알 수 있는 것 +- 자주 바뀌는 정보 +- 긴 설명이나 튜토리얼 +- "clean code 작성해" 같은 당연한 것 + +> 규칙을 무시한다면 CLAUDE.md가 너무 긴 것. 불필요한 내용 제거하거나 hook으로 이전. + +CLAUDE.md import 문법: +```markdown +See @README.md for project overview. +# Additional Instructions +- Git workflow: @docs/git-instructions.md +``` + +CLAUDE.md 위치: +- `~/.claude/CLAUDE.md`: 전역 (모든 세션) +- `./CLAUDE.md`: 프로젝트 루트 (git 공유) +- `./CLAUDE.local.md`: 개인 설정 (.gitignore 추가) +- 하위 폴더: 해당 폴더 작업 시 자동 로드 + +### Hooks 설정 + +훅은 CLAUDE.md 지시와 달리 **결정론적으로 강제 실행**된다. + +``` +claude -p "eslint 실행하는 hook 작성해줘" +claude -p "migrations 폴더 쓰기 차단하는 hook 작성해줘" +``` + +### Skills 생성 + +`.claude/skills/` 에 `SKILL.md` 파일을 넣으면 도메인 지식 및 재사용 워크플로우로 사용 가능. + +```markdown +# .claude/skills/fix-issue/SKILL.md +--- +name: fix-issue +description: Fix a GitHub issue +disable-model-invocation: true +--- +Fix GitHub issue: $ARGUMENTS. +1. gh issue view로 상세 확인 +2. 문제 파악 +3. 관련 파일 탐색 +4. 수정 구현 +5. 테스트 작성 및 실행 +... +``` + +`/fix-issue 1234` 로 실행. `disable-model-invocation: true`는 수동 실행 전용 워크플로우에 사용. + +### Subagents 생성 + +`.claude/agents/`에 정의. 독립 컨텍스트 윈도우 + 특화된 도구 세트. + +```markdown +# .claude/agents/security-reviewer.md +--- +name: security-reviewer +description: Reviews code for security vulnerabilities +tools: Read, Grep, Glob, Bash +model: opus +--- +... +``` + +--- + +## 5. 세션 관리 + +### 컨텍스트를 공격적으로 관리 + +- `/clear`: 무관한 작업 사이에 컨텍스트 초기화 +- `/compact <지시사항>`: 부분 요약 (예: `/compact API 변경 사항 위주로`) +- `/btw`: 컨텍스트에 남기지 않는 사이드 질문 (오버레이로 표시) +- `Esc + Esc` / `/rewind`: 이전 체크포인트로 복원 + +CLAUDE.md에 컴팩션 지시도 가능: +```markdown +When compacting, always preserve the full list of modified files and any test commands. +``` + +### Subagents로 조사 위임 + +조사 시 많은 파일을 읽어 컨텍스트를 소비한다. Subagent로 위임하면 메인 컨텍스트 오염 방지. + +``` +Use subagents to investigate how our authentication system handles token refresh, +and whether we have any existing OAuth utilities I should reuse. +``` + +--- + +## 6. 자동화와 규모 확장 + +### Non-interactive 모드 + +```bash +# 단발 쿼리 +claude -p "이 프로젝트가 무엇인지 설명해줘" + +# 구조화된 출력 (스크립트용) +claude -p "API 엔드포인트 나열해줘" --output-format json + +# 스트리밍 +claude -p "로그 파일 분석해줘" --output-format stream-json +``` + +### 대규모 파일 병렬 처리 (Fan-out) + +```bash +for file in $(cat files.txt); do + claude -p "Migrate $file from React to Vue. Return OK or FAIL." \ + --allowedTools "Edit,Bash(git commit *)" +done +``` + +### Auto mode + +```bash +claude --permission-mode auto -p "fix all lint errors" +``` + +별도 classifier가 명령을 검토해 위험한 것만 차단. CI 파이프라인에 적합. + +--- + +## 7. 흔한 실수 패턴 + +| 패턴 | 문제 | 해결 | +|---|---|---| +| 주방 싱크 세션 | 무관한 작업이 섞여 컨텍스트 오염 | 작업 사이마다 `/clear` | +| 반복 수정 | 틀린 → 수정 → 또 틀린 → 컨텍스트 오염 | 두 번 실패 후 `/clear` + 더 구체적인 프롬프트로 재시작 | +| 비대한 CLAUDE.md | 규칙이 묻혀서 무시됨 | 규칙 줄이고, hook으로 이전 | +| 신뢰 후 검증 없음 | 그럴듯하지만 엣지케이스 미처리 | 항상 검증 수단 제공 (테스트, 스크린샷) | +| 무한 탐색 | 수백 개 파일 읽어 컨텍스트 폭발 | 조사 범위 좁게, 또는 subagent 사용 | diff --git a/raw/claude-code-full-stack-mcp-skills-subagents-hooks.md b/raw/claude-code-full-stack-mcp-skills-subagents-hooks.md new file mode 100644 index 0000000..c1179d3 --- /dev/null +++ b/raw/claude-code-full-stack-mcp-skills-subagents-hooks.md @@ -0,0 +1,106 @@ +# Claude Code 전체 스택 이해: MCP, Skills, Subagents, Hooks + +> 출처: https://alexop.dev/posts/understanding-claude-code-full-stack/ +> 수집일: 2026-05-13 + +--- + +## 개요 + +Claude Code는 CLI, VS Code, JetBrains, 데스크탑, 웹, iOS 등 다양한 플랫폼에서 AI 에이전트를 오케스트레이션하는 **프레임워크**다. 5개 핵심 컴포넌트가 서로 쌓여서 포괄적인 자동화 시스템을 만든다. + +--- + +## 핵심 컴포넌트 5개 + +### 1. MCP (Model Context Protocol) — 기반 + +Claude Code를 외부 도구 및 데이터 소스와 연결하는 **범용 어댑터**. + +- `/` slash 명령어로 MCP 서버 기능에 접근 +- HTTP transport + OAuth 2.1 with PKCE 인증 지원 (remote server) +- ⚠️ MCP 서버는 명시적으로 제공하지 않으면 Claude의 native 도구를 상속하지 않는다 + +```bash +claude mcp add # MCP 서버 연결 +``` + +### 2. Project Memory (CLAUDE.md) — 영속 컨텍스트 + +마크다운 파일로 영속적인 프로젝트 컨텍스트 설정. 계층적으로 병합됨: +**Enterprise → User → Project** + +- 코딩 표준, 아키텍처 패턴, 공통 명령어 +- `.claude/rules/`로 별도 파일 분리 가능 +- `CLAUDE.local.md`: 팀 공유 없는 개인 설정 + +### 3. Skills — 통합 확장 모델 + +재사용 가능한 워크플로우와 도메인 지식. CLAUDE.md의 모듈화 버전. + +frontmatter로 동작 제어: +- `auto-invoke`: Claude가 컨텍스트 기반으로 자동 적용 +- 사용자가 `/slash-command`로 수동 트리거 +- `disable-model-invocation: true`: 수동 전용 (사이드 이펙트 있는 워크플로우) +- `context: fork`: 독립 subagent로 실행 + +### 4. Subagents — 독립 컨텍스트 + +전문화된 AI 페르소나, 독립 컨텍스트 윈도우. + +- "컨텍스트 오염" 방지 (무거운 작업 격리) +- 2026 업데이트: **worktree isolation** — 여러 subagent가 파일을 병렬 편집 가능 +- 내장 타입: Explore, Plan, General-purpose + +### 5. Hooks — 이벤트 기반 강제 + +`.claude/settings.json`에 설정. 수동 호출 없이 자동 실행. + +이벤트 종류: +- 도구 라이프사이클 (PreToolUse, PostToolUse) +- 세션 관리 +- 파일 변경 +- 권한 + +핸들러 타입: command, prompt, HTTP request, async + +> PreToolUse hooks는 도구 실행 전 인수를 수정할 수 있다. + +--- + +## 지원 기능 + +**Plugins**: skills, hooks, 메타데이터를 패키징해서 팀 배포. + +**Scheduled Tasks**: 클라우드 인프라에서 cron 스케줄로 실행 — 사용자 없이 반복 자동화. + +--- + +## 용도별 선택 가이드 + +| 기능 | 사용 시점 | +|---|---| +| CLAUDE.md | 영속이 필요한 정적 지식 | +| Skills | 재사용 워크플로우 (자동/수동) | +| Subagents | 병렬 실행 및 격리가 필요할 때 | +| Hooks | 표준 강제, 이벤트 반응 | +| MCP | 외부 시스템 연동 | +| Scheduled Tasks | 사용자 없는 반복 작업 | + +--- + +## 실전 워크플로우 예시 (통합) + +1. **CLAUDE.md**: 표준 수립 +2. **load-context skill**: 새 채팅 시작 시 컨텍스트 초기화 +3. **documentation skill** (auto-invoke): 구현 후 자동 문서 업데이트 +4. **hooks**: 린팅 강제 +5. **subagents**: 격리된 구현 작업 처리 + +--- + +## 핵심 인사이트 + +> "대부분의 사람들은 기능 한두 개만 쓰고 어떻게 스택으로 연결되는지 보지 못한다." +> +> 이 컴포넌트들을 단순한 코딩 도구가 아니라 **컴퓨터 자동화를 위한 통합 시스템**으로 봐야 한다. diff --git a/raw/claude-code-hooks-cicd-patterns.md b/raw/claude-code-hooks-cicd-patterns.md new file mode 100644 index 0000000..b65a139 --- /dev/null +++ b/raw/claude-code-hooks-cicd-patterns.md @@ -0,0 +1,154 @@ +# Claude Code Hooks: 프로덕션 CI/CD 패턴 완전 가이드 + +> 출처: https://www.pixelmojo.io/blogs/claude-code-hooks-production-quality-ci-cd-patterns +> 수집일: 2026-05-13 + +--- + +## 개요 + +Claude Code hooks는 특정 라이프사이클 포인트에서 자동으로 실행되는 강제 메커니즘. 2026년 초 출시. 코딩 표준을 "권고 사항"에서 "Claude가 코드베이스에 접근할 때마다 실행되는 강제 게이트"로 전환. + +--- + +## 핸들러 타입 3가지 + +### 1. Command Hooks +shell script 실행. JSON을 stdin으로 받고 exit code로 결과 반환. +→ 포맷팅, 린팅, 파일 검증에 적합. + +### 2. Prompt Hooks +`$ARGUMENTS` 플레이스홀더로 컨텍스트를 주입해 Claude 모델에 평가 요청. +→ regex로 자동화하기 어려운 **의미론적 결정** (보안 분류 등)에 적합. + +### 3. Agent Hooks +도구 접근 권한 있는 subagent 실행 (Read, Grep, Glob). +→ 크로스 파일 검증, 아키텍처 패턴 준수 검사에 적합. + +--- + +## 12개 라이프사이클 이벤트 + +핵심 이벤트: +- **PreToolUse** (blocking): 실행 전 평가. **유일하게 작업을 거부할 수 있는 훅 타입** +- **PostToolUse** (non-blocking): 실행 후 포맷팅·검증 +- **Stop** (non-blocking): Claude 응답 완료 시 +- **SubagentStop** (non-blocking): subagent 완료 검증 + +--- + +## 프로덕션 패턴 + +### 자동 포맷팅 (PostToolUse) +```json +{ + "hooks": { + "PostToolUse": [{ + "matcher": "Edit|Write", + "handler": { + "type": "command", + "command": "npx prettier --write $FILEPATH" + } + }] + } +} +``` + +### 중요 파일 보호 (PreToolUse) +```json +{ + "hooks": { + "PreToolUse": [{ + "matcher": "Edit", + "handler": { + "type": "command", + "command": "node scripts/block-critical.js" + } + }] + } +} +``` + +### 의존성 가드 (PreToolUse) +프로덕션 패키지 무단 설치 차단: +```json +{ + "hooks": { + "PreToolUse": [{ + "matcher": "Bash", + "handler": { + "type": "command", + "command": "node scripts/block-deps.js" + } + }] + } +} +``` + +### Prompt 기반 보안 (PreToolUse) +컨텍스트 의존적 결정을 Claude에 위임: +```json +{ + "hooks": { + "PreToolUse": [{ + "matcher": "Edit", + "handler": { + "type": "prompt", + "prompt": "Analyze edit: $ARGUMENTS. Check for auth, DB, payments. DENY if any touched." + } + }] + } +} +``` + +--- + +## CI/CD 통합 + +GitHub Actions, GitLab CI와 동일한 hooks 실행. PR/MR 생성 시 트리거 → 결과를 PR 코멘트로 게시 → 모든 품질 게이트 통과 전까지 merge 차단. + +통합 포인트: +- PR opened/updated → PostToolUse: lint + type check +- MR opened/updated → PostToolUse: lint + security scan +- git commit → Stop: 전체 품질 스위트 +- Scheduled tasks → Agent: 코드베이스 감사 + +--- + +## 경쟁 도구 비교 + +| 기능 | Claude Code | Cursor | Copilot | +|---|---|---|---| +| 핸들러 타입 | Command, Prompt, **Agent** | Command만 | Command만 | +| 작업 차단 가능 | ✅ PreToolUse | ✅ | ✅ | +| LLM 기반 훅 | ✅ | ❌ | ❌ | +| Subagent 훅 | ✅ | ❌ | ❌ | + +--- + +## 설정 파일 위치 + +- `.claude/settings.json`: 프로젝트 레벨 (팀 공유) +- `~/.claude/settings.json`: 개인 기본값 +- 프로젝트 설정이 우선 적용 + +--- + +## 도입 로드맵 (단계별) + +1. **Phase 1**: PostToolUse 포맷팅 훅 (리스크 없음, 즉각 효과) +2. **Phase 2**: 중요 경로 파일 보호 PreToolUse +3. **Phase 3**: 공급망 공격 대비 의존성 가드 +4. **Phase 4**: 의미론적 보안 검토를 위한 Prompt 훅 +5. **Phase 5**: 아키텍처 심층 검증을 위한 Agent 훅 + +--- + +## 기술 부채 방지 효과 (통계) + +- **66% 생산성 세금**: PostToolUse 훅이 포맷팅·타입 오류를 즉시 잡아냄 +- **41% 코드 churne**: PreToolUse prompt 훅이 아키텍처 패턴 검증 → 리팩토링 필요 감소 +- **45% 취약점 비율**: PreToolUse 보안 훅이 리뷰 없는 민감 영역 편집 차단 + +> 인간 리뷰어는 아키텍처, 비즈니스 로직, 시스템 설계 등 섬세한 결정에 집중. +> 반복 가능한 검증 작업은 훅이 처리. diff --git a/raw/claude-code-long-running-agent-harnesses.md b/raw/claude-code-long-running-agent-harnesses.md new file mode 100644 index 0000000..ed16e46 --- /dev/null +++ b/raw/claude-code-long-running-agent-harnesses.md @@ -0,0 +1,75 @@ +# 장기 실행 에이전트를 위한 효과적인 Harness 설계 + +> 출처: https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents +> (Anthropic 엔지니어링 블로그) +> 수집일: 2026-05-13 + +--- + +## 핵심 문제 + +AI 에이전트는 여러 컨텍스트 윈도우에 걸쳐 일관성을 유지하기 어렵다. 컨텍스트 한계 때문에, 몇 시간 또는 며칠 걸리는 복잡한 작업은 여러 세션으로 나눠야 하는데, 각 세션은 이전 작업을 기억하지 못한 채 시작된다. + +--- + +## 해결책: 2단계 구조 + +### 1단계: Initializer Agent (첫 번째 세션) + +기반을 마련하는 역할: +- `init.sh` 스크립트 생성 — 환경 설정 +- `claude-progress.txt` 파일 생성 — 진행 상황 추적 로그 +- 초기 git commit (추가된 파일 기록) +- 200+ 항목의 기능 목록 작성 (claude.ai 클론 예시 기준) + +### 2단계: Coding Agent (이후 세션들) + +점진적 진행에 집중: +- progress 파일과 git 히스토리 읽어서 컨텍스트 복원 +- 한 번에 기능 하나씩 처리 +- 코드를 "merge-ready" 상태 유지 + 명확한 커밋 +- 완료 표시 전 철저한 테스트 필수 + +--- + +## 실패 모드와 해결책 + +| 문제 | 해결책 | +|---|---| +| 에이전트가 전체 프로젝트를 한 번에 완성하려 함 | 기능을 "failing" 상태로 목록화, 구조화된 feature list 강제 | +| 에이전트가 미완성 상태에서 "완료" 선언 | 포괄적 기능 추적 + 한 번에 하나의 기능만 허용 | +| 테스트 없이 완료 표시 | Puppeteer MCP로 브라우저 자동화 테스트 의무화 | +| 버그를 코드베이스에 기록 없이 방치 | 설명적 커밋 메시지 + progress 파일 업데이트 강제 | + +--- + +## 환경 관리 실천법 + +### Feature List +JSON 파일로 관리. 에이전트가 임의로 수정하지 못하게 구조 고정; "passing" 상태만 변경 가능. + +### 점진적 작업 +세션당 기능 하나. 컨텍스트 과부하 방지. + +### 테스트 도구 +브라우저 자동화(Puppeteer MCP)로 코드 검사로는 잡기 어려운 버그 검출. + +### Startup Routine +매 세션 시작 시: +1. `pwd` (현재 디렉토리 확인) +2. progress 파일 읽기 +3. 다음 기능 선택 +4. `init.sh` 실행 +5. 핵심 기능 동작 확인 +6. 점진적 변경 구현 + +--- + +## 핵심 인사이트 + +> "에이전트가 스스로 무엇을 했는지 추적하게 하라. +> 인간이 세션 사이 컨텍스트를 복구해주는 역할을 하면 안 된다." + +- `claude-progress.txt` 같은 파일은 세션 간 "메모리"를 대신한다 +- git 커밋 히스토리도 에이전트의 진행 상황 추적에 활용 가능 +- 초기화 스크립트로 각 세션이 동일한 환경에서 시작하도록 보장 diff --git a/reference/00_Index.md b/reference/00_Index.md new file mode 100644 index 0000000..5b4f290 --- /dev/null +++ b/reference/00_Index.md @@ -0,0 +1,27 @@ +# 🟢 Nuxt Official Wiki (MOC) + +최근 업데이트: 2026-05-12 (Source: Nuxt GitHub) + +## 🗺️ 문서 지도 + +### 1. [Getting Started](./1.getting-started/01.introduction.md) +- 시작하기 전에 알아야 할 기본 개념과 설치 방법 + +### 2. [Directory Structure](./2.directory-structure/) +- Nuxt 프로젝트의 각 폴더별 역할과 특징 + +### 3. [Guide](./3.guide/) +- 실무 핵심: 라우팅, 데이터 페칭, 상태 관리, 미들웨어 등 + +### 4. [API](./4.api/) +- Composables, Components, Utilities 상세 레퍼런스 + +### 5. [Migration & Bridge](./7.migration/) +- 버전 업그레이드 및 브릿지 가이드 + +--- + +## 🛠️ 활용 팁 (Obsidian) +- `Ctrl + O` (또는 `Cmd + O`): 문서 제목으로 검색 +- `Ctrl + Shift + F`: 전체 내용 검색 +- `[[Link]]`: 문서 간 연결 확인 diff --git a/reference/1.getting-started/.navigation.yml b/reference/1.getting-started/.navigation.yml new file mode 100644 index 0000000..92adc8e --- /dev/null +++ b/reference/1.getting-started/.navigation.yml @@ -0,0 +1,3 @@ +title: Get Started +titleTemplate: '%s · Get Started with Nuxt' +icon: i-lucide-rocket diff --git a/reference/1.getting-started/01.introduction.md b/reference/1.getting-started/01.introduction.md new file mode 100644 index 0000000..830f5ca --- /dev/null +++ b/reference/1.getting-started/01.introduction.md @@ -0,0 +1,81 @@ +--- +title: Introduction +description: Nuxt's goal is to make web development intuitive and performant with a great Developer Experience in mind. +navigation: + icon: i-lucide-info +--- + +Nuxt is a free and [open-source framework](https://github.com/nuxt/nuxt) with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with [Vue.js](https://vuejs.org). + +We made everything so you can start writing `.vue` files from the beginning while enjoying hot module replacement in development and a performant application in production with server-side rendering by default. + +Nuxt has no vendor lock-in, allowing you to deploy your application [**everywhere, even on the edge**](/blog/nuxt-on-the-edge). + +::tip +If you want to play around with Nuxt in your browser, you can [try it out in one of our online sandboxes](/docs/4.x/getting-started/installation#play-online). +:: + +## Automation and Conventions + +Nuxt uses conventions and an opinionated directory structure to automate repetitive tasks and allow developers to focus on pushing features. The configuration file can still customize and override its default behaviors. + +- **File-based routing:** define routes based on the structure of your [`app/pages/` directory](/docs/4.x/directory-structure/app/pages). This can make it easier to organize your application and avoid the need for manual route configuration. +- **Code splitting:** Nuxt automatically splits your code into smaller chunks, which can help reduce the initial load time of your application. +- **Server-side rendering out of the box:** Nuxt comes with built-in SSR capabilities, so you don't have to set up a separate server yourself. +- **Auto-imports:** write Vue composables and components in their respective directories and use them without having to import them with the benefits of tree-shaking and optimized JS bundles. +- **Data-fetching utilities:** Nuxt provides composables to handle SSR-compatible data fetching as well as different strategies. +- **Zero-config TypeScript support:** write type-safe code without having to learn TypeScript with our auto-generated types and `tsconfig.json`. +- **Configured build tools:** we use [Vite](https://vite.dev) by default to support hot module replacement (HMR) in development and bundling your code for production with best-practices baked-in. + +Nuxt takes care of these and provides both frontend and backend functionality so you can focus on what matters: **creating your web application**. + +## Server-Side Rendering + +Nuxt comes with built-in server-side rendering (SSR) capabilities by default, without having to configure a server yourself, which has many benefits for web applications: + +- **Faster initial page load time:** Nuxt sends a fully rendered HTML page to the browser, which can be displayed immediately. This can provide a faster perceived page load time and a better user experience (UX), especially on slower networks or devices. +- **Improved SEO:** search engines can better index SSR pages because the HTML content is available immediately, rather than requiring JavaScript to render the content on the client-side. +- **Better performance on low-powered devices:** it reduces the amount of JavaScript that needs to be downloaded and executed on the client-side, which can be beneficial for low-powered devices that may struggle with processing heavy JavaScript applications. +- **Better accessibility:** the content is immediately available on the initial page load, improving accessibility for users who rely on screen readers or other assistive technologies. +- **Easier caching:** pages can be cached on the server-side, which can further improve performance by reducing the amount of time it takes to generate and send the content to the client. + +Overall, server-side rendering can provide a faster and more efficient user experience, as well as improve search engine optimization and accessibility. + +As Nuxt is a versatile framework, it gives you the possibility to statically render your whole application to a static hosting with `nuxt generate`, +disable SSR globally with the `ssr: false` option or leverage hybrid rendering by setting up the `routeRules` option. + +:read-more{title="Nuxt rendering modes" to="/docs/4.x/guide/concepts/rendering"} + +### Server engine + +The Nuxt server engine [Nitro](https://nitro.build/) unlocks new full-stack capabilities. + +In development, it uses Rollup and Node.js workers for your server code and context isolation. It also generates your server API by reading files in `server/api/` and server middleware from `server/middleware/`. + +In production, Nitro builds your app and server into one universal `.output` directory. This output is light: minified and removed from any Node.js modules (except polyfills). You can deploy this output on any system supporting JavaScript, from Node.js, Serverless, Workers, Edge-side rendering or purely static. + +:read-more{title="Nuxt server engine" to="/docs/4.x/guide/concepts/server-engine"} + +### Production-ready + +A Nuxt application can be deployed on a Node or Deno server, pre-rendered to be hosted in static environments, or deployed to serverless and edge providers. + +:read-more{title="Deployment section" to="/docs/4.x/getting-started/deployment"} + +### Modular + +A module system allows you to extend Nuxt with custom features and integrations with third-party services. + +:read-more{title="Nuxt Modules Concept" to="/docs/4.x/guide/concepts/modules"} + +### Architecture + +Nuxt is composed of different [core packages](https://github.com/nuxt/nuxt/tree/main/packages): + +- Core engine: [nuxt](https://github.com/nuxt/nuxt/tree/main/packages/nuxt) +- Bundlers: [@nuxt/vite-builder](https://github.com/nuxt/nuxt/tree/main/packages/vite), [@nuxt/rspack-builder](https://github.com/nuxt/nuxt/tree/main/packages/rspack) and [@nuxt/webpack-builder](https://github.com/nuxt/nuxt/tree/main/packages/webpack) +- Command line interface: [@nuxt/cli](https://github.com/nuxt/cli) +- Server engine: [nitro](https://github.com/nitrojs/nitro) +- Development kit: [@nuxt/kit](https://github.com/nuxt/nuxt/tree/main/packages/kit) + +We recommend reading each concept to have a full vision of Nuxt capabilities and the scope of each package. diff --git a/reference/1.getting-started/02.installation.md b/reference/1.getting-started/02.installation.md new file mode 100644 index 0000000..a7b08fc --- /dev/null +++ b/reference/1.getting-started/02.installation.md @@ -0,0 +1,116 @@ +--- +title: 'Installation' +description: 'Get started with Nuxt quickly with our online starters or start locally with your terminal.' +navigation.icon: i-lucide-play +--- + +## Play Online + +If you just want to play around with Nuxt in your browser without setting up a project, you can use one of our online sandboxes: + +::card-group + :card{title="Open on StackBlitz" icon="i-simple-icons-stackblitz" to="https://nuxt.new/s/v4" target="_blank"} + :card{title="Open on CodeSandbox" icon="i-simple-icons-codesandbox" to="https://nuxt.new/c/v4" target="_blank"} +:: + +Or follow the steps below to set up a new Nuxt project on your computer. + +## New Project + +### Prerequisites + +- **Node.js** - [`20.x`](https://nodejs.org/en) or newer (but we recommend the [active LTS release](https://github.com/nodejs/release#release-schedule)) +- **Text editor** - There is no IDE requirement, but we recommend [Visual Studio Code](https://code.visualstudio.com/) with the [official Vue extension](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (previously known as Volar) or [WebStorm](https://www.jetbrains.com/webstorm/), which, along with [other JetBrains IDEs](https://www.jetbrains.com/ides/), offers great Nuxt support right out-of-the-box. If you use another editor, such as Neovim, you can configure [Vue Language Server](https://github.com/vuejs/language-tools) support by following the [Vue Language Tools setup guides](https://github.com/vuejs/language-tools/wiki). +- **Terminal** - In order to run Nuxt commands + +::note + ::details + :summary[Additional notes for an optimal setup:] + - **Node.js**: Make sure to use an even numbered version (20, 22, etc.) + - **Neovim**: When configuring the Vue TypeScript plugin, make sure `location` points to the `@vue/language-server` package directory, not its binary. See the [Neovim setup guide](https://github.com/vuejs/language-tools/wiki/Neovim) for a working configuration. + - **WSL**: If you are using Windows and experience slow HMR, you may want to try using [WSL (Windows Subsystem for Linux)](https://learn.microsoft.com/en-us/windows/wsl/install) which may solve some performance issues. + - **Windows slow DNS resolution**: Instead of using `localhost:3000` for local dev server on Windows, use `127.0.0.1` for much faster loading experience on browsers. + :: +:: + +Open a terminal (if you're using [Visual Studio Code](https://code.visualstudio.com), you can open an [integrated terminal](https://code.visualstudio.com/docs/terminal/basics)) and use the following command to create a new starter project: + +::code-group{sync="pm"} + +```bash [npm] +npm create nuxt@latest +``` + +```bash [yarn] +yarn create nuxt +``` + +```bash [pnpm] +pnpm create nuxt@latest +``` + +```bash [bun] +bun create nuxt@latest +``` + +```bash [deno] +deno -A npm:create-nuxt@latest +``` + +:: + +::tip +Alternatively, you can find other starters or themes by opening [nuxt.new](https://nuxt.new) and following the instructions there. +:: + +Open your project folder in Visual Studio Code: + +```bash [Terminal] +code +``` + +Or change directory into your new project from your terminal: + +```bash +cd +``` + +## Development Server + +Now you'll be able to start your Nuxt app in development mode: + +::code-group{sync="pm"} + +```bash [npm] +npm run dev -- -o +``` + +```bash [yarn] +yarn dev --open +``` + +```bash [pnpm] +pnpm dev -o +``` + +```bash [bun] +bun run dev -o + +# To use the Bun runtime during development +# bun --bun run dev -o +``` + +```bash [deno] +deno run dev -o +``` +:: + +::tip{icon="i-lucide-circle-check"} +Well done! A browser window should automatically open for . +:: + +## Next Steps + +Now that you've created your Nuxt project, you are ready to start building your application. + +:read-more{title="Nuxt Concepts" to="/docs/4.x/guide/concepts"} diff --git a/reference/1.getting-started/03.configuration.md b/reference/1.getting-started/03.configuration.md new file mode 100644 index 0000000..5efa17b --- /dev/null +++ b/reference/1.getting-started/03.configuration.md @@ -0,0 +1,226 @@ +--- +title: Configuration +description: Nuxt is configured with sensible defaults to make you productive. +navigation.icon: i-lucide-cog +--- + +By default, Nuxt is configured to cover most use cases. The [`nuxt.config.ts`](/docs/4.x/directory-structure/nuxt-config) file can override or extend this default configuration. + +## Nuxt Configuration + +The [`nuxt.config.ts`](/docs/4.x/directory-structure/nuxt-config) file is located at the root of a Nuxt project and can override or extend the application's behavior. + +A minimal configuration file exports the `defineNuxtConfig` function containing an object with your configuration. The `defineNuxtConfig` helper is globally available without import. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + // My Nuxt config +}) +``` + +This file will often be mentioned in the documentation, for example to add custom scripts, register modules or change rendering modes. + +::read-more{to="/docs/4.x/api/configuration/nuxt-config"} +Every option is described in the **Configuration Reference**. +:: + +::note +You don't have to use TypeScript to build an application with Nuxt. However, it is strongly recommended to use the `.ts` extension for the `nuxt.config` file. This way you can benefit from hints in your IDE to avoid typos and mistakes while editing your configuration. +:: + +### Environment Overrides + +You can configure fully typed, per-environment overrides in your nuxt.config + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + $production: { + routeRules: { + '/**': { isr: true }, + }, + }, + $development: { + // + }, + $env: { + staging: { + // + }, + }, +}) +``` + +To select an environment when running a Nuxt CLI command, simply pass the name to the `--envName` flag, like so: `nuxt build --envName staging`. + +To learn more about the mechanism behind these overrides, please refer to the `c12` documentation on [environment-specific configuration](https://github.com/unjs/c12?tab=readme-ov-file#environment-specific-configuration). + +:video-accordion{title="Watch a video from Alexander Lichter about the env-aware nuxt.config.ts" videoId="DFZI2iVCrNc"} + +::note +If you're authoring layers, you can also use the `$meta` key to provide metadata that you or the consumers of your layer might use. +:: + +### Environment Variables and Private Tokens + +The `runtimeConfig` API exposes values like environment variables to the rest of your application. By default, these keys are only available server-side. The keys within `runtimeConfig.public` and `runtimeConfig.app` (which is used by Nuxt internally) are also available client-side. + +Those values should be defined in `nuxt.config` and can be overridden using environment variables. + +::code-group + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + runtimeConfig: { + // The private keys which are only available server-side + apiSecret: '123', + // Keys within public are also exposed client-side + public: { + apiBase: '/api', + }, + }, +}) +``` + +```ini [.env] +# This will override the value of apiSecret +NUXT_API_SECRET=api_secret_token +``` + +:: + +These variables are exposed to the rest of your application using the [`useRuntimeConfig()`](/docs/4.x/api/composables/use-runtime-config) composable. + +```vue [app/pages/index.vue] + +``` + +:read-more{to="/docs/4.x/guide/going-further/runtime-config"} + +## App Configuration + +The `app.config.ts` file, located in the source directory (by default `app/`), is used to expose public variables that can be determined at build time. Contrary to the `runtimeConfig` option, these cannot be overridden using environment variables. + +A minimal configuration file exports the `defineAppConfig` function containing an object with your configuration. The `defineAppConfig` helper is globally available without import. + +```ts [app/app.config.ts] +export default defineAppConfig({ + title: 'Hello Nuxt', + theme: { + dark: true, + colors: { + primary: '#ff0000', + }, + }, +}) +``` + +These variables are exposed to the rest of your application using the [`useAppConfig`](/docs/4.x/api/composables/use-app-config) composable. + +```vue [app/pages/index.vue] + +``` + +:read-more{to="/docs/4.x/directory-structure/app/app-config"} + +## `runtimeConfig` vs. `app.config` + +As stated above, `runtimeConfig` and `app.config` are both used to expose variables to the rest of your application. To determine whether you should use one or the other, here are some guidelines: + +- `runtimeConfig`: Private or public tokens that need to be specified after build using environment variables. +- `app.config`: Public tokens that are determined at build time, website configuration such as theme variant, title and any project config that are not sensitive. + +| Feature | `runtimeConfig` | `app.config` | +|---------------------------|-----------------|--------------| +| Client-side | Hydrated | Bundled | +| Environment variables | ✅ Yes | ❌ No | +| Reactive | ✅ Yes | ✅ Yes | +| Types support | ✅ Partial | ✅ Yes | +| Configuration per request | ❌ No | ✅ Yes | +| Hot module replacement | ❌ No | ✅ Yes | +| Non-primitive JS types | ❌ No | ✅ Yes | + +## External Configuration Files + +Nuxt uses [`nuxt.config.ts`](/docs/4.x/directory-structure/nuxt-config) file as the single source of truth for configurations and skips reading external configuration files. During the course of building your project, you may have a need to configure those. The following table highlights common configurations and, where applicable, how they can be configured with Nuxt. + +| Name | Config File | How To Configure | +|-----------------------------------|-------------------------|---------------------------------------------------------------------------| +| [Nitro](https://nitro.build) | ~~`nitro.config.ts`~~ | Use [`nitro`](/docs/4.x/api/nuxt-config#nitro) key in `nuxt.config` | +| [PostCSS](https://postcss.org) | ~~`postcss.config.js`~~ | Use [`postcss`](/docs/4.x/api/nuxt-config#postcss) key in `nuxt.config` | +| [Vite](https://vite.dev) | ~~`vite.config.ts`~~ | Use [`vite`](/docs/4.x/api/nuxt-config#vite) key in `nuxt.config` | +| [webpack](https://webpack.js.org) | ~~`webpack.config.ts`~~ | Use [`webpack`](/docs/4.x/api/nuxt-config#webpack-1) key in `nuxt.config` | + +Here is a list of other common config files: + +| Name | Config File | How To Configure | +|----------------------------------------------|-----------------------|-------------------------------------------------------------------------------| +| [TypeScript](https://www.typescriptlang.org) | `tsconfig.json` | [More Info](/docs/4.x/directory-structure/tsconfig) | +| [ESLint](https://eslint.org) | `eslint.config.js` | [More Info](https://eslint.org/docs/latest/use/configure/configuration-files) | +| [Prettier](https://prettier.io) | `prettier.config.js` | [More Info](https://prettier.io/docs/configuration.html) | +| [Stylelint](https://stylelint.io) | `stylelint.config.js` | [More Info](https://stylelint.io/user-guide/configure/) | +| [TailwindCSS](https://tailwindcss.com) | `tailwind.config.js` | [More Info](https://tailwindcss.nuxtjs.org/tailwindcss/configuration/) | +| [Vitest](https://vitest.dev) | `vitest.config.ts` | [More Info](https://vitest.dev/config/) | + +## Vue Configuration + +### With Vite + +If you need to pass options to `@vitejs/plugin-vue` or `@vitejs/plugin-vue-jsx`, you can do this in your `nuxt.config` file. + +- `vite.vue` for `@vitejs/plugin-vue`. Check [available options](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue). +- `vite.vueJsx` for `@vitejs/plugin-vue-jsx`. Check [available options](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx). + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + vite: { + vue: { + customElement: true, + }, + vueJsx: { + mergeProps: true, + }, + }, +}) +``` + +:read-more{to="/docs/4.x/api/configuration/nuxt-config#vue"} + +### With webpack + +If you use webpack and need to configure `vue-loader`, you can do this using `webpack.loaders.vue` key inside your `nuxt.config` file. The available options are [defined here](https://github.com/vuejs/vue-loader/blob/main/src/index.ts#L32-L62). + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + webpack: { + loaders: { + vue: { + hotReload: true, + }, + }, + }, +}) +``` + +:read-more{to="/docs/4.x/api/configuration/nuxt-config#loaders"} + +### Enabling Experimental Vue Features + +You may need to enable experimental features in Vue, such as `propsDestructure`. Nuxt provides an easy way to do that in `nuxt.config.ts`, no matter which builder you are using: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + vue: { + propsDestructure: true, + }, +}) +``` + +#### experimental `reactivityTransform` migration from Vue 3.4 and Nuxt 3.9 + +Since Nuxt 3.9 and Vue 3.4, `reactivityTransform` has been moved from Vue to Vue Macros which has a [Nuxt integration](https://vue-macros.dev/guide/nuxt-integration.html). + +:read-more{to="/docs/4.x/api/configuration/nuxt-config#vue-1"} diff --git a/reference/1.getting-started/04.views.md b/reference/1.getting-started/04.views.md new file mode 100644 index 0000000..42a797e --- /dev/null +++ b/reference/1.getting-started/04.views.md @@ -0,0 +1,167 @@ +--- +title: 'Views' +description: 'Nuxt provides several component layers to implement the user interface of your application.' +navigation.icon: i-lucide-panels-top-left +--- + +## `app.vue` + +![The app.vue file is the entry point of your application](/assets/docs/getting-started/views/app.svg) + +By default, Nuxt will treat this file as the **entrypoint** and render its content for every route of the application. + +```vue [app/app.vue] + +``` + +::tip +If you are familiar with Vue, you might wonder where `main.js` is (the file that normally creates a Vue app). Nuxt does this behind the scene. +:: + +## Components + +![Components are reusable pieces of UI](/assets/docs/getting-started/views/components.svg) + +Most components are reusable pieces of the user interface, like buttons and menus. In Nuxt, you can create these components in the [`app/components/`](/docs/4.x/directory-structure/app/components) directory, and they will be automatically available across your application without having to explicitly import them. + +::code-group + +```vue [app/app.vue] + +``` + +```vue [app/components/AppAlert.vue] + +``` + +:: + +## Pages + +![Pages are views tied to a specific route](/assets/docs/getting-started/views/pages.svg) + +Pages represent views for each specific route pattern. Every file in the [`app/pages/`](/docs/4.x/directory-structure/app/pages) directory represents a different route displaying its content. + +To use pages, create an `app/pages/index.vue` file and add `` component to the [`app/app.vue`](/docs/4.x/directory-structure/app/app) (or remove `app/app.vue` for default entry). You can now create more pages and their corresponding routes by adding new files in the [`app/pages/`](/docs/4.x/directory-structure/app/pages) directory. + +::code-group + +```vue [app/pages/index.vue] + +``` + +```vue [app/pages/about.vue] + +``` + +:: + +:read-more{title="Routing Section" to="/docs/4.x/getting-started/routing"} + +## Layouts + +![Layouts are wrapper around pages](/assets/docs/getting-started/views/layouts.svg) + +Layouts are wrappers around pages that contain a common User Interface for several pages, such as header and footer displays. Layouts are Vue files using `` components to display the **page** content. The `app/layouts/default.vue` file will be used by default. Custom layouts can be set as part of your page metadata. + +::note +If you only have a single layout in your application, we recommend using [`app/app.vue`](/docs/4.x/directory-structure/app/app) with [``](/docs/4.x/api/components/nuxt-page) instead. +:: + +::code-group + +```vue [app/app.vue] + +``` + +```vue [app/layouts/default.vue] + +``` + +```vue [app/pages/index.vue] + +``` + +```vue [app/pages/about.vue] + +``` + +:: + +If you want to create more layouts and learn how to use them in your pages, find more information in the [Layouts section](/docs/4.x/directory-structure/app/layouts). + +## Advanced: Extending the HTML Template + +::note +If you only need to modify the ``, you can refer to the [SEO and meta section](/docs/4.x/getting-started/seo-meta). +:: + +You can have full control over the HTML template by adding a Nitro plugin that registers a hook. +The callback function of the `render:html` hook allows you to mutate the HTML before it is sent to the client. + + + +```ts [server/plugins/extend-html.ts] +import { definePlugin } from 'nitro' + +export default definePlugin((nitroApp) => { + nitroApp.hooks.hook('render:html', (html, { event }) => { + // This will be an object representation of the html template. + console.log(html) + html.head.push(``) + }) + // You can also intercept the response here. + nitroApp.hooks.hook('render:response', (response, { event }) => { console.log(response) }) +}) +``` + +:read-more{to="/docs/4.x/guide/going-further/hooks"} diff --git a/reference/1.getting-started/05.assets.md b/reference/1.getting-started/05.assets.md new file mode 100644 index 0000000..f3df675 --- /dev/null +++ b/reference/1.getting-started/05.assets.md @@ -0,0 +1,54 @@ +--- +title: 'Assets' +description: 'Nuxt offers two options for your assets.' +navigation.icon: i-lucide-image +--- + +Nuxt uses two directories to handle assets like stylesheets, fonts or images. + +- The [`public/`](/docs/4.x/directory-structure/public) directory content is served at the server root as-is. +- The [`app/assets/`](/docs/4.x/directory-structure/app/assets) directory contains by convention every asset that you want the build tool (Vite or webpack) to process. + +## Public Directory + +The [`public/`](/docs/4.x/directory-structure/public) directory is used as a public server for static assets publicly available at a defined URL of your application. + +You can get a file in the [`public/`](/docs/4.x/directory-structure/public) directory from your application's code or from a browser by the root URL `/`. + +### Example + +For example, referencing an image file in the `public/img/` directory, available at the static URL `/img/nuxt.png`: + +```vue [app/app.vue] + +``` + +## Assets Directory + +Nuxt uses [Vite](https://vite.dev/guide/assets) (default) or [webpack](https://webpack.js.org/guides/asset-management/) to build and bundle your application. The main function of these build tools is to process JavaScript files, but they can be extended through [plugins](https://vite.dev/plugins/) (for Vite) or [loaders](https://webpack.js.org/loaders/) (for webpack) to process other kinds of assets, like stylesheets, fonts or SVGs. This step transforms the original file, mainly for performance or caching purposes (such as stylesheet minification or browser cache invalidation). + +By convention, Nuxt uses the [`app/assets/`](/docs/4.x/directory-structure/app/assets) directory to store these files but there is no auto-scan functionality for this directory, and you can use any other name for it. + +In your application's code, you can reference a file located in the [`app/assets/`](/docs/4.x/directory-structure/app/assets) directory by using the `~/assets/` path. + +### Example + +For example, referencing an image file that will be processed if a build tool is configured to handle this file extension: + +```vue [app/app.vue] + +``` + +::note +Nuxt won't serve files in the [`app/assets/`](/docs/4.x/directory-structure/app/assets) directory at a static URL like `/assets/my-file.png`. If you need a static URL, use the [`public/`](/docs/4.x/getting-started/assets#public-directory) directory. +:: diff --git a/reference/1.getting-started/06.styling.md b/reference/1.getting-started/06.styling.md new file mode 100644 index 0000000..24c866d --- /dev/null +++ b/reference/1.getting-started/06.styling.md @@ -0,0 +1,583 @@ +--- +title: 'Styling' +description: 'Learn how to style your Nuxt application.' +navigation.icon: i-lucide-palette +--- + +Nuxt is highly flexible when it comes to styling. Write your own styles, or reference local and external stylesheets. +You can use CSS preprocessors, CSS frameworks, UI libraries and Nuxt modules to style your application. + +## Local Stylesheets + +If you're writing local stylesheets, the natural place to put them is the [`app/assets/` directory](/docs/4.x/directory-structure/app/assets). + +### Importing Within Components + +You can import stylesheets in your pages, layouts and components directly. +You can use a JavaScript import, or a CSS [`@import` statement](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@import). + +```vue [app/pages/index.vue] + + + +``` + +::tip +The stylesheets will be inlined in the HTML rendered by Nuxt. +:: + +### The CSS Property + +You can also use the `css` property in the Nuxt configuration. +The natural place for your stylesheets is the [`app/assets/` directory](/docs/4.x/directory-structure/app/assets). You can then reference its path and Nuxt will include it to all the pages of your application. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + css: ['~/assets/css/main.css'], +}) +``` + +::tip +The stylesheets will be inlined in the HTML rendered by Nuxt, injected globally and present in all pages. +:: + +### Working With Fonts + +Place your local fonts files in your `public/` directory, for example in `public/fonts`. You can then reference them in your stylesheets using `url()`. + +```css [assets/css/main.css] +@font-face { + font-family: 'FarAwayGalaxy'; + src: url('/fonts/FarAwayGalaxy.woff') format('woff'); + font-weight: normal; + font-style: normal; + font-display: swap; +} +``` + +Then reference your fonts by name in your stylesheets, pages or components: + +```vue + +``` + +### Stylesheets Distributed Through NPM + +You can also reference stylesheets that are distributed through npm. Let's use the popular `animate.css` library as an example. + +::code-group{sync="pm"} + +```bash [npm] +npm install animate.css +``` + +```bash [yarn] +yarn add animate.css +``` + +```bash [pnpm] +pnpm install animate.css +``` + +```bash [bun] +bun install animate.css +``` + +```bash [deno] +deno install npm:animate.css +``` + +:: + +Then you can reference it directly in your pages, layouts and components: + +```vue [app/app.vue] + + + +``` + +The package can also be referenced as a string in the css property of your Nuxt configuration. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + css: ['animate.css'], +}) +``` + +## External Stylesheets + +You can include external stylesheets in your application by adding a link element in the head section of your nuxt.config file. You can achieve this result using different methods. Note that local stylesheets can also be included this way. + +You can manipulate the head with the [`app.head`](/docs/4.x/api/nuxt-config#head) property of your Nuxt configuration: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + head: { + link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }], + }, + }, +}) +``` + +### Dynamically Adding Stylesheets + +You can use the useHead composable to dynamically set a value in your head in your code. + +:read-more{to="/docs/4.x/api/composables/use-head"} + +```ts twoslash +useHead({ + link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }], +}) +``` + +Nuxt uses `unhead` under the hood, and you can refer to [its full documentation](https://unhead.unjs.io). + +### Modifying The Rendered Head With A Nitro Plugin + +If you need more advanced control, you can intercept the rendered html with a hook and modify the head programmatically. + +Create a plugin in `~~/server/plugins/my-plugin.ts` like this: + + + +```ts [server/plugins/my-plugin.ts] +import { definePlugin } from 'nitro' + +export default definePlugin((nitro) => { + nitro.hooks.hook('render:html', (html) => { + html.head.push('') + }) +}) +``` + +External stylesheets are render-blocking resources: they must be loaded and processed before the browser renders the page. Web pages that contain unnecessarily large styles take longer to render. You can read more about it on [web.dev](https://web.dev/articles/defer-non-critical-css). + +## Using Preprocessors + +To use a preprocessor like SCSS, Sass, Less or Stylus, install it first. + +::code-group + +```bash [Sass & SCSS] +npm install -D sass +``` + +```bash [Less] +npm install -D less +``` + +```bash [Stylus] +npm install -D stylus +``` + +:: + +The natural place to write your stylesheets is the `app/assets` directory. +You can then import your source files in your `app.vue` (or layouts files) using your preprocessor's syntax. + +```vue [app/pages/app.vue] + +``` + +Alternatively, you can use the `css` property of your Nuxt configuration. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + css: ['~/assets/scss/main.scss'], +}) +``` + +::tip +In both cases, the compiled stylesheets will be inlined in the HTML rendered by Nuxt. +:: + +If you need to inject code in pre-processed files, like a [Sass partial](https://sass-lang.com/documentation/at-rules/use/#partials) with color variables, you can do so with the Vite [preprocessors options](https://vite.dev/config/shared-options#css-preprocessoroptions). + +Create some partials in your `app/assets` directory: + +::code-group{sync="preprocessor"} + +```scss [assets/_colors.scss] +$primary: #49240F; +$secondary: #E4A79D; +``` + +```sass [assets/_colors.sass] +$primary: #49240F +$secondary: #E4A79D +``` + +:: + +Then in your `nuxt.config` : + +::code-group + +```ts twoslash [SCSS] +export default defineNuxtConfig({ + vite: { + css: { + preprocessorOptions: { + scss: { + additionalData: '@use "~/assets/_colors.scss" as *;', + }, + }, + }, + }, +}) +``` + +```ts twoslash [SASS] +export default defineNuxtConfig({ + vite: { + css: { + preprocessorOptions: { + sass: { + additionalData: '@use "~/assets/_colors.sass" as *\n', + }, + }, + }, + }, +}) +``` + +:: + +Nuxt uses Vite by default. If you wish to use webpack instead, refer to each preprocessor loader [documentation](https://webpack.js.org/loaders/sass-loader/). + +### Preprocessor Workers (Experimental) + +Vite has made available an [experimental option](https://vite.dev/config/shared-options#css-preprocessormaxworkers) which can speed up using preprocessors. + +You can enable this in your `nuxt.config`: + +```ts +export default defineNuxtConfig({ + vite: { + css: { + preprocessorMaxWorkers: true, // number of CPUs minus 1 + }, + }, +}) +``` + +::note +This is an experimental option and you should refer to the Vite documentation and [provide feedback](https://github.com/vitejs/vite/discussions/15835). +:: + +## Single File Components (SFC) Styling + +One of the best things about Vue and SFC is how great it is at naturally dealing with styling. You can directly write CSS or preprocessor code in the style block of your components file, therefore you will have fantastic developer experience without having to use something like CSS-in-JS. However if you wish to use CSS-in-JS, you can find 3rd party libraries and modules that support it, such as [pinceau](https://github.com/Tahul/pinceau). + +You can refer to the [Vue docs](https://vuejs.org/api/sfc-css-features) for a comprehensive reference about styling components in SFC. + +### Class And Style Bindings + +You can leverage Vue SFC features to style your components with class and style attributes. + +::code-group + +```vue [Ref and Reactive] + + + +``` + +```vue [Computed] + + + +``` + +```vue [Array] + + + +``` + +```vue [Style] + + + +``` + +:: + +Refer to the [Vue docs](https://vuejs.org/guide/essentials/class-and-style) for more information. + +### Dynamic Styles With `v-bind` + +You can reference JavaScript variable and expression within your style blocks with the v-bind function. +The binding will be dynamic, meaning that if the variable value changes, the style will be updated. + +```vue + + + + + +``` + +### Scoped Styles + +The scoped attribute allows you to style components in isolation. The styles declared with this attribute will only apply to this component. + +```vue + + + +``` + +### CSS Modules + +You can use [CSS Modules](https://github.com/css-modules/css-modules) with the module attribute. Access it with the injected `$style` variable. + +```vue + + + +``` + +### Preprocessors Support + +SFC style blocks support preprocessor syntax. Vite comes with built-in support for .scss, .sass, .less, .styl and .stylus files without configuration. You just need to install them first, and they will be available directly in SFC with the lang attribute. + +::code-group + +```vue [SCSS] + +``` + +```vue [Sass] + +``` + +```vue [LESS] + +``` + +```vue [Stylus] + +``` + +:: + +You can refer to the [Vite CSS docs](https://vite.dev/guide/features#css) and the [@vitejs/plugin-vue docs](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue). +For webpack users, refer to the [vue loader docs](https://vue-loader.vuejs.org). + +## Using PostCSS + +Nuxt comes with postcss built-in. You can configure it in your `nuxt.config` file. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + postcss: { + plugins: { + 'postcss-nested': {}, + 'postcss-custom-media': {}, + }, + }, +}) +``` + +For proper syntax highlighting in SFC, you can use the postcss lang attribute. + +```vue + +``` + +By default, Nuxt comes with the following plugins already pre-configured: + +- [postcss-import](https://github.com/postcss/postcss-import): Improves the `@import` rule +- [postcss-url](https://github.com/postcss/postcss-url): Transforms `url()` statements +- [autoprefixer](https://github.com/postcss/autoprefixer): Automatically adds vendor prefixes +- [cssnano](https://cssnano.github.io/cssnano/): Minification and purge + +## Leveraging Layouts For Multiple Styles + +If you need to style different parts of your application completely differently, you can use layouts. +Use different styles for different layouts. + +```vue + + + +``` + +:read-more{to="/docs/4.x/directory-structure/app/layouts"} + +## Third Party Libraries And Modules + +Nuxt isn't opinionated when it comes to styling and provides you with a wide variety of options. You can use any styling tool that you want, such as popular libraries like [UnoCSS](https://unocss.dev) or [Tailwind CSS](https://tailwindcss.com). + +The community and the Nuxt team have developed plenty of Nuxt modules to make the integration easier. +You can discover them on the [modules section](/modules) of the website. +Here are a few modules to help you get started: + +- [UnoCSS](/modules/unocss): Instant on-demand atomic CSS engine +- [Tailwind CSS](/modules/tailwindcss): Utility-first CSS framework +- [Fontaine](https://github.com/nuxt-modules/fontaine): Font metric fallback +- [Pinceau](https://github.com/Tahul/pinceau): Adaptable styling framework +- [Nuxt UI](https://ui.nuxt.com): A UI Library for Modern Web Apps +- [Panda CSS](https://panda-css.com/docs/installation/nuxt): CSS-in-JS engine that generates atomic CSS at build time + +Nuxt modules provide you with a good developer experience out of the box, but remember that if your favorite tool doesn't have a module, it doesn't mean that you can't use it with Nuxt! You can configure it yourself for your own project. Depending on the tool, you might need to use a [Nuxt plugin](/docs/4.x/directory-structure/app/plugins) and/or [make your own module](/docs/4.x/guide/modules). Share them with the [community](/modules) if you do! + +### Easily Load Webfonts + +You can use [the Nuxt Google Fonts module](https://github.com/nuxt-modules/google-fonts) to load Google Fonts. + +If you are using [UnoCSS](https://unocss.dev/integrations/nuxt), note that it comes with a [web fonts presets](https://unocss.dev/presets/web-fonts) to conveniently load fonts from common providers, including Google Fonts and more. + +## Advanced + +### Transitions + +Nuxt comes with the same `` element that Vue has, and also has support for the experimental [View Transitions API](/docs/4.x/getting-started/transitions#view-transitions-api-experimental). + +:read-more{to="/docs/4.x/getting-started/transitions"} + +### Font Advanced Optimization + +We would recommend using [Fontaine](https://github.com/nuxt-modules/fontaine) to reduce your [CLS](https://web.dev/articles/cls). If you need something more advanced, consider creating a Nuxt module to extend the build process or the Nuxt runtime. + +::tip +Always remember to take advantage of the various tools and techniques available in the Web ecosystem at large to make styling your application easier and more efficient. Whether you're using native CSS, a preprocessor, postcss, a UI library or a module, Nuxt has got you covered. Happy styling! +:: + +### LCP Advanced Optimizations + +You can do the following to speed-up the download of your global CSS files: + +- Use a CDN so the files are physically closer to your users +- Compress your assets, ideally using Brotli +- Use HTTP2/HTTP3 for delivery +- Host your assets on the same domain (do not use a different subdomain) + +Most of these things should be done for you automatically if you're using modern platforms like Cloudflare, Netlify or Vercel. +You can find an LCP optimization guide on [web.dev](https://web.dev/articles/optimize-lcp). + +If all of your CSS is inlined by Nuxt, you can (experimentally) completely stop external CSS files from being referenced in your rendered HTML. +You can achieve that with a hook, that you can place in a module, or in your Nuxt configuration file. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + hooks: { + 'build:manifest': (manifest) => { + // find the app entry, css list + const css = Object.values(manifest).find(options => options.isEntry)?.css + if (css) { + // start from the end of the array and go to the beginning + for (let i = css.length - 1; i >= 0; i--) { + // if it starts with 'entry', remove it from the list + if (css[i].startsWith('entry')) { + css.splice(i, 1) + } + } + } + }, + }, +}) +``` diff --git a/reference/1.getting-started/07.routing.md b/reference/1.getting-started/07.routing.md new file mode 100644 index 0000000..4888d94 --- /dev/null +++ b/reference/1.getting-started/07.routing.md @@ -0,0 +1,153 @@ +--- +title: 'Routing' +description: Nuxt file-system routing creates a route for every file in the pages/ directory. +navigation.icon: i-lucide-milestone +--- + +One core feature of Nuxt is the file system router. Every Vue file inside the [`app/pages/`](/docs/4.x/directory-structure/app/pages) directory creates a corresponding URL (or route) that displays the contents of the file. By using dynamic imports for each page, Nuxt leverages code-splitting to ship the minimum amount of JavaScript for the requested route. + +## Pages + +Nuxt routing is based on [vue-router](https://router.vuejs.org) and generates the routes from every component created in the [`app/pages/` directory](/docs/4.x/directory-structure/app/pages), based on their filename. + +This file system routing uses naming conventions to create dynamic and nested routes: + +::code-group + +```bash [Directory Structure] +-| pages/ +---| about.vue +---| index.vue +---| posts/ +-----| [id].vue +``` + +```json [Generated Router File] +{ + "routes": [ + { + "path": "/about", + "component": "pages/about.vue" + }, + { + "path": "/", + "component": "pages/index.vue" + }, + { + "path": "/posts/:id", + "component": "pages/posts/[id].vue" + } + ] +} +``` + +:: + +:read-more{to="/docs/4.x/directory-structure/app/pages"} + +## Navigation + +The [``](/docs/4.x/api/components/nuxt-link) component links pages between them. It renders an `` tag with the `href` attribute set to the route of the page. Once the application is hydrated, page transitions are performed in JavaScript by updating the browser URL. This prevents full-page refreshes and allows for animated transitions. + +When a [``](/docs/4.x/api/components/nuxt-link) enters the viewport on the client side, Nuxt will automatically prefetch components and payload (generated pages) of the linked pages ahead of time, resulting in faster navigation. + +```vue [app/pages/index.vue] + +``` + +:read-more{to="/docs/4.x/api/components/nuxt-link"} + +## Route Parameters + +The [`useRoute()`](/docs/4.x/api/composables/use-route) composable can be used in a ` +``` + +:read-more{to="/docs/4.x/api/composables/use-route"} + +## Route Middleware + +Nuxt provides a customizable route middleware framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route. + +::note +Route middleware runs within the Vue part of your Nuxt app. Despite the similar name, they are completely different from server middleware, which are run in the Nitro server part of your app. +:: + +::important +Route middleware does **not** run for server routes (e.g. `/api/*`) or other server requests. To apply middleware to these requests, use [server middleware](/docs/4.x/directory-structure/server#server-middleware) instead. +:: + +There are three kinds of route middleware: + +1. Anonymous (or inline) route middleware, which are defined directly in the pages where they are used. +2. Named route middleware, which are placed in the [`app/middleware/`](/docs/4.x/directory-structure/app/middleware) directory and will be automatically loaded via asynchronous import when used on a page. (**Note**: The route middleware name is normalized to kebab-case, so `someMiddleware` becomes `some-middleware`.) +3. Global route middleware, which are placed in the [`app/middleware/`](/docs/4.x/directory-structure/app/middleware) directory (with a `.global` suffix) and will be automatically run on every route change. + +Example of an `auth` middleware protecting the `/dashboard` page: + +::code-group + +```ts twoslash [middleware/auth.ts] +function isAuthenticated (): boolean { return false } +// ---cut--- +export default defineNuxtRouteMiddleware((to, from) => { + // isAuthenticated() is an example method verifying if a user is authenticated + if (isAuthenticated() === false) { + return navigateTo('/login') + } +}) +``` + +```vue twoslash [pages/dashboard.vue] + + + +``` + +:: + +:read-more{to="/docs/4.x/directory-structure/app/middleware"} + +## Route Validation + +Nuxt offers route validation via the `validate` property in [`definePageMeta()`](/docs/4.x/api/utils/define-page-meta) in each page you wish to validate. + +The `validate` property accepts the `route` as an argument. You can return a boolean value to determine whether or not this is a valid route to be rendered with this page. If you return `false`, this will cause a 404 error. You can also directly return an object with `status`/`statusText` to customize the error returned. + +If you have a more complex use case, then you can use anonymous route middleware instead. + +```vue twoslash [pages/posts/[id\\].vue] + +``` + +:read-more{to="/docs/4.x/api/utils/define-page-meta"} diff --git a/reference/1.getting-started/08.seo-meta.md b/reference/1.getting-started/08.seo-meta.md new file mode 100644 index 0000000..dc57325 --- /dev/null +++ b/reference/1.getting-started/08.seo-meta.md @@ -0,0 +1,377 @@ +--- +title: SEO and Meta +description: Improve your Nuxt app's SEO with powerful head config, composables and components. +navigation.icon: i-lucide-file-search +--- + +Nuxt head tag management is powered by [Unhead](https://unhead.unjs.io). It provides sensible defaults, several powerful composables +and numerous configuration options to manage your app's head and SEO meta tags. + +## Nuxt Config + +Providing an [`app.head`](/docs/4.x/api/nuxt-config#head) property in your [`nuxt.config.ts`](/docs/4.x/directory-structure/nuxt-config) allows you to statically customize the head for your entire app. + +::important +This method does not allow you to provide reactive data. We recommend using `useHead()` in `app.vue`. +:: + +It's good practice to set tags here that won't change such as your site title default, language and favicon. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + head: { + title: 'Nuxt', // default fallback title + htmlAttrs: { + lang: 'en', + }, + link: [ + { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }, + ], + }, + }, +}) +``` + +You can also provide any of the keys listed below in [Types](/docs/4.x/getting-started/seo-meta#types). + +### Defaults Tags + +Some tags are provided by Nuxt by default to ensure your website works well out of the box. + +- `viewport`: `width=device-width, initial-scale=1` +- `charset`: `utf-8` + +While most sites won't need to override these defaults, you can update them using the keyed shortcuts. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + head: { + // update Nuxt defaults + charset: 'utf-16', + viewport: 'width=device-width, initial-scale=1, maximum-scale=1', + }, + }, +}) +``` + +## `useHead` + +The [`useHead`](/docs/4.x/api/composables/use-head) composable function supports reactive input, allowing you to manage your head tags programmatically. + +```vue twoslash [app/app.vue] + +``` + +We recommend taking a look at the [`useHead`](/docs/4.x/api/composables/use-head) and [`useHeadSafe`](/docs/4.x/api/composables/use-head-safe) composables. + +## `useSeoMeta` + +The [`useSeoMeta`](/docs/4.x/api/composables/use-seo-meta) composable lets you define your site's SEO meta tags as an object with full type safety. + +This helps you avoid typos and common mistakes, such as using `name` instead of `property`. + +```vue twoslash [app/app.vue] + +``` + +:read-more{to="/docs/4.x/api/composables/use-seo-meta"} + +## Components + +While using [`useHead`](/docs/4.x/api/composables/use-head) is recommended in all cases, you may have a personal preference for defining your head tags in your template using components. + +Nuxt provides the following components for this purpose: ``, `<Base>`, `<NoScript>`, `<Style>`, `<Meta>`, `<Link>`, `<Body>`, `<Html>` and `<Head>`. Note +the capitalization of these components ensuring we don't use invalid native HTML tags. + +`<Head>` and `<Body>` can accept nested meta tags (for aesthetic reasons) but this does not affect _where_ the nested meta tags are rendered in the final HTML. + +<!-- @case-police-ignore html --> + +```vue [app/app.vue] +<script setup lang="ts"> +const title = ref('Hello World') +</script> + +<template> + <div> + <Head> + <Title>{{ title }} + + + + +

{{ title }}

+ + +``` + +It's suggested to wrap your components in either a `` or `` components as tags will be deduped more intuitively. + +::warning +If you need to duplicate tags across client-server boundaries, apply a `key` attribute on the `` component. +:: + +## Types + +Below are the non-reactive types used for [`useHead`](/docs/4.x/api/composables/use-head), [`app.head`](/docs/4.x/api/nuxt-config#head) and components. + +```ts +interface MetaObject { + title?: string + titleTemplate?: string | ((title?: string) => string) + templateParams?: Record> + base?: Base + link?: Link[] + meta?: Meta[] + style?: Style[] + script?: Script[] + noscript?: Noscript[] + htmlAttrs?: HtmlAttributes + bodyAttrs?: BodyAttributes +} +``` + +See [@unhead/vue](https://github.com/unjs/unhead/blob/main/packages/vue/src/types/schema.ts) for more detailed types. + +## Features + +### Reactivity + +Reactivity is supported on all properties, by providing a computed value, a getter, or a reactive object. + +::code-group + + ```vue twoslash [useHead] + + ``` + + ```vue twoslash [useSeoMeta] + + ``` + + ```vue [app/Components] + + + + ``` + +:: + +### Title Template + +You can use the `titleTemplate` option to provide a dynamic template for customizing the title of your site. For example, you could add the name of your site to the title of every page. + +The `titleTemplate` can either be a string, where `%s` is replaced with the title, or a function. + +If you want to use a function (for full control), then this cannot be set in your `nuxt.config`. It is recommended instead to set it within your `app.vue` file where it will apply to all pages on your site: + +::code-group + + ```vue twoslash [useHead] + + ``` + +:: + +Now, if you set the title to `My Page` with [`useHead`](/docs/4.x/api/composables/use-head) on another page of your site, the title would appear as 'My Page - Site Title' in the browser tab. You could also pass `null` to default to 'Site Title'. + +### Template Params + +You can use `templateParams` to provide additional placeholders in your `titleTemplate` besides the default `%s`. This allows for more dynamic title generation. + +::code-group + + ```vue twoslash [useHead] + + ``` + +:: + +### Body Tags + +You can use the `tagPosition: 'bodyClose'` option on applicable tags to append them to the end of the `` tag. + +For example: + +```vue twoslash + +``` + +## Examples + +### With `definePageMeta` + +Within your [`app/pages/` directory](/docs/4.x/directory-structure/app/pages), you can use `definePageMeta` along with [`useHead`](/docs/4.x/api/composables/use-head) to set metadata based on the current route. + +For example, you can first set the current page title (this is extracted at build time via a macro, so it can't be set dynamically): + +```vue twoslash [pages/some-page.vue] + +``` + +And then in your layout file, you might use the route's metadata you have previously set: + +```vue twoslash [layouts/default.vue] + +``` + +:link-example{to="/docs/4.x/examples/features/meta-tags"} + +:read-more{to="/docs/4.x/directory-structure/app/pages/#page-metadata"} + +### Dynamic Title + +In the example below, `titleTemplate` is set either as a string with the `%s` placeholder or as a `function`, which allows greater flexibility in setting the page title dynamically for each route of your Nuxt app: + +```vue twoslash [app/app.vue] + +``` + +```vue twoslash [app/app.vue] + +``` + +`nuxt.config` is also used as an alternative way of setting the page title. However, `nuxt.config` does not allow the page title to be dynamic. Therefore, it is recommended to use `titleTemplate` in the `app.vue` file to add a dynamic title, which is then applied to all routes of your Nuxt app. + +### External CSS + +The example below shows how you might enable Google Fonts using either the `link` property of the [`useHead`](/docs/4.x/api/composables/use-head) composable or using the `` component: + +::code-group + + ```vue twoslash [useHead] + + ``` + + ```vue [app/Components] + + ``` + +:: diff --git a/reference/1.getting-started/09.transitions.md b/reference/1.getting-started/09.transitions.md new file mode 100644 index 0000000..caacabc --- /dev/null +++ b/reference/1.getting-started/09.transitions.md @@ -0,0 +1,578 @@ +--- +title: 'Transitions' +description: Apply transitions between pages and layouts with Vue or native browser View Transitions. +navigation.icon: i-lucide-toggle-right +--- + +::note +Nuxt leverages Vue's [``](https://vuejs.org/guide/built-ins/transition#the-transition-component) component to apply transitions between pages and layouts. +:: + +## Page Transitions + +You can enable page transitions to apply an automatic transition for all your [pages](/docs/4.x/directory-structure/app/pages). + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + pageTransition: { name: 'page', mode: 'out-in' }, + }, +}) +``` + +::note +If you are changing layouts as well as page, the page transition you set here will not run. Instead, you should set a [layout transition](/docs/4.x/getting-started/transitions#layout-transitions). +:: + +To start adding transition between your pages, add the following CSS to your [`app.vue`](/docs/4.x/directory-structure/app/app): + +::code-group + +```vue [app/app.vue] + + + +``` + +```vue [app/pages/index.vue] + +``` + +```vue [app/pages/about.vue] + +``` + +:: + +This produces the following result when navigating between pages: + + + +To set a different transition for a page, set the `pageTransition` key in [`definePageMeta`](/docs/4.x/api/utils/define-page-meta) of the page: + +::code-group + +```vue twoslash [pages/about.vue] + +``` + +```vue [app/app.vue] + + + +``` + +:: + +Moving to the about page will add the 3d rotation effect: + + + +## Layout Transitions + +You can enable layout transitions to apply an automatic transition for all your [layouts](/docs/4.x/directory-structure/app/layouts). + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + layoutTransition: { name: 'layout', mode: 'out-in' }, + }, +}) +``` + +To start adding transition between your pages and layouts, add the following CSS to your [`app.vue`](/docs/4.x/directory-structure/app/app): + +::code-group + +```vue [app/app.vue] + + + +``` + +```vue [app/layouts/default.vue] + + + +``` + +```vue [app/layouts/orange.vue] + + + +``` + +```vue [app/pages/index.vue] + +``` + +```vue [app/pages/about.vue] + + + +``` + +:: + +This produces the following result when navigating between pages: + + + +Similar to `pageTransition`, you can apply a custom `layoutTransition` to the page component using `definePageMeta`: + +```vue twoslash [pages/about.vue] + +``` + +## Global Settings + +You can customize these default transition names globally using `nuxt.config`. + +Both `pageTransition` and `layoutTransition` keys accept [`TransitionProps`](https://vuejs.org/api/built-in-components#transition) as JSON serializable values where you can pass the `name`, `mode` and other valid transition-props of the custom CSS transition. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + pageTransition: { + name: 'fade', + mode: 'out-in', // default + }, + layoutTransition: { + name: 'slide', + mode: 'out-in', // default + }, + }, +}) +``` + +::warning +If you change the `name` property, you also have to rename the CSS classes accordingly. +:: + +To override the global transition property, use the `definePageMeta` to define page or layout transitions for a single Nuxt page and override any page or layout transitions that are defined globally in `nuxt.config` file. + +```vue twoslash [pages/some-page.vue] + +``` + +## Disable Transitions + +`pageTransition` and `layoutTransition` can be disabled for a specific route: + +```vue twoslash [pages/some-page.vue] + +``` + +Or globally in the `nuxt.config`: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + pageTransition: false, + layoutTransition: false, + }, +}) +``` + +## JavaScript Hooks + +For advanced use-cases, you can use JavaScript hooks to create highly dynamic and custom transitions for your Nuxt pages. + +This way presents perfect use-cases for JavaScript animation libraries such as [GSAP](https://gsap.com). + +```vue twoslash [pages/some-page.vue] + +``` + +::tip +Learn more about additional [JavaScript hooks](https://vuejs.org/guide/built-ins/transition#javascript-hooks) available in the `Transition` component. +:: + +## Dynamic Transitions + +To apply dynamic transitions using conditional logic, you can leverage inline [middleware](/docs/4.x/directory-structure/app/middleware) to assign a different transition name to `to.meta.pageTransition`. + +::code-group + +```vue twoslash [pages/[id\\].vue] + + + + + +``` + +```vue [app/layouts/default.vue] + + + +``` + +:: + +The page now applies the `slide-left` transition when going to the next id and `slide-right` for the previous: + + + +## Transition with NuxtPage + +When `` is used in `app.vue`, transitions can be configured with the `transition` prop to activate transitions globally. + +```vue [app/app.vue] + +``` + +::note +Remember, this page transition cannot be overridden with `definePageMeta` on individual pages. +:: + +## View Transitions API (experimental) + +Nuxt ships with an experimental implementation of the [**View Transitions API**](https://developer.chrome.com/docs/web-platform/view-transitions) (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API)). This is an exciting new way to implement native browser transitions which (among other things) have the ability to transition between unrelated elements on different pages. + +You can check a demo [on StackBlitz](https://stackblitz.com/edit/nuxt-view-transitions). + +The Nuxt integration can be enabled with the `experimental.viewTransition` option in your configuration file: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + experimental: { + viewTransition: true, + }, +}) +``` + +The possible values are: `false`, `true`, or `'always'`. + +If set to true, Nuxt will not apply transitions if the user's browser matches `prefers-reduced-motion: reduce` (recommended). If set to `always`, Nuxt will always apply the transition and it is up to you to respect the user's preference. + +By default, view transitions are enabled for all [pages](/docs/4.x/directory-structure/app/pages), but you can set a different global default. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + // Disable view transitions globally, and opt-in on a per page basis + viewTransition: false, + }, +}) +``` + +It is possible to override the default `viewTransition` value for a page by setting the `viewTransition` key in [`definePageMeta`](/docs/4.x/api/utils/define-page-meta) of the page: + +```vue twoslash [pages/about.vue] + +``` + +::warning +Overriding view transitions on a per-page basis will only have an effect if you have enabled the `experimental.viewTransition` option. +:: + +### View Transition Types + +[View transition types](https://developer.chrome.com/blog/view-transitions-update-io24#view-transition-types) allow you to apply different CSS animations depending on the type of navigation. This is useful for creating asymmetric transitions (e.g., a different animation when navigating forward vs. backward). + +Types are set on the [`ViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) and can be targeted in CSS using the [`:active-view-transition-type()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:active-view-transition-type) pseudo-class selector. + +You can set default types globally in your `nuxt.config.ts`: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + app: { + viewTransition: { + enabled: true, + types: ['slide'], + }, + }, +}) +``` + +Or configure types per-page using `definePageMeta`. Per-page types support both static arrays and functions for dynamic behavior: + +```vue twoslash [pages/detail.vue] + +``` + +You can also use functions for `types`, `toTypes`, and `fromTypes` in `definePageMeta` to determine types dynamically based on the route: + +```vue twoslash [pages/[id].vue] + +``` + +Then target these types in your CSS: + +```css +/* Default crossfade */ +::view-transition-old(root), +::view-transition-new(root) { + animation-duration: 0.3s; +} + +/* Slide left animation */ +html:active-view-transition-type(slide-left) { + &::view-transition-old(root) { + animation: slide-out-left 0.3s ease-in-out; + } + &::view-transition-new(root) { + animation: slide-in-right 0.3s ease-in-out; + } +} + +/* Slide right animation */ +html:active-view-transition-type(slide-right) { + &::view-transition-old(root) { + animation: slide-out-right 0.3s ease-in-out; + } + &::view-transition-new(root) { + animation: slide-in-left 0.3s ease-in-out; + } +} +``` + +::note +Function values for `types`, `toTypes`, and `fromTypes` only work in `definePageMeta`, not in `nuxt.config.ts` (where only static `string[]` is supported). +:: + +The `page:view-transition:start` hook provides access to the [`ViewTransition`](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition) object, which includes a [`types`](https://developer.mozilla.org/en-US/docs/Web/API/ViewTransition/types) property (`ViewTransitionTypeSet`) that can be read or modified at runtime: + +```ts [plugins/view-transition.client.ts] +export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.hook('page:view-transition:start', (transition) => { + // Read or modify types at runtime + console.log([...transition.types]) + }) +}) +``` + +If you are also using Vue transitions like `pageTransition` and `layoutTransition` (see above) to achieve the same result as the new View Transitions API, then you may wish to _disable_ Vue transitions if the user's browser supports the newer, native web API. You can do this by creating `~/middleware/disable-vue-transitions.global.ts` with the following contents: + +```ts +export default defineNuxtRouteMiddleware((to) => { + if (import.meta.server || !document.startViewTransition) { + return + } + + // Disable built-in Vue transitions + to.meta.pageTransition = false + to.meta.layoutTransition = false +}) +``` + +### Known Issues + +- If you perform data fetching within your page setup functions, you may wish to reconsider using this feature for the moment. (By design, View Transitions completely freeze DOM updates whilst they are taking place.) We're looking at restricting the View Transition to the final moments before `` resolves, but in the interim you may want to consider carefully whether to adopt this feature if this describes you. diff --git a/reference/1.getting-started/10.data-fetching.md b/reference/1.getting-started/10.data-fetching.md new file mode 100644 index 0000000..f60acff --- /dev/null +++ b/reference/1.getting-started/10.data-fetching.md @@ -0,0 +1,817 @@ +--- +title: 'Data Fetching' +description: Nuxt provides composables to handle data fetching within your application. +navigation.icon: i-lucide-cable +--- + +Nuxt comes with two composables and a built-in library to perform data-fetching in browser or server environments: `useFetch`, [`useAsyncData`](/docs/4.x/api/composables/use-async-data) and `$fetch`. + +In a nutshell: + +- [`$fetch`](/docs/4.x/api/utils/dollarfetch) is the simplest way to make a network request. +- [`useFetch`](/docs/4.x/api/composables/use-fetch) is a wrapper around `$fetch` that fetches data only once in [universal rendering](/docs/4.x/guide/concepts/rendering#universal-rendering). +- [`useAsyncData`](/docs/4.x/api/composables/use-async-data) is similar to `useFetch` but offers more fine-grained control. + +Both `useFetch` and `useAsyncData` share a common set of options and patterns that we will detail in the last sections. + +## The need for `useFetch` and `useAsyncData` + +Nuxt is a framework which can run isomorphic (or universal) code in both server and client environments. If the [`$fetch` function](/docs/4.x/api/utils/dollarfetch) is used to perform data fetching in the setup function of a Vue component, this may cause data to be fetched twice, once on the server (to render the HTML) and once again on the client (when the HTML is hydrated). This can cause hydration issues, increase the time to interactivity and cause unpredictable behavior. + +The [`useFetch`](/docs/4.x/api/composables/use-fetch) and [`useAsyncData`](/docs/4.x/api/composables/use-async-data) composables solve this problem by ensuring that if an API call is made on the server, the data is forwarded to the client in the payload. + +The payload is a JavaScript object accessible through [`useNuxtApp().payload`](/docs/4.x/api/composables/use-nuxt-app#payload). It is used on the client to avoid refetching the same data when the code is executed in the browser [during hydration](/docs/4.x/guide/concepts/rendering#universal-rendering). + +::tip +Use the [Nuxt DevTools](https://devtools.nuxt.com) to inspect this data in the **Payload tab**. +:: + +```vue [app/app.vue] + + + +``` + +In the example above, `useFetch` would make sure that the request would occur in the server and is properly forwarded to the browser. `$fetch` has no such mechanism and is a better option to use when the request is solely made from the browser. + +### Suspense + +Nuxt uses Vue's [``](https://vuejs.org/guide/built-ins/suspense) component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-call basis. + +::note +You can add the [``](/docs/4.x/api/components/nuxt-loading-indicator) to add a progress bar between page navigations. +:: + +## `$fetch` + +Nuxt includes the [ofetch](https://github.com/unjs/ofetch) library, and is auto-imported as the `$fetch` alias globally across your application. + +```vue twoslash [pages/todos.vue] + +``` + +::warning +Beware that using only `$fetch` will not provide [network calls de-duplication and navigation prevention](/docs/4.x/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata). :br +It is recommended to use `$fetch` for client-side interactions (event-based) or combined with [`useAsyncData`](/docs/4.x/getting-started/data-fetching#useasyncdata) when fetching the initial component data. +:: + +::read-more{to="/docs/4.x/api/utils/dollarfetch"} +Read more about `$fetch`. +:: + +### Pass Client Headers to the API + +When calling `useFetch` on the server, Nuxt will use [`useRequestFetch`](/docs/4.x/api/composables/use-request-fetch) to proxy client headers and cookies (with the exception of headers not meant to be forwarded, like `host`). + +```vue + +``` + +```ts +// /api/echo.ts +export default defineEventHandler(event => parseCookies(event)) +``` + +Alternatively, the example below shows how to use [`useRequestHeaders`](/docs/4.x/api/composables/use-request-headers) to access and send cookies to the API from a server-side request (originating on the client). Using an isomorphic `$fetch` call, we ensure that the API endpoint has access to the same `cookie` header originally sent by the user's browser. This is only necessary if you aren't using `useFetch`. + +```vue + +``` + +::tip +You can also use [`useRequestFetch`](/docs/4.x/api/composables/use-request-fetch) to proxy headers to the call automatically. +:: + +::caution +Be very careful before proxying headers to an external API and just include headers that you need. Not all headers are safe to be bypassed and might introduce unwanted behavior. Here is a list of common headers that are NOT to be proxied: + +- `host`, `accept` +- `content-length`, `content-md5`, `content-type` +- `x-forwarded-host`, `x-forwarded-port`, `x-forwarded-proto` +- `cf-connecting-ip`, `cf-ray` +:: + +## `useFetch` + +The [`useFetch`](/docs/4.x/api/composables/use-fetch) composable uses `$fetch` under-the-hood to make SSR-safe network calls in the setup function. + +```vue twoslash [app/app.vue] + + + +``` + +This composable is a wrapper around the [`useAsyncData`](/docs/4.x/api/composables/use-async-data) composable and `$fetch` utility. + +:video-accordion{title="Watch a video from Alexander Lichter to avoid using useFetch the wrong way" videoId="njsGVmcWviY"} + +:read-more{to="/docs/4.x/api/composables/use-fetch"} + +:link-example{to="/docs/4.x/examples/features/data-fetching"} + +## `useAsyncData` + +The `useAsyncData` composable is responsible for wrapping async logic and returning the result once it is resolved. + +::tip +`useFetch(url)` is nearly equivalent to `useAsyncData(url, () => event.$fetch(url))`. :br +It's developer experience sugar for the most common use case. (You can find out more about `event.fetch` at [`useRequestFetch`](/docs/4.x/api/composables/use-request-fetch).) +:: + +:video-accordion{title="Watch a video from Alexander Lichter to dig deeper into the difference between useFetch and useAsyncData" videoId="0X-aOpSGabA"} + +There are some cases when using the [`useFetch`](/docs/4.x/api/composables/use-fetch) composable is not appropriate, for example when a CMS or a third-party provide their own query layer. In this case, you can use [`useAsyncData`](/docs/4.x/api/composables/use-async-data) to wrap your calls and still keep the benefits provided by the composable. + +```vue [app/pages/users.vue] + +``` + +::note +The first argument of [`useAsyncData`](/docs/4.x/api/composables/use-async-data) is a unique key used to cache the response of the second argument, the querying function. This key can be ignored by directly passing the querying function, the key will be auto-generated. +:br :br +Since the autogenerated key only takes into account the file and line where `useAsyncData` is invoked, it is recommended to always create your own key to avoid unwanted behavior, like when you are creating your own custom composable wrapping `useAsyncData`. +:br :br +Setting a key can be useful to share the same data between components using [`useNuxtData`](/docs/4.x/api/composables/use-nuxt-data) or to [refresh specific data](/docs/4.x/api/utils/refresh-nuxt-data#refresh-specific-data). +:: + +```vue [app/pages/users/[id\\].vue] + +``` + +The `useAsyncData` composable is a great way to wrap and wait for multiple `$fetch` requests to be completed, and then process the results. + +```vue + +``` + +::note +`useAsyncData` is for fetching and caching data, not triggering side effects like calling Pinia actions, as this can cause unintended behavior such as repeated executions with nullish values. If you need to trigger side effects, use the [`callOnce`](/docs/4.x/api/utils/call-once) utility to do so. + +```vue + +``` +:: + +::read-more{to="/docs/4.x/api/composables/use-async-data"} +Read more about `useAsyncData`. +:: + +## Return Values + +`useFetch` and `useAsyncData` have the same return values listed below. + +- `data`: the result of the asynchronous function that is passed in. +- `refresh`/`execute`: a function that can be used to refresh the data returned by the `handler` function. +- `clear`: a function that can be used to set `data` to `undefined` (or the value of `options.default()` if provided), set `error` to `undefined`, set `status` to `idle`, and mark any currently pending requests as cancelled. +- `error`: an error object if the data fetching failed. +- `status`: a string indicating the status of the data request (`"idle"`, `"pending"`, `"success"`, `"error"`). + +::note +`data`, `error` and `status` are Vue refs accessible with `.value` in ` + + +``` + +You can alternatively use [`useLazyFetch`](/docs/4.x/api/composables/use-lazy-fetch) and `useLazyAsyncData` as convenient methods to perform the same. + +```vue twoslash + +``` + +::read-more{to="/docs/4.x/api/composables/use-lazy-fetch"} +Read more about `useLazyFetch`. +:: + +::read-more{to="/docs/4.x/api/composables/use-lazy-async-data"} +Read more about `useLazyAsyncData`. +:: + +:video-accordion{title="Watch a video from Vue School on blocking vs. non-blocking (lazy) requests" videoId="1022000555" platform="vimeo"} + +### Client-only fetching + +By default, data fetching composables will perform their asynchronous function on both client and server environments. Set the `server` option to `false` to only perform the call on the client-side. On initial load, the data will not be fetched before hydration is complete so you have to handle a pending state, though on subsequent client-side navigation the data will be awaited before loading the page. + +Combined with the `lazy` option, this can be useful for data that is not needed on the first render (for example, non-SEO sensitive data). + +```ts twoslash +/* This call is performed before hydration */ +const articles = await useFetch('/api/article') + +/* This call will only be performed on the client */ +const { status, data: comments } = useFetch('/api/comments', { + lazy: true, + server: false, +}) +``` + +The `useFetch` composable is meant to be invoked in setup method or called directly at the top level of a function in lifecycle hooks, otherwise you should use [`$fetch` method](/docs/4.x/getting-started/data-fetching#fetch). + +### Minimize payload size + +The `pick` option helps you to minimize the payload size stored in your HTML document by only selecting the fields that you want returned from the composables. + +```vue + + + +``` + +If you need more control or map over several objects, you can use the `transform` function to alter the result of the query. + +```ts +const { data: mountains } = await useFetch('/api/mountains', { + transform: (mountains) => { + return mountains.map(mountain => ({ title: mountain.title, description: mountain.description })) + }, +}) +``` + +::note +Both `pick` and `transform` don't prevent the unwanted data from being fetched initially. But they will prevent unwanted data from being added to the payload transferred from server to client. +:: + +:video-accordion{title="Watch a video from Vue School on minimizing payload size" videoId="1026410430" platform="vimeo"} + +### Caching and refetching + +#### Keys + +[`useFetch`](/docs/4.x/api/composables/use-fetch) and [`useAsyncData`](/docs/4.x/api/composables/use-async-data) use keys to prevent refetching the same data. + +- [`useFetch`](/docs/4.x/api/composables/use-fetch) uses the provided URL as a key. Alternatively, a `key` value can be provided in the `options` object passed as a last argument. +- [`useAsyncData`](/docs/4.x/api/composables/use-async-data) uses its first argument as a key if it is a string. If the first argument is the handler function that performs the query, then a key that is unique to the file name and line number of the instance of `useAsyncData` will be generated for you. + +::tip +To get the cached data by key, you can use [`useNuxtData`](/docs/4.x/api/composables/use-nuxt-data) +:: + +:video-accordion{title="Watch a video from Vue School on caching data with the key option" videoId="1026410044" platform="vimeo"} + +#### Shared State and Option Consistency + +When multiple components use the same key with `useAsyncData` or `useFetch`, they will share the same `data`, `error` and `status` refs. This ensures consistency across components but requires some options to be consistent. + +The following options **must be consistent** across all calls with the same key: +- `handler` function +- `deep` option +- `transform` function +- `pick` array +- `getCachedData` function +- `default` value + +```ts +// ❌ This will trigger a development warning +const { data: users1 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { deep: false }) +const { data: users2 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { deep: true }) +``` + +The following options **can safely differ** without triggering warnings: +- `server` +- `lazy` +- `immediate` +- `dedupe` +- `watch` + +```ts +// ✅ This is allowed +const { data: users1 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { immediate: true }) +const { data: users2 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { immediate: false }) +``` + +If you need independent instances, use different keys: + +```ts +// These are completely independent instances +const { data: users1 } = useAsyncData('users-1', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })) +const { data: users2 } = useAsyncData('users-2', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })) +``` + +#### Reactive Keys + +You can use computed refs, plain refs or getter functions as keys, allowing for dynamic data fetching that automatically updates when dependencies change: + +```ts +// Using a computed property as a key +const userId = ref('123') +const { data: user } = useAsyncData( + computed(() => `user-${userId.value}`), + () => fetchUser(userId.value), +) + +// When userId changes, the data will be automatically refetched +// and the old data will be cleaned up if no other components use it +userId.value = '456' +``` + +#### Refresh and execute + +If you want to fetch or refresh data manually, use the `execute` or `refresh` function provided by the composables. + +```vue twoslash + + + +``` + +The `execute` function is an alias for `refresh` that works in exactly the same way but is more semantic for cases when the fetch is [not immediate](/docs/4.x/getting-started/data-fetching#not-immediate). + +::tip +To globally refetch or invalidate cached data, see [`clearNuxtData`](/docs/4.x/api/utils/clear-nuxt-data) and [`refreshNuxtData`](/docs/4.x/api/utils/refresh-nuxt-data). +:: + +#### Clear + +If you want to clear the data provided, for whatever reason, without needing to know the specific key to pass to `clearNuxtData`, you can use the `clear` function provided by the composables. + +```vue twoslash + +``` + +#### Watch + +To re-run your fetching function each time other reactive values in your application change, use the `watch` option. You can use it for one or multiple _watchable_ elements. + +```vue twoslash + +``` + +Note that **watching a reactive value won't change the URL fetched**. For example, this will keep fetching the same initial ID of the user because the URL is constructed at the moment the function is invoked. + +```vue + +``` + +If you need to change the URL based on a reactive value, you may want to use a [computed URL](/docs/4.x/getting-started/data-fetching#computed-url) instead. + +When reactive fetch options are provided, they'll be automatically watched and trigger refetches. In some cases, it can be useful to opt-out of this behavior by specifying `watch: false`. + +```ts +const id = ref(1) + +// Won't automatically refetch when id changes +const { data, execute } = await useFetch('/api/users', { + query: { id }, // id is watched by default + watch: false, // disables automatic watching of id +}) + +// doesn't trigger refetch +id.value = 2 +``` + +#### Computed URL + +Sometimes you may need to compute a URL from reactive values, and refresh the data each time these change. Instead of juggling your way around, you can attach each param as a reactive value. Nuxt will automatically use the reactive value and re-fetch each time it changes. + +```vue + +``` + +In the case of more complex URL construction, you may use a callback as a [computed getter](https://vuejs.org/guide/essentials/computed) that returns the URL string. + +Every time a dependency changes, the data will be fetched using the newly constructed URL. Combine this with [not-immediate](/docs/4.x/getting-started/data-fetching#not-immediate), and you can wait until the reactive element changes before fetching. + +```vue + + + +``` + +If you need to force a refresh when other reactive values change, you can also [watch other values](/docs/4.x/getting-started/data-fetching#watch). + +### Not immediate + +The `useFetch` composable will start fetching data the moment is invoked. You may prevent this by setting `immediate: false`, for example, to wait for user interaction. + +With that, you will need both the `status` to handle the fetch lifecycle, and `execute` to start the data fetch. + +```vue + + + +``` + +For finer control, the `status` variable can be: + +- `idle` when the fetch hasn't started +- `pending` when a fetch has started but not yet completed +- `error` when the fetch fails +- `success` when the fetch is completed successfully + +## Passing Headers and Cookies + +When we call `$fetch` in the browser, user headers like `cookie` will be directly sent to the API. + +Normally, during server-side-rendering, due to security considerations, the `$fetch` wouldn't include the user's browser cookies, nor pass on cookies from the fetch response. + +However, when calling `useFetch` with a relative URL on the server, Nuxt will use [`useRequestFetch`](/docs/4.x/api/composables/use-request-fetch) to proxy headers and cookies (with the exception of headers not meant to be forwarded, like `host`). + +### Pass Cookies From Server-side API Calls on SSR Response + + If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself. + +```ts [app/composables/fetch.ts] +import type { H3Event } from 'h3' + +export const fetchWithCookie = async (event: H3Event, url: string) => { + /* Get the response from the server endpoint */ + const res = await $fetch.raw(url) + /* Get the cookies from the response */ + const cookies = res.headers.getSetCookie() + /* Attach each cookie to our incoming Request */ + for (const cookie of cookies) { + event.res.headers.append('set-cookie', cookie) + } + /* Return the data of the response */ + return res._data +} +``` + +```vue + +``` + +## Options API Support + +Nuxt provides a way to perform `asyncData` fetching within the Options API. You must wrap your component definition within `defineNuxtComponent` for this to work. + +```vue + +``` + +::note +Using ` +``` + +### Custom serializer function + +To customize the serialization behavior, you can define a `toJSON` function on your returned object. If you define a `toJSON` method, Nuxt will respect the return type of the function and will not try to convert the types. + +```ts [server/api/bar.ts] +export default defineEventHandler(() => { + const data = { + createdAt: new Date(), + + toJSON () { + return { + createdAt: { + year: this.createdAt.getFullYear(), + month: this.createdAt.getMonth(), + day: this.createdAt.getDate(), + }, + } + }, + } + return data +}) +``` + +```vue [app/app.vue] + +``` + +### Using an alternative serializer + +Nuxt does not currently support an alternative serializer to `JSON.stringify`. However, you can return your payload as a normal string and utilize the `toJSON` method to maintain type safety. + +In the example below, we use [superjson](https://github.com/flightcontrolhq/superjson) as our serializer. + +```ts [server/api/superjson.ts] +import superjson from 'superjson' + +export default defineEventHandler(() => { + const data = { + createdAt: new Date(), + + // Workaround the type conversion + toJSON () { + return this + }, + } + + // Serialize the output to string, using superjson + return superjson.stringify(data) as unknown as typeof data +}) +``` + +```vue [app/app.vue] + +``` + +## Recipes + +### Consuming SSE (Server-Sent Events) via POST request + +::tip +If you're consuming SSE via GET request, you can use [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or VueUse composable [`useEventSource`](https://vueuse.org/core/useeventsource/). +:: + +When consuming SSE via POST request, you need to handle the connection manually. Here's how you can do it: + +```ts +// Make a POST request to the SSE endpoint +const response = await $fetch('/chats/ask-ai', { + method: 'POST', + body: { + query: 'Hello AI, how are you?', + }, + responseType: 'stream', +}) + +// Create a new ReadableStream from the response with TextDecoderStream to get the data as text +const reader = response.pipeThrough(new TextDecoderStream()).getReader() + +// Read the chunk of data as we get it +while (true) { + const { value, done } = await reader.read() + + if (done) { break } + + console.log('Received:', value) +} +``` + +### Making parallel requests + +When requests don't rely on each other, you can make them in parallel with `Promise.all()` to boost performance. + +```ts +const { data } = await useAsyncData((_nuxtApp, { signal }) => { + return Promise.all([ + $fetch('/api/comments/', { signal }), + $fetch('/api/author/12', { signal }), + ]) +}) + +const comments = computed(() => data.value?.[0]) +const author = computed(() => data.value?.[1]) +``` + +:video-accordion{title="Watch a video from Vue School on parallel data fetching" videoId="1024262536" platform="vimeo"} diff --git a/reference/1.getting-started/11.state-management.md b/reference/1.getting-started/11.state-management.md new file mode 100644 index 0000000..0af6332 --- /dev/null +++ b/reference/1.getting-started/11.state-management.md @@ -0,0 +1,230 @@ +--- +title: 'State Management' +description: Nuxt provides powerful state management libraries and the useState composable to create a reactive and SSR-friendly shared state. +navigation.icon: i-lucide-database +--- + +Nuxt provides the [`useState`](/docs/4.x/api/composables/use-state) composable to create a reactive and SSR-friendly shared state across components. + +[`useState`](/docs/4.x/api/composables/use-state) is an SSR-friendly [`ref`](https://vuejs.org/api/reactivity-core#ref) replacement. Its value will be preserved after server-side rendering (during client-side hydration) and shared across all components using a unique key. + +:video-accordion{title="Watch a video from Alexander Lichter about why and when to use useState" videoId="mv0WcBABcIk"} + +::important +Because the data inside [`useState`](/docs/4.x/api/composables/use-state) will be serialized to JSON, it is important that it does not contain anything that cannot be serialized, such as classes, functions or symbols. +:: + +::read-more{to="/docs/4.x/api/composables/use-state"} +Read more about `useState` composable. +:: + +## Best Practices + +::warning +Never define `const state = ref()` outside of ` + + +``` + +:link-example{to="/docs/4.x/examples/features/state-management"} + +::note +To globally invalidate cached state, see [`clearNuxtState`](/docs/4.x/api/utils/clear-nuxt-state) util. +:: + +### Initializing State + +Most of the time, you will want to initialize your state with data that resolves asynchronously. You can use the [`app.vue`](/docs/4.x/directory-structure/app/app) component with the [`callOnce`](/docs/4.x/api/utils/call-once) util to do so. + +```vue twoslash [app/app.vue] + +``` + +::tip +This is similar to the [`nuxtServerInit` action](https://v2.nuxt.com/docs/directory-structure/store/#the-nuxtserverinit-action) in Nuxt 2, which allows filling the initial state of your store server-side before rendering the page. +:: + +:read-more{to="/docs/4.x/api/utils/call-once"} + +### Usage with Pinia + +In this example, we leverage the [Pinia module](/modules/pinia) to create a global store and use it across the app. + +::important +Make sure to install the Pinia module with `npx nuxt module add pinia` or follow the [module's installation steps](https://pinia.vuejs.org/ssr/nuxt.html#Installation). +:: + +::code-group +```ts [app/stores/website.ts] +export const useWebsiteStore = defineStore('websiteStore', { + state: () => ({ + name: '', + description: '', + }), + actions: { + async fetch () { + const infos = await $fetch('https://api.nuxt.com/modules/pinia') + + this.name = infos.name + this.description = infos.description + }, + }, +}) +``` +```vue [app/app.vue] + + + +``` +:: + +## Advanced Usage + +::code-group +```ts [app/composables/locale.ts] +import type { Ref } from 'vue' + +export const useLocale = () => { + return useState('locale', () => useDefaultLocale().value) +} + +export const useDefaultLocale = (fallback = 'en-US') => { + const locale = ref(fallback) + if (import.meta.server) { + const reqLocale = useRequestHeaders()['accept-language']?.split(',')[0] + if (reqLocale) { + locale.value = reqLocale + } + } else if (import.meta.client) { + const navLang = navigator.language + if (navLang) { + locale.value = navLang + } + } + return locale +} + +export const useLocales = () => { + const locale = useLocale() + const locales = ref([ + 'en-US', + 'en-GB', + // ..., + 'ja-JP-u-ca-japanese', + ]) + if (!locales.value.includes(locale.value)) { + locales.value.unshift(locale.value) + } + return locales +} + +export const useLocaleDate = (date: Ref | Date, locale = useLocale()) => { + return computed(() => new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(unref(date))) +} +``` + +```vue [app/app.vue] + + + +``` +:: + +:link-example{to="/docs/4.x/examples/advanced/locale"} + +## Shared State + +By using [auto-imported composables](/docs/4.x/directory-structure/app/composables) we can define global type-safe states and import them across the app. + +```ts twoslash [composables/states.ts] +export const useColor = () => useState('color', () => 'pink') +``` + +```vue [app/app.vue] + + + +``` + +:video-accordion{title="Watch a video from Daniel Roe on how to deal with global state and SSR in Nuxt" videoId="dZSNW07sO-A"} + +## Using third-party libraries + +Nuxt **used to rely** on the Vuex library to provide global state management. If you are migrating from Nuxt 2, please head to [the migration guide](/docs/4.x/migration/configuration#vuex). + +Nuxt is not opinionated about state management, so feel free to choose the right solution for your needs. There are multiple integrations with the most popular state management libraries, including: + +- [Pinia](/modules/pinia) - the official Vue recommendation +- [Harlem](/modules/harlem) - immutable global state management +- [XState](/modules/xstate) - state machine approach with tools for visualizing and testing your state logic diff --git a/reference/1.getting-started/12.error-handling.md b/reference/1.getting-started/12.error-handling.md new file mode 100644 index 0000000..92794a0 --- /dev/null +++ b/reference/1.getting-started/12.error-handling.md @@ -0,0 +1,241 @@ +--- +title: 'Error Handling' +description: 'Learn how to catch and handle errors in Nuxt.' +navigation.icon: i-lucide-bug-off +--- + +Nuxt is a full-stack framework, which means there are several sources of unpreventable user runtime errors that can happen in different contexts: + +- Errors during the Vue rendering lifecycle (SSR & CSR) +- Server and client startup errors (SSR + CSR) +- Errors during Nitro server lifecycle ([`server/`](/docs/4.x/directory-structure/server) directory) +- Errors downloading JS chunks + +::tip +**SSR** stands for **Server-Side Rendering** and **CSR** for **Client-Side Rendering**. +:: + +## Vue Errors + +You can hook into Vue errors using [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle#onerrorcaptured). + +In addition, Nuxt provides a [`vue:error`](/docs/4.x/api/advanced/hooks#app-hooks-runtime) hook that will be called if any errors propagate up to the top level. + +If you are using an error reporting framework, you can provide a global handler through [`vueApp.config.errorHandler`](https://vuejs.org/api/application#app-config-errorhandler). It will receive all Vue errors, even if they are handled. + +```ts twoslash [plugins/error-handler.ts] +export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.vueApp.config.errorHandler = (error, instance, info) => { + // handle error, e.g. report to a service + } + + // Also possible + nuxtApp.hook('vue:error', (error, instance, info) => { + // handle error, e.g. report to a service + }) +}) +``` + +::note +Note that the `vue:error` hook is based on [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle#onerrorcaptured) lifecycle hook. +:: + +## Startup Errors + +Nuxt will call the `app:error` hook if there are any errors in starting your Nuxt application. + +This includes: +- running [Nuxt plugins](/docs/4.x/directory-structure/app/plugins) +- processing `app:created` and `app:beforeMount` hooks +- rendering your Vue app to HTML (during SSR) +- mounting the app (on client-side), though you should handle this case with `onErrorCaptured` or with `vue:error` +- processing the `app:mounted` hook + +## Nitro Server Errors + +You cannot currently define a server-side handler for these errors, but can render an error page, see the [Render an Error Page](/docs/4.x/getting-started/error-handling#error-page) section. + +## Errors with JS Chunks + +You might encounter chunk loading errors due to a network connectivity failure or a new deployment (which invalidates your old, hashed JS chunk URLs). Nuxt provides built-in support for handling chunk loading errors by performing a hard reload when a chunk fails to load during route navigation. + +You can change this behavior by setting `experimental.emitRouteChunkError` to `false` (to disable hooking into these errors at all) or to `manual` if you want to handle them yourself. If you want to handle chunk loading errors manually, you can check out the [the automatic implementation](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/plugins/chunk-reload.client.ts) for ideas. + +## Error Page + +::note +When Nuxt encounters a fatal error (any unhandled error on the server, or an error created with `fatal: true` on the client) it will either render a JSON response (if requested with `Accept: application/json` header) or trigger a full-screen error page. +:: + +An error may occur during the server lifecycle when: +- processing your Nuxt plugins +- rendering your Vue app into HTML +- a server API route throws an error + +It can also occur on the client side when: +- processing your Nuxt plugins +- before mounting the application (`app:beforeMount` hook) +- mounting your app if the error was not handled with `onErrorCaptured` or `vue:error` hook +- the Vue app is initialized and mounted in browser (`app:mounted`). + +::read-more{to="/docs/4.x/api/advanced/hooks"} +Discover all the Nuxt lifecycle hooks. +:: + +Customize the default error page by adding `~/error.vue` in the source directory of your application, alongside `app.vue`. + + + +```vue [error.vue] + + + +``` + +::read-more{to="/docs/4.x/directory-structure/app/error"} +Read more about `error.vue` and its uses. +:: + +For custom errors we highly recommend using `onErrorCaptured` composable that can be called in a page/component setup function or `vue:error` runtime nuxt hook that can be configured in a nuxt plugin. + +```ts twoslash [plugins/error-handler.ts] +export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.hook('vue:error', (err) => { + // + }) +}) +``` + +When you are ready to remove the error page, you can call the [`clearError`](/docs/4.x/api/utils/clear-error) helper function, which takes an optional path to redirect to (for example, if you want to navigate to a 'safe' page). + +::important +Make sure to check before using anything dependent on Nuxt plugins, such as `$route` or `useRouter`, as if a plugin threw an error, then it won't be re-run until you clear the error. +:: + +::note +Rendering an error page is an entirely separate page load, meaning any registered middleware will run again. You can use [`useError`](/docs/4.x/getting-started/error-handling#useerror) in middleware to check if an error is being handled. +:: + +::note +If you are running on Node 16 and you set any cookies when rendering your error page, they will [overwrite cookies previously set](https://github.com/nuxt/nuxt/pull/20585). We recommend using a newer version of Node as Node 16 reached end-of-life in September 2023. +:: + +## Error Utils + +### `useError` + +```ts [TS Signature] +function useError (): Ref +``` + +This function will return the global Nuxt error that is being handled. + +::read-more{to="/docs/4.x/api/composables/use-error"} +Read more about `useError` composable. +:: + +### `createError` + +```ts [TS Signature] +function createError (err: string | { cause, data, message, name, stack, status, statusText, fatal }): Error +``` + +Create an error object with additional metadata. You can pass a string to be set as the error `message` or an object containing error properties. It is usable in both the Vue and Server portions of your app, and is meant to be thrown. + +If you throw an error created with `createError`: +- on server-side, it will trigger a full-screen error page which you can clear with [`clearError`](/docs/4.x/getting-started/error-handling#clearerror). +- on client-side, it will throw a non-fatal error for you to handle. If you need to trigger a full-screen error page, then you can do this by setting `fatal: true`. + +```vue twoslash [pages/movies/[slug\\].vue] + +``` + +::tip +The `statusText` property is intended for short, HTTP-compliant status texts (e.g., "Not Found"). It should only contain horizontal tabs, spaces, and visible ASCII characters (`[\t\u0020-\u007E]`). + +For any detailed descriptions, multi-line messages, or content with non-ASCII characters, you should always use the `message` property instead. +:: + +::read-more{to="/docs/4.x/api/utils/create-error"} +Read more about `createError` util. +:: + +### `showError` + +```ts [TS Signature] +function showError (err: string | Error | { status, statusText }): Error +``` + +You can call this function at any point on client-side, or (on server side) directly within middleware, plugins or `setup()` functions. It will trigger a full-screen error page which you can clear with [`clearError`](/docs/4.x/getting-started/error-handling#clearerror). + +It is recommended instead to use `throw createError()`. + +::read-more{to="/docs/4.x/api/utils/show-error"} +Read more about `showError` util. +:: + +### `clearError` + +```ts [TS Signature] +function clearError (options?: { redirect?: string }): Promise +``` + +This function will clear the currently handled Nuxt error. It also takes an optional path to redirect to (for example, if you want to navigate to a 'safe' page). + +::read-more{to="/docs/4.x/api/utils/clear-error"} +Read more about `clearError` util. +:: + +## Render Error in Component + +Nuxt also provides a [``](/docs/4.x/api/components/nuxt-error-boundary) component that allows you to handle client-side errors within your app, without replacing your entire site with an error page. + +This component is responsible for handling errors that occur within its default slot. On client-side, it will prevent the error from bubbling up to the top level, and will render the `#error` slot instead. + +The `#error` slot will receive `error` as a prop. (If you set `error = null` it will trigger re-rendering the default slot; you'll need to ensure that the error is fully resolved first or the error slot will just be rendered a second time.) + +::tip +If you navigate to another route, the error will be cleared automatically. +:: + +```vue [app/pages/index.vue] + +``` + +:link-example{to="/docs/4.x/examples/advanced/error-handling"} diff --git a/reference/1.getting-started/13.server.md b/reference/1.getting-started/13.server.md new file mode 100644 index 0000000..9d21355 --- /dev/null +++ b/reference/1.getting-started/13.server.md @@ -0,0 +1,96 @@ +--- +title: 'Server' +description: Build full-stack applications with Nuxt's server framework. You can fetch data from your database or another server, create APIs, or even generate static server-side content like a sitemap or a RSS feed - all from a single codebase. +navigation.icon: i-lucide-pc-case +--- + +:read-more{to="/docs/4.x/directory-structure/server"} + +## Powered by Nitro + +![Server engine](/assets/docs/getting-started/server.svg) + +Nuxt's server is [Nitro](https://github.com/nitrojs/nitro). It was originally created for Nuxt but is now part of [UnJS](https://unjs.io) and open for other frameworks - and can even be used on its own. + +Using Nitro gives Nuxt superpowers: + +- Full control of the server-side part of your app +- Universal deployment on any provider (many zero-config) +- Hybrid rendering + +Nitro is internally using [h3](https://github.com/h3js/h3), a minimal H(TTP) framework built for high performance and portability. + +:video-accordion{title="Watch a video from Alexander Lichter to understand the responsibilities of Nuxt and Nitro in your application" videoId="DkvgJa-X31k"} + +## Server Endpoints & Middleware + +You can easily manage the server-only part of your Nuxt app, from API endpoints to middleware. + +Both endpoints and middleware can be defined like this: + +```ts twoslash [server/api/test.ts] +import { defineEventHandler } from 'nitro/h3' + +export default defineEventHandler(async (event) => { + // ... Do whatever you want here +}) +``` + +And you can directly return `text`, `json`, `html` or even a `stream`. + +Out-of-the-box, it supports **hot module replacement** and **auto-import** like the other parts of your Nuxt application. + +:read-more{to="/docs/4.x/directory-structure/server"} + +## Universal Deployment + +Nitro offers the ability to deploy your Nuxt app anywhere, from a bare metal server to the edge network, with a start time of just a few milliseconds. That's fast! + +:read-more{to="/blog/nuxt-on-the-edge"} + +There are more than 15 presets to build your Nuxt app for different cloud providers and servers, including: + +- [Cloudflare Workers](https://workers.cloudflare.com) +- [Netlify Functions](https://www.netlify.com/platform/core/functions/) +- [Vercel Cloud](https://vercel.com/home) + +Or for other runtimes: + +::card-group + :card{icon="i-logos-deno" title="Deno" to="https://deno.com" target="_blank"} + :card{icon="i-logos-bun" title="Bun" to="https://bun.com" target="_blank"} +:: + +:read-more{to="/docs/4.x/getting-started/deployment"} + +## Hybrid Rendering + +Nitro has a powerful feature called `routeRules` which allows you to define a set of rules to customize how each route of your Nuxt app is rendered (and more). + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + routeRules: { + // Generated at build time for SEO purpose + '/': { prerender: true }, + // Cached for 1 hour + '/api/*': { cache: { maxAge: 60 * 60 } }, + // Redirection to avoid 404 + '/old-page': { + redirect: { to: '/new-page', status: 302 }, + }, + // ... + }, +}) +``` + +::read-more{to="/docs/4.x/guide/concepts/rendering#hybrid-rendering"} +Learn about all available route rules are available to customize the rendering mode of your routes. +:: + +In addition, there are some route rules (for example, `ssr`, `appMiddleware`, and `noScripts`) that are Nuxt specific to change the behavior when rendering your pages to HTML. + +Some route rules (`appMiddleware`, `redirect` and `prerender`) also affect client-side behavior. + +Nitro is used to build the app for server side rendering, as well as pre-rendering. + +:read-more{to="/docs/4.x/guide/concepts/rendering"} diff --git a/reference/1.getting-started/14.layers.md b/reference/1.getting-started/14.layers.md new file mode 100644 index 0000000..0f8e2da --- /dev/null +++ b/reference/1.getting-started/14.layers.md @@ -0,0 +1,172 @@ +--- +title: 'Layers' +description: Nuxt provides a powerful system that allows you to extend the default files, configs, and much more. +navigation.icon: i-lucide-layers +--- + +One of the core features of Nuxt is the layers and extending support. You can extend a default Nuxt application to reuse components, utils, and configuration. The layers structure is almost identical to a standard Nuxt application which makes them easy to author and maintain. + +## Use Cases + +- Share reusable configuration presets across projects using `nuxt.config` and `app.config` +- Create a component library using [`app/components/`](/docs/4.x/directory-structure/app/components) directory +- Create utility and composable library using [`app/composables/`](/docs/4.x/directory-structure/app/composables) and [`app/utils/`](/docs/4.x/directory-structure/app/utils) directories +- Create Nuxt module presets +- Share standard setup across projects +- Create Nuxt themes +- Enhance code organization by implementing a modular architecture and support Domain-Driven Design (DDD) pattern in large scale projects. + +## Usage + +By default, any layers within your project in the `~~/layers` directory will be automatically registered as layers in your project. + +::note +Layer auto-registration was introduced in Nuxt v3.12.0. +:: + +In addition, named layer aliases to the `srcDir` of each of these layers will automatically be created. For example, you will be able to access the `~~/layers/test` layer via `#layers/test`. + +::note +Named layer aliases were introduced in Nuxt v3.16.0. +:: + +In addition, you can extend from a layer by adding the [extends](/docs/4.x/api/nuxt-config#extends) property to your [`nuxt.config`](/docs/4.x/directory-structure/nuxt-config) file. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + extends: [ + // Extend from a local layer + '../base', + // Extend from an installed npm package + '@my-themes/awesome', + // Extend from a git repository + 'github:my-themes/awesome#v1', + ], +}) +``` + +You can also pass an authentication token if you are extending from a private GitHub repository: + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + extends: [ + // per layer configuration + ['github:my-themes/private-awesome', { auth: process.env.GITHUB_TOKEN }], + ], +}) +``` + +::note +If a branch is not specified, this will clone `main`. +:: + +::tip +You can override a layer's alias by specifying it in the options next to the layer source. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + extends: [ + [ + 'github:my-themes/awesome', + { + meta: { + name: 'my-awesome-theme', + }, + }, + ], + ], +}) +``` + +:: + +Nuxt uses [unjs/c12](https://github.com/unjs/c12) and [unjs/giget](https://github.com/unjs/giget) for extending remote layers. Check the documentation for more information and all available options. + +## Layer Priority + +When using multiple layers, it's important to understand the override order. Layers with **higher priority** override layers with lower priority when they define the same files or components. + +### Priority Order + +From highest to lowest priority: + +1. **Your project files** - always have the highest priority +2. **Auto-scanned layers** from `~~/layers` directory - sorted alphabetically (Z has higher priority than A) +3. **Layers in `extends`** config - first entry has higher priority than second + +### Practical Example + +Consider multiple layers defining the same component: + +```bash [Directory structure] +layers/ + 1.base/ + app/components/Button.vue # Base button style + 2.theme/ + app/components/Button.vue # Themed button (overrides base) +app/ + components/Button.vue # Project button (overrides all layers) +``` + +In this case: +- If only layers exist, `2.theme/Button.vue` is used (higher alphabetically) +- If `app/components/Button.vue` exists in your project, it overrides all layers + +### Controlling Priority + +You can prefix layer directories with numbers to control the order: + +```bash [Directory structure] +layers/ + 1.base/ # Lowest priority + 2.features/ # Medium priority + 3.admin/ # Highest priority (among layers) +``` + +::tip +This pattern is useful for creating base layers with defaults that can be progressively overridden by more specific layers. +:: + +### When to Use Each + +- **`~~/layers` directory** - Use for local layers that are part of your project +- **`extends`** - Use for external dependencies (npm packages, remote repositories) or layers outside your project directory + +### Full Example with extends + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + extends: [ + '../base', // Local layer outside project + '@my-themes/awesome', // NPM package + 'github:my-themes/awesome#v1', // Remote repository + ], +}) +``` + +If you also have `~~/layers/custom`, the priority order is: +- Your project files (highest) +- `~~/layers/custom` +- `../base` +- `@my-themes/awesome` +- `github:my-themes/awesome#v1` (lowest) + +::read-more{to="/docs/4.x/directory-structure/layers"} +Learn about the **layers/ directory** to organize and share reusable code, components, composables, and configurations across your Nuxt application. +:: + +::read-more{to="/docs/4.x/guide/going-further/layers"} +Read more about layers in the **Layer Author Guide**. +:: + +:video-accordion{title="Watch a video from Learn Vue about Nuxt Layers" videoId="lnFCM7c9f7I"} + +:video-accordion{title="Watch a video from Alexander Lichter about Nuxt Layers" videoId="fr5yo3aVkfA"} + +## Examples + +::card-group + ::card{icon="i-simple-icons-github" title="Content Wind" to="https://github.com/Atinux/content-wind" target="_blank"} + A lightweight Nuxt theme to build a Markdown driven website. Powered by Nuxt Content, TailwindCSS and Iconify. + :: +:: diff --git a/reference/1.getting-started/15.prerendering.md b/reference/1.getting-started/15.prerendering.md new file mode 100644 index 0000000..7773593 --- /dev/null +++ b/reference/1.getting-started/15.prerendering.md @@ -0,0 +1,208 @@ +--- +title: "Prerendering" +description: Nuxt allows pages to be statically rendered at build time to improve certain performance or SEO metrics +navigation.icon: i-lucide-file-code-2 +--- + +Nuxt allows for select pages from your application to be rendered at build time. Nuxt will serve the prebuilt pages when requested instead of generating them on the fly. + +:read-more{title="Nuxt rendering modes" to="/docs/4.x/guide/concepts/rendering"} + +## Crawl-based Pre-rendering + +Use the [`nuxt generate` command](/docs/4.x/api/commands/generate) to build and pre-render your application using the [Nitro](/docs/4.x/guide/concepts/server-engine) crawler. This command is similar to `nuxt build` with the `nitro.static` option set to `true`, or running `nuxt build --prerender`. + +This will build your site, stand up a nuxt instance, and, by default, prerender the root page `/` along with any of your site's pages it links to, any of your site's pages they link to, and so on. + +::code-group{sync="pm"} + +```bash [npm] +npx nuxt generate +``` + +```bash [yarn] +yarn nuxt generate +``` + +```bash [pnpm] +pnpm nuxt generate +``` + +```bash [bun] +bun x nuxt generate +``` + +```bash [deno] +deno x nuxt generate +``` + +:: + +You can now deploy the `.output/public` directory to any static hosting service or preview it locally with `npx serve .output/public`. + +Working of the Nitro crawler: + +1. Load the HTML of your application's root route (`/`), any non-dynamic pages in your `~/pages` directory, and any other routes in the `nitro.prerender.routes` array. +2. Save the HTML and `payload.json` to the `~/.output/public/` directory to be served statically. +3. Find all anchor tags (`
`) in the HTML to navigate to other routes. +4. Repeat steps 1-3 for each anchor tag found until there are no more anchor tags to crawl. + +This is important to understand since pages that are not linked to a discoverable page can't be pre-rendered automatically. + +### Payload Extraction + +Nuxt generates `_payload.json` alongside HTML for: +- Prerendered routes (at build time) +- ISR/SWR routes (on first request) + +Payloads contain serialized data from `useAsyncData` and `useFetch`. Client-side navigation loads these cached payloads instead of re-fetching data. Configure dynamic routes like `pages/[...slug].vue` with route rules: `'/**': { isr: true }`. + +::read-more{to="/docs/4.x/api/commands/generate#nuxt-generate"} +Read more about the `nuxt generate` command. +:: + +### Selective Pre-rendering + +You can manually specify routes that [Nitro](/docs/4.x/guide/concepts/server-engine) will fetch and pre-render during the build or ignore routes that you don't want to pre-render like `/dynamic` in the `nuxt.config` file: + +```ts twoslash [nuxt.config.ts] +// @errors: 2353 +export default defineNuxtConfig({ + nitro: { + prerender: { + routes: ['/user/1', '/user/2'], + ignore: ['/dynamic'], + }, + }, +}) +``` + +You can combine this with the `crawlLinks` option to pre-render a set of routes that the crawler can't discover like your `/sitemap.xml` or `/robots.txt`: + +```ts twoslash [nuxt.config.ts] +// @errors: 2353 +export default defineNuxtConfig({ + nitro: { + prerender: { + crawlLinks: true, + routes: ['/sitemap.xml', '/robots.txt'], + }, + }, +}) +``` + +Setting `nitro.prerender` to `true` is similar to `nitro.prerender.crawlLinks` to `true`. + +::read-more{to="https://nitro.build/config#prerender"} +Read more about pre-rendering in the Nitro documentation. +:: + +Lastly, you can manually configure this using routeRules. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + routeRules: { + // Set prerender to true to configure it to be prerendered + '/rss.xml': { prerender: true }, + // Set it to false to configure it to be skipped for prerendering + '/this-DOES-NOT-get-prerendered': { prerender: false }, + // Everything under /blog gets prerendered as long as it + // is linked to from another page + '/blog/**': { prerender: true }, + }, +}) +``` + +::read-more{to="https://nitro.build/config#routerules"} +Read more about Nitro's `routeRules` configuration. +:: + +As a shorthand, you can also configure this in a page file using [`defineRouteRules`](/docs/4.x/api/utils/define-route-rules). + +::read-more{to="/docs/4.x/guide/going-further/experimental-features#inlinerouterules" icon="i-lucide-star"} +This feature is experimental and in order to use it you must enable the `experimental.inlineRouteRules` option in your `nuxt.config`. +:: + +```vue [app/pages/index.vue] + + + +``` + +This will be translated to: + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + routeRules: { + '/': { prerender: true }, + }, +}) +``` + +## Runtime Prerender Configuration + +### `prerenderRoutes` + +You can use this at runtime within a [Nuxt context](/docs/4.x/guide/going-further/nuxt-app#the-nuxt-context) to add more routes for Nitro to prerender. + +```vue [app/pages/index.vue] + + + +``` + +:read-more{title="prerenderRoutes" to="/docs/4.x/api/utils/prerender-routes"} + +### `prerender:routes` Nuxt hook + +This is called before prerendering for additional routes to be registered. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + hooks: { + async 'prerender:routes' (ctx) { + const { pages } = await fetch('https://api.some-cms.com/pages').then( + res => res.json(), + ) + for (const page of pages) { + ctx.routes.add(`/${page.name}`) + } + }, + }, +}) +``` + +### `prerender:generate` Nitro hook + +This is called for each route during prerendering. You can use this for fine-grained handling of each route that gets prerendered. + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + nitro: { + hooks: { + 'prerender:generate' (route) { + if (route.route?.includes('private')) { + route.skip = true + } + }, + }, + }, +}) +``` diff --git a/reference/1.getting-started/16.deployment.md b/reference/1.getting-started/16.deployment.md new file mode 100644 index 0000000..c0f96f9 --- /dev/null +++ b/reference/1.getting-started/16.deployment.md @@ -0,0 +1,137 @@ +--- +title: 'Deployment' +description: Learn how to deploy your Nuxt application to any hosting provider. +navigation.icon: i-lucide-cloud +--- + +A Nuxt application can be deployed on a Node.js server, pre-rendered for static hosting, or deployed to serverless or edge (CDN) environments. + +::tip +If you are looking for a list of cloud providers that support Nuxt, see the [Hosting providers](/deploy) section. +:: + +## Node.js Server + +Discover the Node.js server preset with Nitro to deploy on any Node hosting. + +- **Default output format** if none is specified or auto-detected
+- Loads only the required chunks to render the request for optimal cold start timing
+- Useful for deploying Nuxt apps to any Node.js hosting + +### Entry Point + +When running `nuxt build` with the Node server preset, the result will be an entry point that launches a ready-to-run Node server. + +```bash [Terminal] +NODE_ENV=production node .output/server/index.mjs +``` + +This will launch your production Nuxt server that listens on port 3000 by default. + +::important +Set `NODE_ENV=production` when running the server. Some dependencies (notably Vue Router) only strip development-only warnings when this is set, so leaving it unset can flood your logs with messages like `[Vue Router warn]: No match found for location with path …` on unmatched routes. +:: + +It respects the following runtime environment variables: + +- `NITRO_PORT` or `PORT` (defaults to `3000`) +- `NITRO_HOST` or `HOST` (defaults to `'0.0.0.0'`) +- `NITRO_SSL_CERT` and `NITRO_SSL_KEY` - if both are present, this will launch the server in HTTPS mode. In the vast majority of cases, this should not be used other than for testing, and the Nitro server should be run behind a reverse proxy like nginx or Cloudflare which terminates SSL. + +### PM2 + +[PM2](https://pm2.keymetrics.io/) (Process Manager 2) is a fast and easy solution for hosting your Nuxt application on your server or VM. + +To use `pm2`, use an `ecosystem.config.cjs`: + +```ts [ecosystem.config.cjs] +module.exports = { + apps: [ + { + name: 'NuxtAppName', + port: '3000', + exec_mode: 'cluster', + instances: 'max', + script: './.output/server/index.mjs', + env: { + NODE_ENV: 'production', + }, + }, + ], +} +``` + +### Cluster Mode + +You can use `NITRO_PRESET=node_cluster` in order to leverage multi-process performance using Node.js [cluster](https://nodejs.org/dist/latest/docs/api/cluster.html) module. + +By default, the workload gets distributed to the workers with the round robin strategy. + +### Learn More + +:read-more{to="https://nitro.build/deploy/runtimes/node" title="the Nitro documentation for node-server preset"} + +:video-accordion{title="Watch Daniel Roe's short video on the topic" videoId="0x1H6K5yOfs"} + +## Static Hosting + +There are two ways to deploy a Nuxt application to any static hosting services: + +- Static site generation (SSG) with `ssr: true` pre-renders routes of your application at build time. (This is the default behavior when running `nuxt generate`.) It will also generate `/200.html` and `/404.html` single-page app fallback pages, which can render dynamic routes or 404 errors on the client (though you may need to configure this on your static host). +- Alternatively, you can prerender your site with `ssr: false` (static single-page app). This will produce HTML pages with an empty `
` where your Vue app would normally be rendered. You will lose many SEO benefits of prerendering your site, so it is suggested instead to use [``](/docs/4.x/api/components/client-only) to wrap the portions of your site that cannot be server rendered (if any). + +:read-more{title="Nuxt prerendering" to="/docs/4.x/getting-started/prerendering"} + +### Client-side Only Rendering + +If you don't want to pre-render your routes, another way of using static hosting is to set the `ssr` property to `false` in the `nuxt.config` file. The `nuxt generate` command will then output an `.output/public/index.html` entrypoint and JavaScript bundles like a classic client-side Vue.js application. + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + ssr: false, +}) +``` + +## Hosting Providers + +Nuxt can be deployed to several cloud providers with a minimal amount of configuration: + +:read-more{to="/deploy"} + +## Presets + +In addition to Node.js servers and static hosting services, a Nuxt project can be deployed with several well-tested presets and minimal amount of configuration. + +You can explicitly set the desired preset in the [`nuxt.config.ts`](/docs/4.x/directory-structure/nuxt-config) file: + +```ts twoslash [nuxt.config.ts] +// @errors: 2353 +export default defineNuxtConfig({ + nitro: { + preset: 'node-server', + }, +}) +``` + +... or use the `NITRO_PRESET` environment variable when running `nuxt build`: + +```bash [Terminal] +NITRO_PRESET=node-server nuxt build +``` + +🔎 Check [the Nitro deployment](https://nitro.build/deploy) for all possible deployment presets and providers. + +## CDN Proxy + +In most cases, Nuxt can work with third-party content that is not generated or created by Nuxt itself. But sometimes such content can cause problems, especially Cloudflare's "Minification and Security Options". + +Accordingly, you should make sure that the following options are unchecked / disabled in Cloudflare. Otherwise, unnecessary re-rendering or hydration errors could impact your production application. + +1. Speed > Settings > Content Optimization > Disable "Rocket Loader™" +2. Security > Settings > Disable "Email Address Obfuscation" + +With these settings, you can be sure that Cloudflare won't inject scripts into your Nuxt application that may cause unwanted side effects. + +::tip +Their location on the Cloudflare dashboard sometimes changes so don't hesitate to look around. +:: diff --git a/reference/1.getting-started/17.testing.md b/reference/1.getting-started/17.testing.md new file mode 100644 index 0000000..7d9fc84 --- /dev/null +++ b/reference/1.getting-started/17.testing.md @@ -0,0 +1,877 @@ +--- +title: Testing +description: How to test your Nuxt application. +navigation.icon: i-lucide-circle-check +--- + +::tip +If you are a module author, you can find more specific information in the [Module Author's guide](/docs/4.x/guide/modules/testing). +:: + +Nuxt offers first-class support for end-to-end and unit testing of your Nuxt application via `@nuxt/test-utils`, a library of test utilities and configuration that currently powers the [tests we use on Nuxt itself](https://github.com/nuxt/nuxt/tree/main/test) and tests throughout the module ecosystem. + +:video-accordion{title="Watch a video from Alexander Lichter about getting started with @nuxt/test-utils" videoId="yGzwk9xi9gU"} + +## Installation + +In order to allow you to manage your other testing dependencies, `@nuxt/test-utils` ships with various optional peer dependencies. For example: + +- you can choose between `happy-dom` and `jsdom` for a runtime Nuxt environment +- you can choose between `vitest`, `cucumber`, `jest` and `playwright` for end-to-end test runners +- `playwright-core` is only required if you wish to use the built-in browser testing utilities (and are not using `@playwright/test` as your test runner) + +::code-group{sync="pm"} +```bash [npm] +npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core +``` +```bash [yarn] +yarn add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core +``` +```bash [pnpm] +pnpm add -D @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core +``` +```bash [bun] +bun add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core +``` +:: + +## Unit Testing + +We currently ship an environment for unit testing code that needs a [Nuxt](https://nuxt.com) runtime environment. It currently _only has support for `vitest`_ (although contribution to add other runtimes would be welcome). + +### Setup + +1. Add `@nuxt/test-utils/module` to your `nuxt.config` file (optional). It adds a Vitest integration to your Nuxt DevTools which supports running your unit tests in development. + + ```ts twoslash + export default defineNuxtConfig({ + modules: [ + '@nuxt/test-utils/module', + ], + }) + ``` + +2. Create a `vitest.config.ts` with the following content: + + ```ts twoslash + import { defineConfig } from 'vitest/config' + import { defineVitestProject } from '@nuxt/test-utils/config' + + export default defineConfig({ + test: { + projects: [ + { + test: { + name: 'unit', + include: ['test/unit/*.{test,spec}.ts'], + environment: 'node', + }, + }, + { + test: { + name: 'e2e', + include: ['test/e2e/*.{test,spec}.ts'], + environment: 'node', + }, + }, + await defineVitestProject({ + test: { + name: 'nuxt', + include: ['test/nuxt/*.{test,spec}.ts'], + environment: 'nuxt', + }, + }), + ], + }, + }) + ``` + +::tip +When importing `@nuxt/test-utils` in your vitest config, It is necessary to have `"type": "module"` specified in your `package.json` or rename your vitest config file appropriately. +> i.e., `vitest.config.m{ts,js}`. +:: + +::tip +It is possible to set environment variables for testing by using the `.env.test` file. +:: + +### Using a Nuxt Runtime Environment + +Using [Vitest projects](https://vitest.dev/guide/projects.html#test-projects), you have fine-grained control over which tests run in which environment: + +- **Unit tests**: Place regular unit tests in `test/unit/` - these run in a Node environment for speed +- **Nuxt tests**: Place tests that rely on the Nuxt runtime environment in `test/nuxt/` - these will run within a Nuxt runtime environment + +#### Alternative: Simple Setup + +If you prefer a simpler setup and want all tests to run in the Nuxt environment, you can use the basic configuration: + +```ts twoslash +import { defineVitestConfig } from '@nuxt/test-utils/config' +import { fileURLToPath } from 'node:url' + +export default defineVitestConfig({ + test: { + environment: 'nuxt', + // you can optionally set Nuxt-specific environment options + // environmentOptions: { + // nuxt: { + // rootDir: fileURLToPath(new URL('./playground', import.meta.url)), + // domEnvironment: 'happy-dom', // 'happy-dom' (default) or 'jsdom' + // overrides: { + // // other Nuxt config you want to pass + // } + // } + // } + }, +}) +``` + +If you're using the simple setup with `environment: 'nuxt'` by default, you can opt _out_ of the [Nuxt environment](https://vitest.dev/guide/environment.html#test-environment) per test file as needed. + +```ts twoslash +// @vitest-environment node +import { test } from 'vitest' + +test('my test', () => { + // ... test without Nuxt environment! +}) +``` + +::warning +This approach is not recommended as it creates a hybrid environment where Nuxt Vite plugins run but the Nuxt entry and `nuxtApp` are not initialized. This can lead to hard-to-debug errors. +:: + +### Organizing Your Tests + +With the project-based setup, you might organize your tests as follows: + +```bash [Directory structure] +test/ +├── e2e/ +│ └── ssr.test.ts +├── nuxt/ +│ ├── components.test.ts +│ └── composables.test.ts +├── unit/ +│ └── utils.test.ts +``` + +You can of course opt for any test structure, but keeping the Nuxt runtime environment separated from Nuxt end-to-end tests is important for test stability. + +#### TypeScript Support in Tests + +By default, test files in `test/nuxt/` and `tests/nuxt/` directories are included in the [Nuxt app TypeScript context](/docs/4.x/guide/concepts/typescript#how-nuxt-uses-project-references). That means they will recognise Nuxt aliases (like `~/`, `@/`, `#imports`) and TypeScript will be aware of auto-imports that work in your Nuxt app. + +::tip +This matches the recommended structure where only tests that need the Nuxt runtime environment are placed in these directories. Unit tests in other directories like `test/unit/` can be added manually if needed. +:: + +##### Adding other test directories + +If you have tests in other directories that you will be running in the Nuxt Vitest environment, you can include them in the Nuxt app TypeScript context by adding them to your configuration: + + + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + typescript: { + tsConfig: { + include: [ + // this path is relative to the generated .nuxt/tsconfig.json + '../test/other-nuxt-context/**/*', + ], + }, + }, +}) +``` + +::important +Unit tests should not depend on Nuxt runtime features like auto-imports or composables. Only add TypeScript path alias support if your tests import from your source files (e.g., `~/utils/helpers`), not for Nuxt-specific features. +:: + +#### Running Tests + +With the project setup, you can run different test suites: + +```bash +# Run all tests +npx vitest + +# Run only unit tests +npx vitest --project unit + +# Run only Nuxt tests +npx vitest --project nuxt + +# Run tests in watch mode +npx vitest --watch +``` + +::warning +When you run your tests within the Nuxt environment, they will be running in a [`happy-dom`](https://github.com/capricorn86/happy-dom) or [`jsdom`](https://github.com/jsdom/jsdom) environment. Before your tests run, a global Nuxt app will be initialized (including, for example, running any plugins or code you've defined in your `app.vue`). + +This means you should take particular care not to mutate the global state in your tests (or, if you need to, to reset it afterwards). +:: + +### 🎭 Built-In Mocks + +`@nuxt/test-utils` provides some built-in mocks for the DOM environment. + +#### `intersectionObserver` + +Default `true`, creates a dummy class without any functionality for the IntersectionObserver API + +#### `indexedDB` + +Default `false`, uses [`fake-indexeddb`](https://github.com/dumbmatter/fakeIndexedDB) to create a functional mock of the IndexedDB API + +These can be configured in the `environmentOptions` section of your `vitest.config.ts` file: + +```ts twoslash +import { defineVitestConfig } from '@nuxt/test-utils/config' + +export default defineVitestConfig({ + test: { + environmentOptions: { + nuxt: { + mock: { + intersectionObserver: true, + indexedDb: true, + }, + }, + }, + }, +}) +``` + +### 🛠️ Helpers + +`@nuxt/test-utils` provides a number of helpers to make testing Nuxt apps easier. + +#### `mountSuspended` + +`mountSuspended` allows you to mount any Vue component within the Nuxt environment, allowing async setup and access to injections from your Nuxt plugins. + +::note +Under the hood, `mountSuspended` wraps `mount` from `@vue/test-utils`, so you can check out [the Vue Test Utils documentation](https://test-utils.vuejs.org/guide/) for more on the options you can pass, and how to use this utility. +:: + +For example: + +```ts twoslash +// @noErrors +import { expect, it } from 'vitest' +import type { Component } from 'vue' + +declare module '#components' { + export const SomeComponent: Component +} +// ---cut--- +// tests/components/SomeComponents.nuxt.spec.ts +import { mountSuspended } from '@nuxt/test-utils/runtime' +import { SomeComponent } from '#components' + +it('can mount some component', async () => { + const component = await mountSuspended(SomeComponent) + expect(component.text()).toMatchInlineSnapshot( + '"This is an auto-imported component"', + ) +}) +``` + +```ts twoslash +// @noErrors +import { expect, it } from 'vitest' +// ---cut--- +// tests/components/SomeComponents.nuxt.spec.ts +import { mountSuspended } from '@nuxt/test-utils/runtime' +import App from '~/app.vue' + +// tests/App.nuxt.spec.ts +it('can also mount an app', async () => { + const component = await mountSuspended(App, { route: '/test' }) + expect(component.html()).toMatchInlineSnapshot(` + "
This is an auto-imported component
+
I am a global component
+
/
+
Test link " + `) +}) +``` + +The options object accepts `@vue/test-utils` mount options and the following properties: + + - `route`: the initial route, or `false` to skip the initial route change (default `/`). + +#### `renderSuspended` + +`renderSuspended` allows you to render any Vue component within the Nuxt environment using `@testing-library/vue`, allowing async setup and access to injections from your Nuxt plugins. + +This should be used together with utilities from Testing Library, e.g. `screen` and `fireEvent`. Install [@testing-library/vue](https://testing-library.com/docs/vue-testing-library/intro/) in your project to use these. + +Additionally, Testing Library also relies on testing globals for cleanup. You should turn these on in your [Vitest config](https://vitest.dev/config/globals). + +The passed in component will be rendered inside a `
`. + +Examples: + +```ts twoslash +// @noErrors +import { expect, it } from 'vitest' +import type { Component } from 'vue' + +declare module '#components' { + export const SomeComponent: Component +} +// ---cut--- +// tests/components/SomeComponents.nuxt.spec.ts +import { renderSuspended } from '@nuxt/test-utils/runtime' +import { SomeComponent } from '#components' +import { screen } from '@testing-library/vue' + +it('can render some component', async () => { + await renderSuspended(SomeComponent) + expect(screen.getByText('This is an auto-imported component')).toBeDefined() +}) +``` + +```ts twoslash +// @noErrors +import { expect, it } from 'vitest' +// ---cut--- +// tests/App.nuxt.spec.ts +import { renderSuspended } from '@nuxt/test-utils/runtime' +import App from '~/app.vue' + +it('can also render an app', async () => { + const html = await renderSuspended(App, { route: '/test' }) + expect(html).toMatchInlineSnapshot(` + "
+
This is an auto-imported component
+
I am a global component
+
Index page
Test link +
" + `) +}) +``` + +The options object accepts `@testing-library/vue` render options and the following properties: + + - `route`: the initial route, or `false` to skip the initial route change (default `/`). + +#### `mockNuxtImport` + +`mockNuxtImport` allows you to mock Nuxt's auto import functionality. For example, to mock `useState`, you can do so like this: + +```ts twoslash +import { mockNuxtImport } from '@nuxt/test-utils/runtime' + +mockNuxtImport('useState', () => { + return () => { + return { value: 'mocked storage' } + } +}) + +// your tests here +``` + +You can explicitly type the mock for type safety, and use the original implementation passed to the factory function when mocking complex functionality. + +```ts twoslash [test/nuxt/import.test.ts] +import { mockNuxtImport } from '@nuxt/test-utils/runtime' + +mockNuxtImport('useState', (original) => { + return (...args) => { + return { ...original('some-key'), value: 'mocked state' } + } +}) + +// or specify the target to mock +mockNuxtImport(useState, (original) => { + return (...args) => { + return { ...original('some-key'), value: 'mocked state' } + } +}) + +// your tests here +``` + +::note +`mockNuxtImport` can only be used once per mocked import per test file. It is actually a macro that gets transformed to `vi.mock` and `vi.mock` is hoisted, as described [in the Vitest docs](https://vitest.dev/api/vi#vi-mock). +:: + +If you need to mock a Nuxt import and provide different implementations between tests, you can do it by creating and exposing your mocks using [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted), and then use those mocks in `mockNuxtImport`. You then have access to the mocked imports, and can change the implementation between tests. Be careful to [restore mocks](https://vitest.dev/api/mock#mockrestore) before or after each test to undo mock state changes between runs. + +```ts twoslash +import { vi } from 'vitest' +import { mockNuxtImport } from '@nuxt/test-utils/runtime' + +const { useStateMock } = vi.hoisted(() => { + return { + useStateMock: vi.fn(() => { + return { value: 'mocked storage' } + }), + } +}) + +mockNuxtImport('useState', () => { + return useStateMock +}) + +// Then, inside a test +useStateMock.mockImplementation(() => { + return { value: 'something else' } +}) +``` + +If you need to mock behavior only inside a test, you can also use the following approach. + +```ts twoslash +import { beforeEach, vi } from 'vitest' +import { mockNuxtImport } from '@nuxt/test-utils/runtime' + +mockNuxtImport(useRoute, original => vi.fn(original)) + +beforeEach(() => { + vi.resetAllMocks() +}) + +// Then, inside a test +const useRouteOriginal = vi.mocked(useRoute).getMockImplementation()! +vi.mocked(useRoute).mockImplementation( + (...args) => ({ ...useRouteOriginal(...args), path: '/mocked' }), +) +``` + +#### `mockComponent` + +`mockComponent` allows you to mock Nuxt's component. +The first argument can be the component name in PascalCase, or the relative path of the component. +The second argument is a factory function that returns the mocked component. + +For example, to mock `MyComponent`, you can: + +```ts twoslash +import { mockComponent } from '@nuxt/test-utils/runtime' + +mockComponent('MyComponent', { + props: { + value: String, + }, + setup (props) { + // ... + }, +}) + +// relative path or alias also works +mockComponent('~/components/my-component.vue', () => { + // or a factory function + return defineComponent({ + setup (props) { + // ... + }, + }) +}) + +// or you can use SFC for redirecting to a mock component +mockComponent('MyComponent', () => import('./MockComponent.vue')) + +// your tests here +``` + +> **Note**: You can't reference local variables in the factory function since they are hoisted. If you need to access Vue APIs or other variables, you need to import them in your factory function. + +```ts twoslash +import { mockComponent } from '@nuxt/test-utils/runtime' + +mockComponent('MyComponent', async () => { + const { ref, h } = await import('vue') + + return defineComponent({ + setup (props) { + const counter = ref(0) + return () => h('div', null, counter.value) + }, + }) +}) +``` + +#### `registerEndpoint` + +`registerEndpoint` allows you create Nitro endpoint that returns mocked data. It can come in handy if you want to test a component that makes requests to API to display some data. + +The first argument is the endpoint name (e.g. `/test/`). +The second argument is a factory function that returns the mocked data. + +For example, to mock `/test/` endpoint, you can do: + +```ts twoslash +import { registerEndpoint } from '@nuxt/test-utils/runtime' + +registerEndpoint('/test/', () => ({ + test: 'test-field', +})) +``` + +By default, your request will be made using the `GET` method. You may use another method by setting an object as the second argument instead of a function. + +```ts twoslash +import { registerEndpoint } from '@nuxt/test-utils/runtime' + +registerEndpoint('/test/', { + method: 'POST', + handler: () => ({ test: 'test-field' }), +}) +``` + +This object accepts the following properties: + +- `handler`: the event handler function +- `method`: (optional) HTTP method to match (e.g., 'GET', 'POST') +- `once`: (optional) if true, the handler will only be used for the first matching request and then automatically removed + +> **Note**: If your requests in a component go to an external API, you can use `baseURL` and then make it empty using [Nuxt Environment Override Config](/docs/4.x/getting-started/configuration#environment-overrides) (`$test`) so all your requests will go to Nitro server. + +#### Conflict with End-To-End Testing + +`@nuxt/test-utils/runtime` and `@nuxt/test-utils/e2e` need to run in different testing environments and so can't be used in the same file. + +If you would like to use both the end-to-end and unit testing functionality of `@nuxt/test-utils`, you can split your tests into separate files. You then either specify a test environment per-file with the special `// @vitest-environment nuxt` comment, or name your runtime unit test files with the `.nuxt.spec.ts` extension. + +`app.nuxt.spec.ts` + +```ts twoslash +import { mockNuxtImport } from '@nuxt/test-utils/runtime' + +mockNuxtImport('useState', () => { + return () => { + return { value: 'mocked storage' } + } +}) +``` + +`app.e2e.spec.ts` + +```ts twoslash +import { $fetch, setup } from '@nuxt/test-utils/e2e' + +await setup({ + setupTimeout: 10000, +}) + +// ... +``` + +### Using `@vue/test-utils` + +If you prefer to use `@vue/test-utils` on its own for unit testing in Nuxt, and you are only testing components which do not rely on Nuxt composables, auto-imports or context, you can follow these steps to set it up. + +1. Install the needed dependencies + + ::code-group{sync="pm"} + ```bash [npm] + npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue + ``` + ```bash [yarn] + yarn add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue + ``` + ```bash [pnpm] + pnpm add -D vitest @vue/test-utils happy-dom @vitejs/plugin-vue + ``` + ```bash [bun] + bun add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue + ``` + :: + +2. Create a `vitest.config.ts` with the following content: + + ```ts + import { defineConfig } from 'vitest/config' + import vue from '@vitejs/plugin-vue' + + export default defineConfig({ + plugins: [vue()], + test: { + environment: 'happy-dom', + }, + }) + ``` + +3. Add a new command for test in your `package.json` + + ```json + "scripts": { + "build": "nuxt build", + "dev": "nuxt dev", + ... + "test": "vitest" + }, + ``` + +4. Create a simple `` component `app/components/HelloWorld.vue` with the following content: + + ```vue + + ``` + +5. Create a simple unit test for this newly created component `~/components/HelloWorld.spec.ts` + + ```ts twoslash + import { describe, expect, it } from 'vitest' + import { mount } from '@vue/test-utils' + + import HelloWorld from './HelloWorld.vue' + + describe('HelloWorld', () => { + it('component renders Hello world properly', () => { + const wrapper = mount(HelloWorld) + expect(wrapper.text()).toContain('Hello world') + }) + }) + ``` + +6. Run vitest command + + ::code-group{sync="pm"} + ```bash [npm] + npm run test + ``` + ```bash [yarn] + yarn test + ``` + ```bash [pnpm] + pnpm run test + ``` + ```bash [bun] + bun run test + ``` + :: + +Congratulations, you're all set to start unit testing with `@vue/test-utils` in Nuxt! Happy testing! + +## End-To-End Testing + +For end-to-end testing, we support [Vitest](https://github.com/vitest-dev/vitest), [Jest](https://jestjs.io), [Cucumber](https://cucumber.io/) and [Playwright](https://playwright.dev/) as test runners. + +### Setup + +In each `describe` block where you are taking advantage of the `@nuxt/test-utils/e2e` helper methods, you will need to set up the test context before beginning. + +```ts twoslash [test/my-test.spec.ts] +import { describe, test } from 'vitest' +import { $fetch, setup } from '@nuxt/test-utils/e2e' + +describe('My test', async () => { + await setup({ + // test context options + }) + + test('my test', () => { + // ... + }) +}) +``` + +Behind the scenes, `setup` performs a number of tasks in `beforeAll`, `beforeEach`, `afterEach` and `afterAll` to set up the Nuxt test environment correctly. + +Please use the options below for the `setup` method. + +#### Nuxt Config + +- `rootDir`: Path to a directory with a Nuxt app to be put under test. + - Type: `string` + - Default: `'.'` +- `configFile`: Name of the configuration file. + - Type: `string` + - Default: `'nuxt.config'` + + + +#### Timings + +- `setupTimeout`: The amount of time (in milliseconds) to allow for `setupTest` to complete its work (which could include building or generating files for a Nuxt application, depending on the options that are passed). + - Type: `number` + - Default: `120000` or `240000` on windows + +- `teardownTimeout`: The amount of time (in milliseconds) to allow tearing down the test environment, such as closing the browser. + - Type: `number` + - Default: `30000` + +#### Features + +- `build`: Whether to run a separate build step. + - Type: `boolean` + - Default: `true` (`false` if `browser` or `server` is disabled, or if a `host` is provided) + +- `server`: Whether to launch a server to respond to requests in the test suite. + - Type: `boolean` + - Default: `true` (`false` if a `host` is provided) + +- `port`: If provided, set the launched test server port to the value. + - Type: `number | undefined` + - Default: `undefined` + +- `host`: If provided, a URL to use as the test target instead of building and running a new server. Useful for running "real" end-to-end tests against a deployed version of your application, or against an already running local server (which may provide a significant reduction in test execution timings). See the [target host end-to-end example below](/docs/4.x/getting-started/testing#target-host-end-to-end-example). + - Type: `string` + - Default: `undefined` + +- `browser`: Under the hood, Nuxt test utils uses [`playwright`](https://playwright.dev) to carry out browser testing. If this option is set, a browser will be launched and can be controlled in the subsequent test suite. + - Type: `boolean` + - Default: `false` +- `browserOptions` + - Type: `object` with the following properties + - `type`: The type of browser to launch - either `chromium`, `firefox` or `webkit` + - `launch`: `object` of options that will be passed to playwright when launching the browser. See [full API reference](https://playwright.dev/docs/api/class-browsertype#browser-type-launch). +- `runner`: Specify the runner for the test suite. Currently, [Vitest](https://vitest.dev) is recommended. + - Type: `'vitest' | 'jest' | 'cucumber'` + - Default: `'vitest'` + +##### Target `host` end-to-end example + +A common use-case for end-to-end testing is running the tests against a deployed application running in the same environment typically used for Production. + +For local development or automated deploy pipelines, testing against a separate local server can be more efficient and is typically faster than allowing the test framework to rebuild between tests. + +To utilize a separate target host for end-to-end tests, simply provide the `host` property of the `setup` function with the desired URL. + +```ts +import { createPage, setup } from '@nuxt/test-utils/e2e' +import { describe, expect, it } from 'vitest' + +describe('login page', async () => { + await setup({ + host: 'http://localhost:8787', + }) + + it('displays the email and password fields', async () => { + const page = await createPage('/login') + expect(await page.getByTestId('email').isVisible()).toBe(true) + expect(await page.getByTestId('password').isVisible()).toBe(true) + }) +}) +``` + +### APIs + +#### `$fetch(url)` + +Get the HTML of a server-rendered page. + +```ts twoslash +import { $fetch } from '@nuxt/test-utils/e2e' + +const html = await $fetch('/') +``` + +#### `fetch(url)` + +Get the response of a server-rendered page. + +```ts twoslash +import { fetch } from '@nuxt/test-utils/e2e' + +const res = await fetch('/') +const { body, headers } = res +``` + +#### `url(path)` + +Get the full URL for a given page (including the port the test server is running on.) + +```ts twoslash +import { url } from '@nuxt/test-utils/e2e' + +const pageUrl = url('/page') +// 'http://localhost:6840/page' +``` + +### Testing in a Browser + +We provide built-in support using Playwright within `@nuxt/test-utils`, either programmatically or via the Playwright test runner. + +#### `createPage(url)` + +Within `vitest`, `jest` or `cucumber`, you can create a configured Playwright browser instance with `createPage`, and (optionally) point it at a path from the running server. You can find out more about the API methods available from [in the Playwright documentation](https://playwright.dev/docs/api/class-page). + +```ts twoslash +import { createPage } from '@nuxt/test-utils/e2e' + +const page = await createPage('/page') +// you can access all the Playwright APIs from the `page` variable +``` + +#### Testing with Playwright Test Runner + +We also provide first-class support for testing Nuxt within [the Playwright test runner](https://playwright.dev/docs/intro). + +::code-group{sync="pm"} +```bash [npm] +npm i --save-dev @playwright/test @nuxt/test-utils +``` +```bash [yarn] +yarn add --dev @playwright/test @nuxt/test-utils +``` +```bash [pnpm] +pnpm add -D @playwright/test @nuxt/test-utils +``` +```bash [bun] +bun add --dev @playwright/test @nuxt/test-utils +``` +```bash [deno] +deno add --dev npm:@playwright/test npm:@nuxt/test-utils +``` +:: + +You can provide global Nuxt configuration, with the same configuration details as the `setup()` function mentioned earlier in this section. + +```ts [playwright.config.ts] +import { fileURLToPath } from 'node:url' +import { defineConfig, devices } from '@playwright/test' +import type { ConfigOptions } from '@nuxt/test-utils/playwright' + +export default defineConfig({ + use: { + nuxt: { + rootDir: fileURLToPath(new URL('.', import.meta.url)), + }, + }, + // ... +}) +``` + +::read-more{title="See full example config" to="https://github.com/nuxt/test-utils/blob/main/examples/app-playwright/playwright.config.ts" target="_blank"} +:: + +Your test file should then use `expect` and `test` directly from `@nuxt/test-utils/playwright`: + +```ts [tests/example.test.ts] +import { expect, test } from '@nuxt/test-utils/playwright' + +test('test', async ({ page, goto }) => { + await goto('/', { waitUntil: 'hydration' }) + await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!') +}) +``` + +You can alternatively configure your Nuxt server directly within your test file: + +```ts [tests/example.test.ts] +import { expect, test } from '@nuxt/test-utils/playwright' + +test.use({ + nuxt: { + rootDir: fileURLToPath(new URL('..', import.meta.url)), + }, +}) + +test('test', async ({ page, goto }) => { + await goto('/', { waitUntil: 'hydration' }) + await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!') +}) +``` diff --git a/reference/1.getting-started/18.upgrade.md b/reference/1.getting-started/18.upgrade.md new file mode 100644 index 0000000..dcdf6df --- /dev/null +++ b/reference/1.getting-started/18.upgrade.md @@ -0,0 +1,526 @@ +--- +title: Upgrade Guide +description: 'Learn how to upgrade to the latest Nuxt version.' +navigation.icon: i-lucide-circle-arrow-up +--- + +## Upgrading Nuxt + +### Latest release + +To upgrade Nuxt to the [latest release](https://github.com/nuxt/nuxt/releases), use the `nuxt upgrade` command. + +::code-group{sync="pm"} + +```bash [npm] +npx nuxt upgrade +``` + +```bash [yarn] +yarn nuxt upgrade +``` + +```bash [pnpm] +pnpm nuxt upgrade +``` + +```bash [bun] +bun x nuxt upgrade +``` + +```bash [deno] +deno x nuxt upgrade +``` + +:: + +### Nightly Release Channel + +To use the latest Nuxt build and test features before their release, read about the [nightly release channel](/docs/4.x/guide/going-further/nightly-release-channel) guide. + +## Testing Nuxt 5 + +Nuxt 5 is **currently in development**. Until the release, it is possible to test many of Nuxt 5's breaking changes from Nuxt version 4.2+. + +### Opting in to Nuxt 5 + +First, upgrade Nuxt to the [latest release](https://github.com/nuxt/nuxt/releases). + +Then you can set your `future.compatibilityVersion` to match Nuxt 5 behavior: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + future: { + compatibilityVersion: 5, + }, +}) +``` + +When you set your `future.compatibilityVersion` to `5`, defaults throughout your Nuxt configuration will change to opt in to Nuxt v5 behavior, including: + +- **Vite Environment API**: Uses the new [Vite Environment API](/docs/4.x/getting-started/upgrade#migration-to-vite-environment-api) for improved build configuration +- **Normalized Page Names**: Page component names will [match their route names](/docs/4.x/getting-started/upgrade#normalized-page-component-names) for consistent `` behavior +- **`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` +- **Non-async `callHook`**: [`callHook` may return `void`](/docs/4.x/getting-started/upgrade#non-async-callhook) instead of always returning a `Promise` +- **Comment node placeholders**: Client-only components use [comment nodes instead of `
`](/docs/4.x/getting-started/upgrade#client-only-comment-placeholders) as SSR placeholders, fixing a scoped styles hydration issue +- Other Nuxt 5 improvements and changes as they become available + +::note +This section is subject to change until the final release, so please check back here regularly if you are testing Nuxt 5 using `future.compatibilityVersion: 5`. +:: + +Breaking or significant changes will be noted below along with migration steps for backward/forward compatibility. + +### Migration to Vite Environment API + +🚦 **Impact Level**: Medium + +#### What Changed + +Nuxt 5 migrates to Vite 6's new [Environment API](https://vite.dev/guide/api-environment), which formalizes the concept of environments and provides better control over configuration per environment. + +Previously, Nuxt used separate client and server Vite configurations. Now, Nuxt uses a shared Vite configuration with environment-specific plugins that use the `applyToEnvironment()` method to target specific environments. + +::note +The Vite Environment API is always enabled in Nuxt 5. The `experimental.viteEnvironmentApi` option has been removed. +:: + +**Key changes:** + +1. **Deprecated environment-specific `extendViteConfig()`**: The `server` and `client` options in `extendViteConfig()` are deprecated and will show warnings when used. + +2. **Changed plugin registration**: Vite plugins registered with `addVitePlugin()` and only targeting one environment (by passing `server: false` or `client: false`) will not have their `config` or `configResolved` hooks called. + +3. **Shared configuration**: The `vite:extendConfig` and `vite:configResolved` hooks now work with a shared configuration rather than separate client/server configs. + +#### Reasons for Change + +The Vite Environment API provides: +- Better consistency between development and production builds +- More granular control over environment-specific configuration +- Improved performance and plugin architecture +- Support for custom environments beyond just client and server + +#### Migration Steps + +##### 1. Migrate to use Vite plugins + +We would recommend you use a Vite plugin instead of `extendViteConfig`, `vite:configResolved` and `vite:extendConfig`. + +```ts +// Before +extendViteConfig((config) => { + config.optimizeDeps.include.push('my-package') +}, { server: false }) + +nuxt.hook('vite:extendConfig' /* or vite:configResolved */, (config, { isClient }) => { + if (isClient) { + config.optimizeDeps.include.push('my-package') + } +}) + +// After +addVitePlugin(() => ({ + name: 'my-plugin', + config (config) { + // you can set global vite configuration here + }, + configResolved (config) { + // you can access the fully resolved vite configuration here + }, + configEnvironment (name, config) { + // you can set environment-specific vite configuration here + if (name === 'client') { + config.optimizeDeps ||= {} + config.optimizeDeps.include ||= [] + config.optimizeDeps.include.push('my-package') + } + }, + applyToEnvironment (environment) { + return environment.name === 'client' + }, +})) +``` + +##### 2. Migrate Vite plugins to use environments + +Instead of using `addVitePlugin` with `server: false` or `client: false`, you can instead use the new `applyToEnvironment` hook within your plugin. + +```ts +// Before +addVitePlugin(() => ({ + name: 'my-plugin', + config (config) { + config.optimizeDeps.include.push('my-package') + }, +}), { client: false }) + +// After +addVitePlugin(() => ({ + name: 'my-plugin', + config (config) { + // you can set global vite configuration here + }, + configResolved (config) { + // you can access the fully resolved vite configuration here + }, + configEnvironment (name, config) { + // you can set environment-specific vite configuration here + if (name === 'client') { + config.optimizeDeps ||= {} + config.optimizeDeps.include ||= [] + config.optimizeDeps.include.push('my-package') + } + }, + applyToEnvironment (environment) { + return environment.name === 'client' + }, +})) +``` + +::read-more{to="https://vite.dev/guide/api-environment" target="_blank"} +Learn more about Vite's Environment API +:: + +### Migration to Vite 8 + +🚦 **Impact Level**: Medium + +#### What Changed + +Nuxt 5 upgrades from Vite 7 to [Vite 8](https://main.vite.dev/guide/migration), which replaces esbuild and Rollup with [Rolldown](https://rolldown.rs) as the underlying bundler. This brings significantly faster builds but includes several breaking changes. + +::note +Unlike the Vite Environment API migration, this change cannot be opted into early with `future.compatibilityVersion: 5`. If you want to test Vite 8 compatibility ahead of time, you can add a `"vite": "^8.0.0-beta.15"` resolution override in your `package.json`. +:: + +Most of the migration is handled by Nuxt internally, but there are some user-facing changes to be aware of: + +- **`vite.esbuild` and `vite.optimizeDeps.esbuildOptions`** are deprecated in favour of `vite.oxc` and `vite.optimizeDeps.rolldownOptions`. Vite 8 converts these automatically for now, but they will be removed in the future. +- **`build.rollupOptions`** is deprecated in favour of `build.rolldownOptions`. +- **CommonJS interop behaviour** has changed. If you import CJS modules, review the [Vite 8 migration guide](https://main.vite.dev/guide/migration#consistent-commonjs-interop) for details. + +::read-more{to="https://main.vite.dev/guide/migration" target="_blank"} +See the full Vite 8 migration guide for all breaking changes and migration steps. +:: + +### Migration to Nitro v3 + +🚦 **Impact Level**: Significant + +#### What Changed + +Nuxt 5 upgrades to [Nitro v3](https://nitro.build/blog/v3-beta), which is a major rewrite of the server engine. Nitro v3 is built on [srvx](https://srvx.h3.dev) and [h3 v2](https://h3.dev), adopting Web standard `Request`/`Response` APIs throughout. This brings performance improvements and a more consistent API, but includes several breaking changes to server-side code. + +::important +We are still working on Nitro v3 integration so you should expect further changes, as well as additional work to make migration more straightforward. +:: + +::read-more{to="https://nitro.build/blog/v3-beta" target="_blank"} +Read the Nitro v3 beta announcement for a full overview. +:: + +::read-more{to="https://nitro.build/docs/migration" target="_blank"} +See the full Nitro v3 migration guide for all breaking changes. +:: + +The sections below highlight changes that are most relevant to Nuxt application developers and module authors. + +#### Package and Import Path Changes + +The `nitropack` package has been renamed to `nitro`. All import paths have changed: + +| Before | After | +|---|---| +| `nitropack` | `nitro` | +| `nitropack/types` | `nitro/types` | +| `nitropack/runtime` | `nitro` | +| `h3` (for server utilities) | `nitro/h3` | + +Auto-imports within server routes (`defineEventHandler`, `getQuery`, `readBody`, `useRuntimeConfig`, etc.) continue to work without changes. + +If you have explicit imports in server code, update them: + +```diff +- import { defineEventHandler, getQuery } from 'h3' ++ import { defineEventHandler, getQuery } from 'nitro/h3' +``` + +**For module authors**, type augmentations must target the new module path: + +```diff +- declare module 'nitropack/types' { ++ declare module 'nitro/types' { + interface NitroRouteRules { + myModule?: { /* ... */ } + } + } +``` + +#### Error Handling: `status`/`statusText` replace `statusCode`/`statusMessage` + +h3 v2 renames the error properties to align with Web standards: + +```diff + createError({ +- statusCode: 404, +- statusMessage: 'Not Found', ++ status: 404, ++ statusText: 'Not Found', + }) +``` + +In server routes, the error class is now `HTTPError` (replacing `createError` from `h3`): + +```diff +- import { createError } from 'h3' ++ import { HTTPError } from 'nitro/h3' + + export default defineEventHandler(() => { +- throw createError({ statusCode: 400, statusMessage: 'Bad request' }) ++ throw new HTTPError({ status: 400, statusText: 'Bad request' }) + }) +``` + +::note +In the Vue part of your app (the `app/` directory), Nuxt's `createError` composable continues to work and is the recommended way to throw errors. +:: + +#### Server Event API Changes (h3 v2) + +The `H3Event` object now uses Web standard APIs: + +**Request properties:** +```diff +- event.path // string ++ event.url.pathname // URL object - use .pathname, .search, .hash + +- event.method // string ++ event.req.method // via Web Request object + +- event.node.req.headers // Node.js IncomingHttpHeaders ++ event.req.headers // Web Headers API (.get(), .set(), .has()) +``` + +**Response properties:** +```diff +- event.node.res.statusCode = 200 ++ event.res.status = 200 + +- event.node.res.statusMessage = 'OK' ++ event.res.statusText = 'OK' + +- setResponseHeader(event, 'x-custom', 'value') ++ event.res.headers.set('x-custom', 'value') + +- appendResponseHeader(event, 'set-cookie', cookie) ++ event.res.headers.append('set-cookie', cookie) +``` + +#### `useRuntimeConfig()` No Longer Accepts `event` + +In Nitro v3, `useRuntimeConfig()` no longer requires (or accepts) an `event` argument in server routes: + +```diff + export default defineEventHandler((event) => { +- const config = useRuntimeConfig(event) ++ const config = useRuntimeConfig() + }) +``` + +#### Route Rules: `statusCode` Renamed to `status` + +If you define redirect route rules, the property name has changed: + +```diff + export default defineNuxtConfig({ + routeRules: { + '/old-page': { +- redirect: { to: '/new-page', statusCode: 302 }, ++ redirect: { to: '/new-page', status: 302 }, + }, + }, + }) +``` + +#### For Module Authors: Additional Changes + +- **Nitro plugin imports**: Use `import { definePlugin } from 'nitro'` for explicit imports (auto-imports still work). +- **Runtime hooks**: `nitroApp.hooks.hook('beforeResponse', ...)` and `nitroApp.hooks.hook('afterResponse', ...)` have been replaced by `nitroApp.hooks.hook('response', ...)`. +- **`getRouteRules()` from `nitro/app`**: On the server, the Nitro helper changed from `getRouteRules(event)` to `getRouteRules(method, pathname)`, which returns `{ routeRules }`. + +### Removal of `experimental.externalVue` + +🚦 **Impact Level**: Minimal + +#### What Changed + +The `experimental.externalVue` option has been removed. Vue compiler dependencies (`@babel/parser`, `@vue/compiler-core`, `@vue/compiler-dom`, `@vue/compiler-ssr`, `estree-walker`) are now always replaced with mock proxies in the server bundle when `vue.runtimeCompiler` is not enabled. + +#### Reasons for Change + +With the migration to Nitro v3, all dependencies are bundled into the server output by default (unlike Nitro v2, which externalized `node_modules`). The `externalVue` option was originally designed to keep Vue as an external dependency, which was needed to avoid multiple copies of Vue from being bundled, but since Nitro v3 bundles everything regardless, the option became a no-op. + +Vue's server builds include the full compiler toolchain, pulling `@babel/parser` (465KB) and other compiler packages into the server bundle unnecessarily. These compiler packages are only needed when `vue.runtimeCompiler` is enabled for runtime template compilation. + +By always mocking these compiler dependencies, the default server bundle size is reduced by approximately 860KB (~59%). + +#### Migration Steps + +If you previously set `experimental.externalVue` explicitly, you should now remove it. + +```diff + export default defineNuxtConfig({ + experimental: { +- externalVue: false, + }, + }) +``` + +::note +If you use `vue.runtimeCompiler: true`, the real compiler packages are still included as before. +:: + +### `@vitejs/plugin-vue-jsx` Is Now Optional + +🚦 **Impact Level**: Minimal + +#### What Changed + +`@vitejs/plugin-vue-jsx` is no longer installed by default with `@nuxt/vite-builder`. It is now an optional peer dependency that is loaded on demand only when a `.jsx` or `.tsx` file is encountered during the build. + +If your project uses JSX/TSX components, Nuxt will automatically detect this and prompt you to install the package. + +#### Reasons for Change + +The `@vitejs/plugin-vue-jsx` plugin pulls in a significant dependency tree (Babel, `@vue/babel-plugin-jsx`, etc.) that is unnecessary for projects that don't use JSX. Making it optional reduces the default install size and speeds up dependency resolution for the majority of Nuxt projects. + +#### Migration Steps + +If your project uses `.jsx` or `.tsx` files, add `@vitejs/plugin-vue-jsx` as a dev dependency: + +::code-group{sync="pm"} + +```bash [npm] +npm install -D @vitejs/plugin-vue-jsx +``` + +```bash [yarn] +yarn add -D @vitejs/plugin-vue-jsx +``` + +```bash [pnpm] +pnpm add -D @vitejs/plugin-vue-jsx +``` + +```bash [bun] +bun add -D @vitejs/plugin-vue-jsx +``` + +:: + +Alternatively, Nuxt will prompt you to install it automatically the first time a JSX/TSX file is processed during development. + +If your project does not use JSX, no changes are needed. + +### Removal of Legacy `_renderResponse` Support + +🚦 **Impact Level**: Minimal + +#### What Changed + +`ssrContext._renderResponse` is no longer checked as a fallback. Only the internal `ssrContext['~renderResponse']` (set by Nuxt's own router composable) is used. + +#### Reasons for Change + +The `_renderResponse` property on `ssrContext` was kept as a backward-compatibility fallback after [#33896](https://github.com/nuxt/nuxt/pull/33896) migrated the internal API to `~renderResponse`. The TODO comments indicated it should be removed in Nuxt v5. + +#### Migration Steps + +If you were setting `ssrContext._renderResponse` directly (which was never a public API), use `ssrContext['~renderResponse']` instead. The Nuxt router composable already uses the new property, so no changes are needed if you're going through `navigateTo` or route middleware. + +### Non-Async `callHook` + +🚦 **Impact Level**: Minimal + +#### What Changed + +With the upgrade to [hookable v6](https://github.com/unjs/hookable), `callHook` may now return `void` instead of always returning `Promise`. This is a significant performance improvement that avoids unnecessary `Promise` allocations when there are no registered hooks or all hooks are synchronous. + +By default (with `compatibilityVersion: 4`), Nuxt wraps `callHook` with `Promise.resolve()` so that existing `.then()` and `.catch()` chaining continues to work. With `compatibilityVersion: 5`, this wrapper is removed. + +::tip +This affects both build-time Nuxt hooks (used by Nuxt modules) and runtime Nuxt hooks (which you might use in your application code). +:: + +#### Reasons for Change + +Hookable v6's `callHook` is 20-40x faster because it avoids creating a `Promise` when one is not needed. This benefits applications with many hook call sites. + +#### Migration Steps + +If you or your modules use `callHook` with `.then()` or `.catch()` chaining, switch to `await`: + +```diff +- nuxtApp.callHook('my:hook', data).then(() => { ... }) ++ await nuxtApp.callHook('my:hook', data) +``` + +```diff +- nuxtApp.hooks.callHook('my:hook', data).catch(err => { ... }) ++ try { await nuxtApp.hooks.callHook('my:hook', data) } catch (err) { ... } +``` + +::tip +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.asyncCallHook: false`. +:: + +Alternatively, you can ensure `callHook` always returns a `Promise` with: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + experimental: { + asyncCallHook: true, + }, +}) +``` + +### Client-Only Comment Placeholders + +🚦 **Impact Level**: Minimal + +#### What Changed + +With `compatibilityVersion: 5`, client-only components (`.client.vue` files and `createClientOnly()` wrappers) now render an HTML comment (``) on the server instead of an empty `
` element. + +#### Reasons for Change + +When the placeholder `
` 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. + +#### Migration Steps + +If you rely on the placeholder `
` to inherit attributes (`class`, `style`, etc.) for layout purposes (e.g., reserving space to prevent layout shift), wrap the component in `` with a `#fallback` slot instead: + +```diff +- ++ ++ ++ ++ +``` + +::tip +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`. +:: + +Alternatively, you can revert to the previous `
` placeholder behavior with: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + experimental: { + clientNodePlaceholder: false, + }, +}) +``` diff --git a/reference/2.directory-structure/.navigation.yml b/reference/2.directory-structure/.navigation.yml new file mode 100644 index 0000000..c17f21f --- /dev/null +++ b/reference/2.directory-structure/.navigation.yml @@ -0,0 +1,3 @@ +title: Directory Structure +titleTemplate: '%s · Nuxt Directory Structure' +icon: i-vscode-icons-default-folder diff --git a/reference/2.directory-structure/0.nuxt.md b/reference/2.directory-structure/0.nuxt.md new file mode 100644 index 0000000..263a243 --- /dev/null +++ b/reference/2.directory-structure/0.nuxt.md @@ -0,0 +1,20 @@ +--- +title: ".nuxt" +description: "Nuxt uses the .nuxt/ directory in development to generate your Vue application." +head.title: ".nuxt/" +navigation.icon: i-vscode-icons-folder-type-temp +--- + +::important +This directory should be added to your [`.gitignore`](/docs/4.x/directory-structure/gitignore) file to avoid pushing the dev build output to your repository. +:: + +This directory is interesting if you want to learn more about the files Nuxt generates based on your directory structure. + +Nuxt also provides a Virtual File System (VFS) for modules to add templates to this directory without writing them to disk. + +You can explore the generated files by opening the [Nuxt DevTools](https://devtools.nuxt.com) in development mode and navigating to the **Virtual Files** tab. + +::warning +You should not touch any files inside since the whole directory will be re-created when running [`nuxt dev`](/docs/4.x/api/commands/dev). +:: diff --git a/reference/2.directory-structure/0.output.md b/reference/2.directory-structure/0.output.md new file mode 100644 index 0000000..04c7ad1 --- /dev/null +++ b/reference/2.directory-structure/0.output.md @@ -0,0 +1,18 @@ +--- +title: ".output" +description: "Nuxt creates the .output/ directory when building your application for production." +head.title: ".output/" +navigation.icon: i-vscode-icons-folder-type-package +--- + +::important +This directory should be added to your [`.gitignore`](/docs/4.x/directory-structure/gitignore) file to avoid pushing the build output to your repository. +:: + +Use this directory to deploy your Nuxt application to production. + +:read-more{to="/docs/4.x/getting-started/deployment"} + +::warning +You should not touch any files inside since the whole directory will be re-created when running [`nuxt build`](/docs/4.x/api/commands/build). +:: diff --git a/reference/2.directory-structure/1.app/.navigation.yml b/reference/2.directory-structure/1.app/.navigation.yml new file mode 100644 index 0000000..e90b22f --- /dev/null +++ b/reference/2.directory-structure/1.app/.navigation.yml @@ -0,0 +1,5 @@ +title: app +titleTemplate: '%s · Nuxt Directory Structure' +head.title: "app/" +defaultOpen: true +icon: i-vscode-icons-folder-type-app diff --git a/reference/2.directory-structure/1.app/1.assets.md b/reference/2.directory-structure/1.app/1.assets.md new file mode 100644 index 0000000..e072cb6 --- /dev/null +++ b/reference/2.directory-structure/1.app/1.assets.md @@ -0,0 +1,16 @@ +--- +title: "assets" +description: "The assets/ directory is used to add all the website's assets that the build tool will process." +head.title: "assets/" +navigation.icon: i-vscode-icons-folder-type-asset +--- + +The directory usually contains the following types of files: + +- Stylesheets (CSS, SASS, etc.) +- Fonts +- Images that won't be served from the [`public/`](/docs/4.x/directory-structure/public) directory. + +If you want to serve assets from the server, we recommend taking a look at the [`public/`](/docs/4.x/directory-structure/public) directory. + +:read-more{to="/docs/4.x/getting-started/assets"} diff --git a/reference/2.directory-structure/1.app/1.components.md b/reference/2.directory-structure/1.app/1.components.md new file mode 100644 index 0000000..5556059 --- /dev/null +++ b/reference/2.directory-structure/1.app/1.components.md @@ -0,0 +1,639 @@ +--- +title: "components" +head.title: "components/" +description: "The components/ directory is where you put all your Vue components." +navigation.icon: i-vscode-icons-folder-type-component +--- + +Nuxt automatically imports any components in this directory (along with components that are registered by any modules you may be using). + +```bash [Directory Structure] +-| components/ +---| AppHeader.vue +---| AppFooter.vue +``` + +```html [app/app.vue] + +``` + +## Component Names + +If you have a component in nested directories such as: + +```bash [Directory Structure] +-| components/ +---| base/ +-----| foo/ +-------| Button.vue +``` + +... then the component's name will be based on its own path directory and filename, with duplicate segments being removed. Therefore, the component's name will be: + +```html + +``` + +::note +For clarity, we recommend that the component's filename matches its name. So, in the example above, you could rename `Button.vue` to be `BaseFooButton.vue`. +:: + +If you want to auto-import components based only on its name, not path, then you need to set `pathPrefix` option to `false` using extended form of the configuration object: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + components: [ + { + path: '~/components', + pathPrefix: false, // [!code ++] + }, + ], +}) +``` + +This registers the components using the same strategy as used in Nuxt 2. For example, `~/components/Some/MyComponent.vue` will be usable as `` and not ``. + +## Dynamic Components + +If you want to use the Vue ``{lang=vue} syntax, you need to use the `resolveComponent` helper provided by Vue or import the component directly from `#components` and pass it into `is` prop. + +For example: + +```vue [app/pages/index.vue] + + + +``` + +::important +If you are using `resolveComponent` to handle dynamic components, make sure not to insert anything but the name of the component, which must be a literal string and not be or contain a variable. The string is statically analyzed at the compilation step. +:: + +:video-accordion{title="Watch Daniel Roe's short video about resolveComponent()" videoId="4kq8E5IUM2U"} + +Alternatively, though not recommended, you can register all your components globally, which will create async chunks for all your components and make them available throughout your application. + +```diff + export default defineNuxtConfig({ + components: { ++ global: true, ++ dirs: ['~/components'] + }, + }) +``` + +You can also selectively register some components globally by placing them in a `~/components/global` directory, or by using a `.global.vue` suffix in the filename. As noted above, each global component is rendered in a separate chunk, so be careful not to overuse this feature. + +::note +The `global` option can also be set per component directory. +:: + +## Dynamic Imports + +To dynamically import a component (also known as lazy-loading a component) all you need to do is add the `Lazy` prefix to the component's name. This is particularly useful if the component is not always needed. + +By using the `Lazy` prefix you can delay loading the component code until the right moment, which can be helpful for optimizing your JavaScript bundle size. + +```vue [app/pages/index.vue] + + + +``` + +## Delayed (or Lazy) Hydration + +Lazy components are great for controlling the chunk sizes in your app, but they don't always enhance runtime performance, as they still load eagerly unless conditionally rendered. In real-world applications, some pages may include a lot of content and a lot of components, and most of the time not all of them need to be interactive as soon as the page is loaded. Having them all load eagerly can negatively impact performance. + +In order to optimize your app, you may want to delay the hydration of some components until they're visible, or until the browser is done with more important tasks. + +Nuxt supports this using lazy (or delayed) hydration, allowing you to control when components become interactive. + +### Hydration Strategies + +Nuxt provides a range of built-in hydration strategies. Only one strategy can be used per lazy component. + +::note +Any prop change on a lazily hydrated component will trigger hydration immediately. (e.g., changing a prop on a component with `hydrate-never` will cause it to hydrate) +:: + +::warning +Currently Nuxt's built-in lazy hydration only works in single-file components (SFCs), and requires you to define the prop in the template (rather than spreading an object of props via `v-bind`). It also does not work with direct imports from `#components`. +:: + +#### `hydrate-on-visible` + +Hydrates the component when it becomes visible in the viewport. + +```vue [app/pages/index.vue] + +``` + +::read-more{to="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver" title="IntersectionObserver options"} +Read more about the options for `hydrate-on-visible`. +:: + +::note +Under the hood, this uses Vue's built-in [`hydrateOnVisible` strategy](https://vuejs.org/guide/components/async#hydrate-on-visible). +:: + +#### `hydrate-on-idle` + +Hydrates the component when the browser is idle. This is suitable if you need the component to load as soon as possible, but not block the critical rendering path. + +You can also pass a number which serves as a max timeout. + +```vue [app/pages/index.vue] + +``` + +::note +Under the hood, this uses Vue's built-in [`hydrateOnIdle` strategy](https://vuejs.org/guide/components/async#hydrate-on-idle). +:: + +#### `hydrate-on-interaction` + +Hydrates the component after a specified interaction (e.g., click, mouseover). + +```vue [app/pages/index.vue] + +``` + +If you do not pass an event or list of events, it defaults to hydrating on `pointerenter`, `click` and `focus`. + +::note +Under the hood, this uses Vue's built-in [`hydrateOnInteraction` strategy](https://vuejs.org/guide/components/async#hydrate-on-interaction). +:: + +#### `hydrate-on-media-query` + +Hydrates the component when the window matches a media query. + +```vue [app/pages/index.vue] + +``` + +::note +Under the hood, this uses Vue's built-in [`hydrateOnMediaQuery` strategy](https://vuejs.org/guide/components/async#hydrate-on-media-query). +:: + +#### `hydrate-after` + +Hydrates the component after a specified delay (in milliseconds). + +```vue [app/pages/index.vue] + +``` + +#### `hydrate-when` + +Hydrates the component based on a boolean condition. + +```vue [app/pages/index.vue] + + + +``` + +#### `hydrate-never` + +Never hydrates the component. + +```vue [app/pages/index.vue] + +``` + +### Listening to Hydration Events + +All delayed hydration components emit a `@hydrated` event when they are hydrated. + +```vue [app/pages/index.vue] + + + +``` + +### Caveats and Best Practices + +Delayed hydration can offer performance benefits, but it's essential to use it correctly: + +1. **Prioritize In-Viewport Content:** Avoid delayed hydration for critical, above-the-fold content. It's best suited for content that isn't immediately needed. + +2. **Conditional Rendering:** When using `v-if="false"` on a lazy component, you might not need delayed hydration. You can just use a normal lazy component. + +3. **Shared State:** Be mindful of shared state (`v-model`) across multiple components. Updating the model in one component can trigger hydration in all components bound to that model. + +4. **Use Each Strategy's Intended Use Case:** Each strategy is optimized for a specific purpose. + * `hydrate-when` is best for components that might not always need to be hydrated. + * `hydrate-after` is for components that can wait a specific amount of time. + * `hydrate-on-idle` is for components that can be hydrated when the browser is idle. + +5. **Avoid `hydrate-never` on interactive components:** If a component requires user interaction, it should not be set to never hydrate. + +## Direct Imports + +You can also explicitly import components from `#components` if you want or need to bypass Nuxt's auto-importing functionality. + +```vue [app/pages/index.vue] + + + +``` + +## Custom Directories + +By default, only the `~/components` directory is scanned. If you want to add other directories, or change how the components are scanned within a subfolder of this directory, you can add additional directories to the configuration: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + components: [ + // ~/calendar-module/components/event/Update.vue => + { path: '~/calendar-module/components' }, + + // ~/user-module/components/account/UserDeleteDialog.vue => + { path: '~/user-module/components', pathPrefix: false }, + + // ~/components/special-components/Btn.vue => + { path: '~/components/special-components', prefix: 'Special' }, + + // It's important that this comes last if you have overrides you wish to apply + // to sub-directories of `~/components`. + // + // ~/components/Btn.vue => + // ~/components/base/Btn.vue => + '~/components', + ], +}) +``` + +::note +Any nested directories need to be added first as they are scanned in order. +:: + +## npm Packages + +If you want to auto-import components from an npm package, you can use [`addComponent`](/docs/4.x/api/kit/components#addcomponent) in a [local module](/docs/4.x/directory-structure/modules) to register them. + +::code-group + +```ts twoslash [~/modules/register-component.ts] +import { addComponent, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + setup () { + // import { MyComponent as MyAutoImportedComponent } from 'my-npm-package' + addComponent({ + name: 'MyAutoImportedComponent', + export: 'MyComponent', + filePath: 'my-npm-package', + }) + }, +}) +``` + +```vue [app/app.vue] + +``` + +:: + +## Component Extensions + +By default, any file with an extension specified in the [extensions key of `nuxt.config.ts`](/docs/4.x/api/nuxt-config#extensions) is treated as a component. +If you need to restrict the file extensions that should be registered as components, you can use the extended form of the components directory declaration and its `extensions` key: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + components: [ + { + path: '~/components', + extensions: ['.vue'], // [!code ++] + }, + ], +}) +``` + +## Client Components + +If a component is meant to be rendered only client-side, you can add the `.client` suffix to your component. + +```bash [Directory Structure] +| components/ +--| Comments.client.vue +``` + +```vue [app/pages/example.vue] + +``` + +::note +This feature only works with Nuxt auto-imports and `#components` imports. Explicitly importing these components from their real paths does not convert them into client-only components. +:: + +::important +`.client` components are rendered only after being mounted. To access the rendered template using `onMounted()`, add `await nextTick()` in the callback of the `onMounted()` hook. +:: + +::read-more{to="/docs/4.x/api/components/client-only"} +You can also achieve a similar result with the `` component. +:: + +## Server Components + +Server components allow server-rendering individual components within your client-side apps. It's possible to use server components within Nuxt, even if you are generating a static site. That makes it possible to build complex sites that mix dynamic components, server-rendered HTML and even static chunks of markup. + +Server components can either be used on their own or paired with a [client component](/docs/4.x/directory-structure/app/components#paired-with-a-client-component). + +:video-accordion{title="Watch Learn Vue video about Nuxt Server Components" videoId="u1yyXe86xJM"} + +::tip{icon="i-lucide-newspaper" to="https://roe.dev/blog/nuxt-server-components" target="_blank"} +Read Daniel Roe's guide to Nuxt Server Components. +:: + +### Standalone server components + +Standalone server components will always be rendered on the server, also known as Islands components. + +When their props update, this will result in a network request that will update the rendered HTML in-place. + +Server components are currently experimental and in order to use them, you need to enable the 'component islands' feature in your nuxt.config: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + experimental: { + componentIslands: true, + }, +}) +``` + +Now you can register server-only components with the `.server` suffix and use them anywhere in your application automatically. + +```bash [Directory Structure] +-| components/ +---| HighlightedMarkdown.server.vue +``` + +```vue [app/pages/example.vue] + +``` + +Server-only components use [``](/docs/4.x/api/components/nuxt-island) under the hood, meaning that `lazy` prop and `#fallback` slot are both passed down to it. + +::warning +Server components (and islands) must have a single root element. (HTML comments are considered elements as well.) +:: + +::warning +Props are passed to server components via URL query parameters, and are therefore limited by the possible length of a URL, so be careful not to pass enormous amounts of data to server components via props. +:: + +::warning +Be careful when nesting islands within other islands as each island adds some extra overhead. +:: + +::warning +Most features for server-only components and island components, such as slots and client components, are only available for single file components. +:: + +#### Client components within server components + +::note +This feature needs `experimental.componentIslands.selectiveClient` within your configuration to be true. +:: + +You can partially hydrate a component by setting a `nuxt-client` attribute on the component you wish to be loaded client-side. + +```vue [app/components/ServerWithClient.vue] + +``` + +::note +This only works within a server component. Slots for client components are working only with `experimental.componentIsland.selectiveClient` set to `'deep'` and since they are rendered server-side, they are not interactive once client-side. +:: + +#### Server Component Context + +When rendering a server-only or island component, `` makes a fetch request which comes back with a `NuxtIslandResponse`. (This is an internal request if rendered on the server, or a request that you can see in the network tab if it's rendering on client-side navigation.) + +This means: + +* A new Vue app will be created server-side to create the `NuxtIslandResponse`. +* A new 'island context' will be created while rendering the component. +* You can't access the 'island context' from the rest of your app and you can't access the context of the rest of your app from the island component. In other words, the server component or island is _isolated_ from the rest of your app. +* Your plugins will run again when rendering the island, unless they have `env: { islands: false }` set (which you can do in an object-syntax plugin). + +::important +Route middleware does not run when rendering island components. Middleware is a routing concept that applies to pages, not components, and is not designed to control component rendering. +:: + +::important +`useRoute()` and other `vue-router` composables do not track the current page route inside a server (island) component. The island is rendered in its own isolated Vue app keyed only on its props (and any explicit context), which is what keeps islands cacheable independently of the page they are rendered on. Inside an island, `useRoute()` will reflect the island's own request, not the page the user is on. + +If an island needs information about the current route, pass it in explicitly — either as props from the parent component, or via the `context` prop on `` (read inside the island from `nuxtApp.ssrContext.islandContext`). +:: + +Within an island component, you can access its island context through `nuxtApp.ssrContext.islandContext`. Note that while island components are still marked as experimental, the format of this context may change. + +::note +Slots can be interactive and are wrapped within a `
` with `display: contents;` +:: + +### Paired with a Client component + +In this case, the `.server` + `.client` components are two 'halves' of a component and can be used in advanced use cases for separate implementations of a component on server and client side. + +```bash [Directory Structure] +-| components/ +---| Comments.client.vue +---| Comments.server.vue +``` + +```vue [app/pages/example.vue] + +``` + +## Built-In Nuxt Components + +There are a number of components that Nuxt provides, including `` and ``. You can read more about them in the API documentation. + +::read-more{to="/docs/4.x/api"} +:: + +## Library Authors + +Making Vue component libraries with automatic tree-shaking and component registration is super easy. ✨ + +You can use the [`addComponentsDir`](/docs/4.x/api/kit/components#addcomponentsdir) method provided from the `@nuxt/kit` to register your components directory in your Nuxt module. + +Imagine a directory structure like this: + +```bash [Directory Structure] +-| node_modules/ +---| awesome-ui/ +-----| components/ +-------| Alert.vue +-------| Button.vue +-----| nuxt.ts +-| pages/ +---| index.vue +-| nuxt.config.ts +``` + +Then in `awesome-ui/nuxt.ts` you can use the `addComponentsDir` hook: + +```ts twoslash +import { addComponentsDir, createResolver, defineNuxtModule } from '@nuxt/kit' + +export default defineNuxtModule({ + setup () { + const resolver = createResolver(import.meta.url) + + // Add ./components dir to the list + addComponentsDir({ + path: resolver.resolve('./components'), + prefix: 'awesome', + }) + }, +}) +``` + +That's it! Now in your project, you can import your UI library as a Nuxt module in your `nuxt.config` file: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + modules: ['awesome-ui/nuxt'], +}) +``` + +... and directly use the module components (prefixed with `awesome-`) in our `app/pages/index.vue`: + +```vue + +``` + +It will automatically import the components only if used and also support HMR when updating your components in `node_modules/awesome-ui/components/`. + +:link-example{to="/docs/4.x/examples/features/auto-imports"} diff --git a/reference/2.directory-structure/1.app/1.composables.md b/reference/2.directory-structure/1.app/1.composables.md new file mode 100644 index 0000000..0a11e0d --- /dev/null +++ b/reference/2.directory-structure/1.app/1.composables.md @@ -0,0 +1,121 @@ +--- +title: 'composables' +head.title: 'composables/' +description: Use the composables/ directory to auto-import your Vue composables into your application. +navigation.icon: i-vscode-icons-folder-type-src +--- + +## Usage + +**Method 1:** Using named export + +```ts [app/composables/useFoo.ts] +export const useFoo = () => { + return useState('foo', () => 'bar') +} +``` + +**Method 2:** Using default export + +```ts [app/composables/use-foo.ts or composables/useFoo.ts] +// It will be available as useFoo() (camelCase of file name without extension) +export default function () { + return useState('foo', () => 'bar') +} +``` + +**Usage:** You can now use auto imported composable in `.js`, `.ts` and `.vue` files + +```vue [app/app.vue] + + + +``` + +::note +The `app/composables/` directory in Nuxt does not provide any additional reactivity capabilities to your code. Instead, any reactivity within composables is achieved using Vue's Composition API mechanisms, such as ref and reactive. Note that reactive code is also not limited to the boundaries of the `app/composables/` directory. You are free to employ reactivity features wherever they're needed in your application. +:: + +:read-more{to="/docs/4.x/guide/concepts/auto-imports"} + +:link-example{to="/docs/4.x/examples/features/auto-imports"} + +## Types + +Under the hood, Nuxt auto generates the file `.nuxt/imports.d.ts` to declare the types. + +Be aware that you have to run [`nuxt prepare`](/docs/4.x/api/commands/prepare), [`nuxt dev`](/docs/4.x/api/commands/dev) or [`nuxt build`](/docs/4.x/api/commands/build) in order to let Nuxt generate the types. + +::note +If you create a composable without having the dev server running, TypeScript will throw an error, such as `Cannot find name 'useBar'.` +:: + +## Examples + +### Nested Composables + +You can use a composable within another composable using auto imports: + +```ts [app/composables/test.ts] +export const useFoo = () => { + const nuxtApp = useNuxtApp() + const bar = useBar() +} +``` + +### Access plugin injections + +You can access [plugin injections](/docs/4.x/directory-structure/app/plugins#providing-helpers) from composables: + +```ts [app/composables/test.ts] +export const useHello = () => { + const nuxtApp = useNuxtApp() + return nuxtApp.$hello +} +``` + +## How Files Are Scanned + +Nuxt only scans files at the top level of the [`app/composables/` directory](/docs/4.x/directory-structure/app/composables), e.g.: + +```bash [Directory Structure] +-| composables/ +---| index.ts // scanned +---| useFoo.ts // scanned +---| nested/ +-----| utils.ts // not scanned +``` + +Only `app/composables/index.ts` and `app/composables/useFoo.ts` would be searched for imports. + +To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories: + +**Example:** Re-export the composables you need from the `app/composables/index.ts` file: + +```ts [app/composables/index.ts] +// Enables auto import for this export +export { utils } from './nested/utils.ts' +``` + +**Example:** Scan nested directories inside the `app/composables/` folder: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + imports: { + dirs: [ + // Scan top-level composables + '~/composables', + // ... or scan composables nested one level deep with a specific name and file extension + '~/composables/*/index.{ts,js,mjs,mts}', + // ... or scan all composables within given directory + '~/composables/**', + ], + }, +}) +``` diff --git a/reference/2.directory-structure/1.app/1.layouts.md b/reference/2.directory-structure/1.app/1.layouts.md new file mode 100644 index 0000000..7698df9 --- /dev/null +++ b/reference/2.directory-structure/1.app/1.layouts.md @@ -0,0 +1,275 @@ +--- +title: "layouts" +head.title: "layouts/" +description: "Nuxt provides a layouts framework to extract common UI patterns into reusable layouts." +navigation.icon: i-vscode-icons-folder-type-view +--- + +::tip{icon="i-lucide-rocket" } +For best performance, components placed in this directory will be automatically loaded via asynchronous import when used. +:: + +## Enable Layouts + +Layouts are enabled by adding [``](/docs/4.x/api/components/nuxt-layout) to your [`app.vue`](/docs/4.x/directory-structure/app/app): + +```vue [app/app.vue] + +``` + +To use a layout: +- Set a `layout` property in your page with [definePageMeta](/docs/4.x/api/utils/define-page-meta). +- Set the `name` prop of ``. +- Set the `appLayout` property in route rules. + +::note +The layout name is normalized to kebab-case, so `someLayout` becomes `some-layout`. +:: + +::note +If no layout is specified, `app/layouts/default.vue` will be used. +:: + +::important +If you only have a single layout in your application, we recommend using [`app.vue`](/docs/4.x/directory-structure/app/app) instead. +:: + +::important +Unlike other components, your layouts must have a single root element to allow Nuxt to apply transitions between layout changes - and this root element cannot be a ``. +:: + +## Default Layout + +Add a `~/layouts/default.vue`: + +```vue [app/layouts/default.vue] + +``` + +In a layout file, the content of the page will be displayed in the `` component. + +## Named Layout + +```bash [Directory Structure] +-| layouts/ +---| default.vue +---| custom.vue +``` + +Then you can use the `custom` layout in your page: + +```vue twoslash [pages/about.vue] + +``` + +::read-more{to="/docs/4.x/directory-structure/app/pages#page-metadata"} +Learn more about `definePageMeta`. +:: + +You can directly override the default layout for all pages using the `name` property of [``](/docs/4.x/api/components/nuxt-layout): + +```vue [app/app.vue] + + + +``` + +If you have a layout in nested directories, the layout's name will be based on its own path directory and filename, with duplicate segments being removed. + +File | Layout Name +-- | -- +`~/layouts/desktop/default.vue` | `desktop-default` +`~/layouts/desktop-base/base.vue` | `desktop-base` +`~/layouts/desktop/index.vue` | `desktop` + +For clarity, we recommend that the layout's filename matches its name: + +File | Layout Name +-- | -- +`~/layouts/desktop/DesktopDefault.vue` | `desktop-default` +`~/layouts/desktop-base/DesktopBase.vue` | `desktop-base` +`~/layouts/desktop/Desktop.vue` | `desktop` + +:link-example{to="/docs/4.x/examples/features/layouts"} + +## Changing the Layout Dynamically + +You can also use the [`setPageLayout`](/docs/4.x/api/utils/set-page-layout) helper to change the layout dynamically: + +```vue twoslash [app/pages/index.vue] + + + +``` + +You can also set layouts for specific routes using the `appLayout` property in route rules: + +```ts [nuxt.config.ts] +export default defineNuxtConfig({ + routeRules: { + // Set layout for specific route + '/admin': { appLayout: 'admin' }, + // Set layout for multiple routes + '/dashboard/**': { appLayout: 'dashboard' }, + // Disable layout for a route + '/landing': { appLayout: false }, + }, +}) +``` + +::tip +This is useful when you want to manage layouts centrally in your configuration rather than in each page file, or when you need to apply layouts to routes that don't have corresponding page components (such as catchall pages which might match many paths). +:: + +:link-example{to="/docs/4.x/examples/features/layouts"} + +## Passing Props to Layouts :badge[+4.4]{color="primary" class="align-middle"} + +You can pass props to layouts in several ways. + +### Via `definePageMeta` + +Use the object syntax for the `layout` property to pass props directly from your page: + +::code-group + +```vue [app/pages/dashboard.vue] + +``` + +```vue [app/layouts/panel.vue] + + + +``` + +:: + +::tip +Props are fully typed based on your layout's `defineProps`. You'll get autocomplete and type-checking in your editor. +:: + +### Via `setPageLayout` + +You can also pass props when changing the layout dynamically with [`setPageLayout`](/docs/4.x/api/utils/set-page-layout): + +```ts +setPageLayout('panel', { sidebar: true, title: 'Dashboard' }) +``` + +## Overriding a Layout on a Per-page Basis + +If you are using pages, you can take full control by setting `layout: false` and then using the `` component within the page. + +::code-group + +```vue [app/pages/index.vue] + + + +``` + +```vue [app/layouts/custom.vue] + +``` + +:: + +::important +If you use `` within your pages, make sure it is not the root element (or [disable layout/page transitions](/docs/4.x/getting-started/transitions#disable-transitions)). +:: diff --git a/reference/2.directory-structure/1.app/1.middleware.md b/reference/2.directory-structure/1.app/1.middleware.md new file mode 100644 index 0000000..7135bed --- /dev/null +++ b/reference/2.directory-structure/1.app/1.middleware.md @@ -0,0 +1,253 @@ +--- +title: "middleware" +description: "Nuxt provides middleware to run code before navigating to a particular route." +head.title: "middleware/" +navigation.icon: i-vscode-icons-folder-type-middleware +--- + +Nuxt provides a customizable **route middleware** framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route. + +There are three kinds of route middleware: + +1. Anonymous (or inline) route middleware are defined directly within the page. +2. Named route middleware, placed in the `app/middleware/` and automatically loaded via asynchronous import when used on a page. +3. Global route middleware, placed in the `app/middleware/` with a `.global` suffix and is run on every route change. + +The first two kinds of route middleware can be defined in [`definePageMeta`](/docs/4.x/api/utils/define-page-meta). + +::note +Name of middleware are normalized to kebab-case: `myMiddleware` becomes `my-middleware`. +:: + +::note +Route middleware run within the Vue part of your Nuxt app. Despite the similar name, they are completely different from [server middleware](/docs/4.x/directory-structure/server#server-middleware), which are run in the Nitro server part of your app. +:: + +:video-accordion{title="Watch a video from Vue School on all 3 kinds of middleware" videoId="761471577" platform="vimeo"} + +## Usage + +Route middleware are navigation guards that receive the current route and the next route as arguments. + +```ts twoslash [middleware/my-middleware.ts] +export default defineNuxtRouteMiddleware((to, from) => { + if (to.params.id === '1') { + return abortNavigation() + } + // In a real app you would probably not redirect every route to `/` + // however it is important to check `to.path` before redirecting or you + // might get an infinite redirect loop + if (to.path !== '/') { + return navigateTo('/') + } +}) +``` + +Nuxt provides two globally available helpers that can be returned directly from the middleware. + +1. [`navigateTo`](/docs/4.x/api/utils/navigate-to) - Redirects to the given route +2. [`abortNavigation`](/docs/4.x/api/utils/abort-navigation) - Aborts the navigation, with an optional error message. + +Unlike [navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards) from `vue-router`, a third `next()` argument is not passed, and **redirect or route cancellation is handled by returning a value from the middleware**. + +Possible return values are: + +* nothing (a simple `return` or no return at all) - does not block navigation and will move to the next middleware function, if any, or complete the route navigation +* `return navigateTo('/')` - redirects to the given path and will set the redirect code to [`302` Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302) if the redirect happens on the server side +* `return navigateTo('/', { redirectCode: 301 })` - redirects to the given path and will set the redirect code to [`301` Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301) if the redirect happens on the server side +* `return abortNavigation()` - stops the current navigation +* `return abortNavigation(error)` - rejects the current navigation with an error + +:read-more{to="/docs/4.x/api/utils/navigate-to"} +:read-more{to="/docs/4.x/api/utils/abort-navigation"} + +::important +We recommend using the helper functions above for performing redirects or stopping navigation. Other possible return values described in [the vue-router docs](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards) may work but there may be breaking changes in future. +:: + +## Middleware Order + +Middleware runs in the following order: + +1. Global Middleware +2. Page defined middleware order (if there are multiple middleware declared with the array syntax) + +For example, assuming you have the following middleware and component: + +```bash [app/middleware/ directory] +-| middleware/ +---| analytics.global.ts +---| setup.global.ts +---| auth.ts +``` + +```vue twoslash [pages/profile.vue] + +``` + +You can expect the middleware to be run in the following order: + +1. `analytics.global.ts` +2. `setup.global.ts` +3. Custom inline middleware +4. `auth.ts` + +### Ordering Global Middleware + +By default, global middleware is executed alphabetically based on the filename. + +However, there may be times you want to define a specific order. For example, in the last scenario, `setup.global.ts` may need to run before `analytics.global.ts`. In that case, we recommend prefixing global middleware with 'alphabetical' numbering. + +```bash [Directory structure] +-| middleware/ +---| 01.setup.global.ts +---| 02.analytics.global.ts +---| auth.ts +``` + +::note +In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example, `10.new.global.ts` would come before `2.new.global.ts`. This is why the example prefixes single digit numbers with `0`. +:: + +## When Middleware Runs + +If your site is server-rendered or generated, middleware for the initial page will be executed both when the page is rendered and then again on the client. This might be needed if your middleware needs a browser environment, such as if you have a generated site, aggressively cache responses, or want to read a value from local storage. + +However, if you want to avoid this behaviour you can do so: + +```ts twoslash [middleware/example.ts] +export default defineNuxtRouteMiddleware((to) => { + // skip middleware on server + if (import.meta.server) { + return + } + // skip middleware on client side entirely + if (import.meta.client) { + return + } + // or only skip middleware on initial client load + const nuxtApp = useNuxtApp() + if (import.meta.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) { + return + } +}) +``` + +This is true even if you throw an error in your middleware on the server, and an error page is rendered. The middleware will still run again in the browser. + +::note +Rendering an error page is an entirely separate page load, meaning any registered middleware will run again. You can use [`useError`](/docs/4.x/getting-started/error-handling#useerror) in middleware to check if an error is being handled. +:: + +## Accessing Route in Middleware + +Always use the `to` and `from` parameters in your middleware to access the next and previous routes. Avoid using the [`useRoute()`](/docs/4.x/api/composables/use-route) composable in this context altogether. +There is **no concept of a "current route" in middleware**, as middleware can abort a navigation or redirect to a different route. The `useRoute()` composable will always be inaccurate in this context. + +::warning +Sometimes, you might call a composable that uses `useRoute()` internally, which can trigger this warning even if there is no direct call in your middleware. +This leads to the **same issue as above**, so you should structure your functions to accept the route as an argument instead when they are used in middleware. +:: + +::code-group +```ts twoslash [middleware/access-route.ts] +// @errors: 2304 +export default defineNuxtRouteMiddleware((to) => { + // passing the route to the function to avoid calling `useRoute()` in middleware + doSomethingWithRoute(to) + + // ❌ this will output a warning and is NOT recommended + callsRouteInternally() +}) +``` + +```ts twoslash [utils/handle-route.ts] +// providing the route as an argument so that it can be used in middleware correctly +export function doSomethingWithRoute (route = useRoute()) { + // ... +} +``` +```ts twoslash [utils/dont-do-this.ts] +// ❌ this function is not suitable for use in middleware +export function callsRouteInternally () { + const route = useRoute() + // ... +} +``` + +:: + +## Adding Middleware Dynamically + +It is possible to add global or named route middleware manually using the [`addRouteMiddleware()`](/docs/4.x/api/utils/add-route-middleware) helper function, such as from within a plugin. + +```ts twoslash +export default defineNuxtPlugin(() => { + addRouteMiddleware('global-test', () => { + console.log('this global middleware was added in a plugin and will be run on every route change') + }, { global: true }) + + addRouteMiddleware('named-test', () => { + console.log('this named middleware was added in a plugin and would override any existing middleware of the same name') + }) +}) +``` + +## Example + +```bash [Directory Structure] +-| middleware/ +---| auth.ts +``` + +In your page file, you can reference this route middleware: + +```vue twoslash + +``` + +Now, before navigation to that page can complete, the `auth` route middleware will be run. + +:link-example{to="/docs/4.x/examples/routing/middleware"} + +## Setting Middleware at Build Time + +Instead of using `definePageMeta` on each page, you can add named route middleware within the `pages:extend` hook. + +```ts twoslash [nuxt.config.ts] +import type { NuxtPage } from 'nuxt/schema' + +export default defineNuxtConfig({ + hooks: { + 'pages:extend' (pages) { + function setMiddleware (pages: NuxtPage[]) { + for (const page of pages) { + if (/* some condition */ Math.random() > 0.5) { + page.meta ||= {} + // Note that this will override any middleware set in `definePageMeta` in the page + page.meta.middleware = ['named'] + } + if (page.children) { + setMiddleware(page.children) + } + } + } + setMiddleware(pages) + }, + }, +}) +``` diff --git a/reference/2.directory-structure/1.app/1.pages.md b/reference/2.directory-structure/1.app/1.pages.md new file mode 100644 index 0000000..a4390b8 --- /dev/null +++ b/reference/2.directory-structure/1.app/1.pages.md @@ -0,0 +1,467 @@ +--- +title: "pages" +description: "Nuxt provides file-based routing to create routes within your web application." +head.title: "pages/" +navigation.icon: i-vscode-icons-folder-type-view +--- + +::note +To reduce your application's bundle size, this directory is **optional**, meaning that [`vue-router`](https://router.vuejs.org) won't be included if you only use [`app.vue`](/docs/4.x/directory-structure/app/app). To force the pages system, set `pages: true` in `nuxt.config` or have a [`router.options.ts`](/docs/4.x/guide/recipes/custom-routing#using-routeroptions). +:: + +## Usage + +Pages are Vue components and can have any [valid extension](/docs/4.x/api/nuxt-config#extensions) that Nuxt supports (by default `.vue`, `.js`, `.jsx`, `.mjs`, `.ts` or `.tsx`). + +Nuxt will automatically create a route for every page in your `~/pages/` directory. + +::code-group + +```vue [app/pages/index.vue] + +``` + +```ts twoslash [pages/index.ts] +// https://vuejs.org/guide/extras/render-function.html +export default defineComponent({ + render () { + return h('h1', 'Index page') + }, +}) +``` + +```tsx twoslash [pages/index.tsx] +// https://nuxt.com/docs/4.x/examples/advanced/jsx +// https://vuejs.org/guide/extras/render-function.html#jsx-tsx +export default defineComponent({ + render () { + return

Index page

+ }, +}) +``` + +:: + +The `app/pages/index.vue` file will be mapped to the `/` route of your application. + +If you are using [`app.vue`](/docs/4.x/directory-structure/app/app), make sure to use the [``](/docs/4.x/api/components/nuxt-page) component to display the current page: + +```vue [app/app.vue] + +``` + +Pages **must have a single root element** to allow [route transitions](/docs/4.x/getting-started/transitions) between pages. HTML comments are considered elements as well. + +This means that when the route is server-rendered, or statically generated, you will be able to see its contents correctly, but when you navigate towards that route during client-side navigation the transition between routes will fail and you'll see that the route will not be rendered. + +Here are some examples to illustrate what a page with a single root element looks like: + +::code-group + +```vue [app/pages/working.vue] + +``` + +```vue [app/pages/bad-1.vue] + +``` + +```vue [app/pages/bad-2.vue] + +``` + +:: + +## Dynamic Routes + +If you place anything within square brackets, it will be turned into a [dynamic route](https://router.vuejs.org/guide/essentials/dynamic-matching) parameter. You can mix and match multiple parameters and even non-dynamic text within a file name or directory. + +If you want a parameter to be _optional_, you must enclose it in double square brackets - for example, `~/pages/[[slug]]/index.vue` or `~/pages/[[slug]].vue` will match both `/` and `/test`. + +```bash [Directory Structure] +-| pages/ +---| index.vue +---| users-[group]/ +-----| [id].vue +``` + +Given the example above, you can access group/id within your component via the `$route` object: + +```vue [app/pages/users-[group\\]/[id\\].vue] + +``` + +Navigating to `/users-admins/123` would render: + +```html +

admins - 123

+``` + +If you want to access the route using Composition API, there is a global [`useRoute`](/docs/4.x/api/composables/use-route) function that will allow you to access the route just like `this.$route` in the Options API. + +```vue twoslash + +``` + +::note +Named parent routes will take priority over nested dynamic routes. For the `/foo/hello` route, `~/pages/foo.vue` will take priority over `~/pages/foo/[slug].vue`. :br Use `~/pages/foo/index.vue` and `~/pages/foo/[slug].vue` to match `/foo` and `/foo/hello` with different pages,. +:: + +:video-accordion{title="Watch a video from Vue School on dynamic routes" videoId="754465699" platform="vimeo"} + +## Catch-all Route + +If you need a catch-all route, you create it by using a file named like `[...slug].vue`. This will match _all_ routes under that path. + +```vue [app/pages/[...slug\\].vue] + +``` + +Navigating to `/hello/world` would render: + +```html +

["hello", "world"]

+``` + +## Nested Routes + +It is possible to display [nested routes](https://router.vuejs.org/guide/essentials/nested-routes) with ``. + +Example: + +```bash [Directory Structure] +-| pages/ +---| parent/ +-----| child.vue +---| parent.vue +``` + +This file tree will generate these routes: + +```js +[ + { + path: '/parent', + component: '~/pages/parent.vue', + name: 'parent', + children: [ + { + path: 'child', + component: '~/pages/parent/child.vue', + name: 'parent-child', + }, + ], + }, +] +``` + +To display the `child.vue` component, you have to insert the `` component inside `app/pages/parent.vue`: + +```vue {}[pages/parent.vue] + +``` + +```vue {}[pages/parent/child.vue] + +``` + +### Child Route Keys + +If you want more control over when the `` component is re-rendered (for example, for transitions), you can either pass a string or function via the `pageKey` prop, or you can define a `key` value via `definePageMeta`: + +```vue {}[pages/parent.vue] + +``` + +Or alternatively: + +```vue twoslash {}[pages/parent/child.vue] + +``` + +:link-example{to="/docs/4.x/examples/routing/pages"} + +## Route Groups + +In some cases, you may want to group a set of routes together in a way which doesn't affect file-based routing. For this purpose, you can put files in a folder which is wrapped in parentheses - `(` and `)`. + +For example: + +```bash [Directory structure] +-| pages/ +---| index.vue +---| (marketing)/ +-----| about.vue +-----| contact.vue +``` + +This will produce `/`, `/about` and `/contact` pages in your app. The `marketing` group is ignored for purposes of your URL structure. + +### Accessing Route Groups + +Route groups are automatically available in the route metadata as `route.meta.groups`. +This allows you to access the group information in your components for conditional logic, styling, or other purposes. + +```vue {}[pages/(marketing)/about.vue] + + + +``` + +## Page Metadata + +You might want to define metadata for each route in your app. You can do this using the `definePageMeta` macro, which will work both in ` +``` + +This data can then be accessed throughout the rest of your app from the `route.meta` object. + +```vue twoslash + +``` + +If you are using nested routes, the page metadata from all these routes will be merged into a single object. For more on route meta, see the [vue-router docs](https://router.vuejs.org/guide/advanced/meta). + +Much like `defineEmits` or `defineProps` (see [Vue docs](https://vuejs.org/api/sfc-script-setup#defineprops-defineemits)), `definePageMeta` is a **compiler macro**. It will be compiled away so you cannot reference it within your component. Instead, the metadata passed to it will be hoisted out of the component. +Therefore, the page meta object cannot reference the component. However, it can reference imported bindings, as well as locally defined **pure functions**. + +::warning +Make sure not to reference any reactive data or functions that cause side effects. This can lead to unexpected behavior. +:: + +```vue + +``` + +### Special Metadata + +Of course, you are welcome to define metadata for your own use throughout your app. But some metadata defined with `definePageMeta` has a particular purpose: + +#### `alias` + +You can define page aliases. They allow you to access the same page from different paths. It can be either a string or an array of strings as defined [in the vue-router documentation](https://router.vuejs.org/guide/essentials/redirect-and-alias#Alias). + +#### `keepalive` + +Nuxt will automatically wrap your page in [the Vue `` component](https://vuejs.org/guide/built-ins/keep-alive#keepalive) if you set `keepalive: true` in your `definePageMeta`. This might be useful to do, for example, in a parent route that has dynamic child routes, if you want to preserve page state across route changes. + +When your goal is to preserve state for parent routes use this syntax: ``. You can also set props to be passed to `` (see [a full list](https://vuejs.org/api/built-in-components#keepalive)). + +You can set a default value for this property [in your `nuxt.config`](/docs/4.x/api/nuxt-config#keepalive). + +#### `key` + +[See above](/docs/4.x/directory-structure/app/pages#child-route-keys). + +#### `layout` + +You can define the layout used to render the route. This can be either false (to disable any layout), a string or a ref/computed, if you want to make it reactive in some way. [More about layouts](/docs/4.x/directory-structure/app/layouts). + +#### `layoutTransition` and `pageTransition` + +You can define transition properties for the `` component that wraps your pages and layouts, or pass `false` to disable the `` wrapper for that route. You can see [a list of options that can be passed](https://vuejs.org/api/built-in-components#transition) or read [more about how transitions work](https://vuejs.org/guide/built-ins/transition#transition). + +You can set default values for these properties [in your `nuxt.config`](/docs/4.x/api/nuxt-config#layouttransition). + +#### `middleware` + +You can define middleware to apply before loading this page. It will be merged with all the other middleware used in any matching parent/child routes. It can be a string, a function (an anonymous/inlined middleware function following [the global before guard pattern](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards)), or an array of strings/functions. [More about named middleware](/docs/4.x/directory-structure/app/middleware). + +#### `name` + +You may define a name for this page's route. + +#### `path` + +You may define a path matcher, if you have a more complex pattern than can be expressed with the file name. See [the `vue-router` docs](https://router.vuejs.org/guide/essentials/route-matching-syntax#Custom-regex-in-params) for more information. + +#### `props` + +Allows accessing the route `params` as props passed to the page component. See [the `vue-router` docs](https://router.vuejs.org/guide/essentials/passing-props) for more information. + +### Typing Custom Metadata + +If you add custom metadata for your pages, you may wish to do so in a type-safe way. It is possible to augment the type of the object accepted by `definePageMeta`: + +```ts [index.d.ts] +declare module '#app' { + interface PageMeta { + pageType?: string + } +} + +// It is always important to ensure you import/export something when augmenting a type +export {} +``` + +## Navigation + +To navigate between pages of your app, you should use the [``](/docs/4.x/api/components/nuxt-link) component. + +This component is included with Nuxt and therefore you don't have to import it as you do with other components. + +A simple link to the `index.vue` page in your `app/pages` folder: + +```vue + +``` + +::read-more{to="/docs/4.x/api/components/nuxt-link"} +Learn more about `` usage. +:: + +## Programmatic Navigation + +Nuxt allows programmatic navigation through the `navigateTo()` utility method. Using this utility method, you will be able to programmatically navigate the user in your app. This is great for taking input from the user and navigating them dynamically throughout your application. In this example, we have a simple method called `navigate()` that gets called when the user submits a search form. + +::note +Make sure to always `await` on `navigateTo` or chain its result by returning from functions. +:: + +```vue twoslash + +``` + +## Client-Only Pages + +You can define a page as [client only](/docs/4.x/directory-structure/app/components#client-components) by giving it a `.client.vue` suffix. None of the content of this page will be rendered on the server. + +## Server-Only Pages + +You can define a page as [server only](/docs/4.x/directory-structure/app/components#server-components) by giving it a `.server.vue` suffix. While you will be able to navigate to the page using client-side navigation, controlled by `vue-router`, it will be rendered with a server component automatically, meaning the code required to render the page will not be in your client-side bundle. + +::warning +Server-only pages must have a single root element. (HTML comments are considered elements as well.) +:: + +## Custom Routing + +As your app gets bigger and more complex, your routing might require more flexibility. For this reason, Nuxt directly exposes the router, routes and router options for customization in different ways. + +:read-more{to="/docs/4.x/guide/recipes/custom-routing"} + +## Multiple Pages Directories + +By default, all your pages should be in one `app/pages` directory at the root of your project. + +However, you can use [Nuxt Layers](/docs/4.x/getting-started/layers) to create groupings of your app's pages: + +```bash [Directory Structure] +-| some-app/ +---| nuxt.config.ts +---| pages/ +-----| app-page.vue +-| nuxt.config.ts +``` + +```ts twoslash [some-app/nuxt.config.ts] +// some-app/nuxt.config.ts +export default defineNuxtConfig({ +}) +``` + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + extends: ['./some-app'], +}) +``` + +:read-more{to="/docs/4.x/guide/going-further/layers"} diff --git a/reference/2.directory-structure/1.app/1.plugins.md b/reference/2.directory-structure/1.app/1.plugins.md new file mode 100644 index 0000000..a79a6b7 --- /dev/null +++ b/reference/2.directory-structure/1.app/1.plugins.md @@ -0,0 +1,298 @@ +--- +title: "plugins" +description: "Nuxt has a plugins system to use Vue plugins and more at the creation of your Vue application." +head.title: "plugins/" +navigation.icon: i-vscode-icons-folder-type-plugin +--- + +Nuxt automatically reads the files in the `app/plugins/` directory and loads them at the creation of the Vue application. + +::note +All plugins inside are auto-registered, you don't need to add them to your `nuxt.config` separately. +:: + +::note +You can use `.server` or `.client` suffix in the file name to load a plugin only on the server or client side. +:: + +## Registered Plugins + +Only files at the top level of the directory (or index files within any subdirectories) will be auto-registered as plugins. + +```bash [Directory structure] +-| plugins/ +---| foo.ts // scanned +---| bar/ +-----| baz.ts // not scanned +-----| foz.vue // not scanned +-----| index.ts // currently scanned but deprecated +``` + +Only `foo.ts` and `bar/index.ts` would be registered. + +To add plugins in subdirectories, you can use the [`app/plugins`](/docs/4.x/api/nuxt-config#plugins-1) option in `nuxt.config.ts`: + +```ts twoslash [nuxt.config.ts] +export default defineNuxtConfig({ + plugins: [ + '~/plugins/bar/baz', + '~/plugins/bar/foz', + ], +}) +``` + +## Creating Plugins + +The only argument passed to a plugin is [`nuxtApp`](/docs/4.x/api/composables/use-nuxt-app). + +```ts twoslash [plugins/hello.ts] +export default defineNuxtPlugin((nuxtApp) => { + // Doing something with nuxtApp +}) +``` + +### Object Syntax Plugins + +It is also possible to define a plugin using an object syntax, for more advanced use cases. For example: + +```ts twoslash [plugins/hello.ts] +export default defineNuxtPlugin({ + name: 'my-plugin', + enforce: 'pre', // or 'post' + async setup (nuxtApp) { + // this is the equivalent of a normal functional plugin + }, + hooks: { + // You can directly register Nuxt app runtime hooks here + 'app:created' () { + const nuxtApp = useNuxtApp() + // do something in the hook + }, + }, + env: { + // Set this value to `false` if you don't want the plugin to run when rendering server-only or island components. + islands: true, + }, +}) +``` + +:video-accordion{title="Watch a video from Alexander Lichter about the Object Syntax for Nuxt plugins" videoId="2aXZyXB1QGQ"} + +::note +If you are using the object-syntax, the properties are statically analyzed to produce a more optimized build. So you should not define them at runtime. :br +For example, setting `enforce: import.meta.server ? 'pre' : 'post'` would defeat any future optimization Nuxt is able to do for your plugins. +Nuxt does statically pre-load any hook listeners when using object-syntax, allowing you to define hooks without needing to worry about order of plugin registration. +:: + +## Registration Order + +You can control the order in which plugins are registered by prefixing with 'alphabetical' numbering to the file names. + +```bash [Directory structure] +plugins/ + | - 01.myPlugin.ts + | - 02.myOtherPlugin.ts +``` + +In this example, `02.myOtherPlugin.ts` will be able to access anything that was injected by `01.myPlugin.ts`. + +This is useful in situations where you have a plugin that depends on another plugin. + +::note +In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example, `10.myPlugin.ts` would come before `2.myOtherPlugin.ts`. This is why the example prefixes single digit numbers with `0`. +:: + +## Loading Strategy + +### Parallel Plugins + +By default, Nuxt loads plugins sequentially. You can define a plugin as `parallel` so Nuxt won't wait until the end of the plugin's execution before loading the next plugin. + +```ts twoslash [plugins/my-plugin.ts] +export default defineNuxtPlugin({ + name: 'my-plugin', + parallel: true, + async setup (nuxtApp) { + // the next plugin will be executed immediately + }, +}) +``` + +### Plugins With Dependencies + +If a plugin needs to wait for another plugin before it runs, you can add the plugin's name to the `dependsOn` array. + +```ts twoslash [plugins/depending-on-my-plugin.ts] +export default defineNuxtPlugin({ + name: 'depends-on-my-plugin', + dependsOn: ['my-plugin'], + async setup (nuxtApp) { + // this plugin will wait for the end of `my-plugin`'s execution before it runs + }, +}) +``` + +## Using Composables + +You can use [composables](/docs/4.x/directory-structure/app/composables) as well as [utils](/docs/4.x/directory-structure/app/utils) within Nuxt plugins: + +```ts [app/plugins/hello.ts] +export default defineNuxtPlugin((nuxtApp) => { + const foo = useFoo() +}) +``` + +However, keep in mind there are some limitations and differences: + +::important +**If a composable depends on another plugin registered later, it might not work.** :br + +Plugins are called in order sequentially and before everything else. You might use a composable that depends on another plugin which has not been called yet. +:: + +::important +**If a composable depends on the Vue.js lifecycle, it won't work.** :br + +Normally, Vue.js composables are bound to the current component instance while plugins are only bound to [`nuxtApp`](/docs/4.x/api/composables/use-nuxt-app) instance. +:: + +## Providing Helpers + +If you would like to provide a helper on the [`NuxtApp`](/docs/4.x/api/composables/use-nuxt-app) instance, return it from the plugin under a `provide` key. + +::code-group +```ts twoslash [plugins/hello.ts] +export default defineNuxtPlugin(() => { + return { + provide: { + hello: (msg: string) => `Hello ${msg}!`, + }, + } +}) +``` +```ts twoslash [plugins/hello-object-syntax.ts] +export default defineNuxtPlugin({ + name: 'hello', + setup () { + return { + provide: { + hello: (msg: string) => `Hello ${msg}!`, + }, + } + }, +}) +``` +:: + +You can then use the helper in your components: + +```vue [app/components/Hello.vue] + + + +``` + +::important +Note that we highly recommend using [`composables`](/docs/4.x/directory-structure/app/composables) instead of providing helpers to avoid polluting the global namespace and keep your main bundle entry small. +:: + +::warning +**If your plugin provides a `ref` or `computed`, it will not be unwrapped in a component `