Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 87 ยท Performance, Security and Ecosystem

Nuxt Overview

Get to know Nuxt: file-based routing, auto imports, useFetch, server routes, rendering modes and deployment, with runnable stand-ins for its core ideas.

Vue by itself is a view library with an excellent core, and you choose the rest: a router, a state library, a build setup, server rendering, deployment. Nuxt is the full-stack framework built on top of Vue that makes those choices for you. You create files in the right folders, and Nuxt turns them into routes, API endpoints, server-rendered pages and an optimized build.

This lesson is a tour, not a full course. Nuxt needs Node, a build step and a dev server, none of which exist in the sandbox of this site, so the real project code is read-only. Two of its central ideas, file-based routing and shared data fetching, are small enough to rebuild with plain Vue, so you can run those and see how they work.

Why use a framework on top of Vue?

Everything in Server-Side Rendering and Hydration can be built by hand, but the plumbing is long: a server entry and a client entry, per-request app creation, routing that works on both sides, data that is fetched on the server and reused in the browser, code splitting, and deployment. Nuxt packages all of it with sensible defaults:

  • File-based routing. Files in pages/ become routes.
  • Auto imports. Components, composables and Vue APIs are available without import lines.
  • Data fetching that works during server rendering and in the browser.
  • Server routes for writing API endpoints in the same project.
  • Hybrid rendering. SSR, static generation or plain SPA mode, chosen per route.
  • Modules for content, images, UI kits, Pinia and more.

You can scaffold a project with npm create nuxt (read-only here) and start the dev server with npm run dev. Nuxt uses Vue 3, Vite for building and a server engine called Nitro under the hood.

flowchart LR
  R["request"] --> N["Nitro server"]
  N --> Q{"route type"}
  Q -- "/api/..." --> H["server route handler"]
  Q -- page --> V["render Vue pages on the server"]
  V --> P["HTML plus data payload"]
  P --> B["browser hydrates"]
  B --> C["client-side navigation"]

Nitro handles every request: it runs a server route for API URLs and renders Vue for pages. The browser reuses the HTML and the data, then takes over navigation.

Project layout

A fresh Nuxt project looks like this. Names matter: Nuxt finds your code by folder (recent versions place application code inside an app/ folder, older ones at the project root, and the rules below are the same).

TEXT
my-site/
  nuxt.config.ts        settings: modules, route rules, runtime config
  app/
    app.vue             the root component
    pages/              routes: one file per page
    layouts/            page frames (header, footer)
    components/         auto-imported components
    composables/        auto-imported useX functions
    middleware/         route guards
  server/
    api/                API endpoints, e.g. api/products.get.ts
  public/               files served as they are

The root component is tiny. <NuxtPage /> shows the page for the current route, and <NuxtLayout> wraps it in a layout:

VUE
<!-- app/app.vue (read-only) -->
<template>
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

File-based routing

Instead of writing a route table, as in Vue Router Basics, you add files. The rules are few:

File in pages/ Route
index.vue /
about.vue /about
blog/index.vue /blog
blog/[slug].vue /blog/:slug (a dynamic segment)
[[page]].vue an optional parameter
[...slug].vue a catch-all, often used for a 404 page

A folder with a file of the same name (for example users.vue next to users/) makes a nested route: the file is the parent and shows its children where it places <NuxtPage />. Nuxt generates the router from these files, and every page is automatically a separate chunk, so route-level code splitting (see Build and Load Performance) comes for free.

The demo below implements the naming rules above with plain Vue. Edit the list of files and visit different URLs. A specific file always wins over a dynamic one, and the catch-all comes last.

File names become routes

Try /blog/hello-vue, /users/42/settings and /nothing/here. The last one is caught by [...slug].vue, with the rest of the path in slug. Delete that line from the list and the same URL reports "No page matches". Real Nuxt does the matching with Vue Router and is stricter (for example about nested routes), but the naming rules are the ones you saw.

Auto imports

In a Nuxt project you rarely write import lines for the things you use most. Vue APIs (ref, computed, watch), Nuxt composables, your own components in components/ and functions in composables/ are imported for you, at build time. They are still ordinary ES imports in the final code, so tree shaking works, and the editor gets types for all of them.

VUE
<!-- app/pages/products.vue (read-only) -->
<script setup>
const { data: products, pending, error, refresh } = await useFetch("/api/products");
</script>

<template>
  <p v-if="pending">Loading...</p>
  <p v-else-if="error">Could not load products.</p>
  <ProductCard v-for="p in products" :key="p.id" :product="p" />
  <button @click="refresh()">Refresh</button>
</template>

Neither useFetch nor ProductCard is imported. The file also shows the shape of Nuxt data fetching, which is the next topic.

Data fetching

The hard part of SSR is data. If the server fetches products to render HTML, the browser must not fetch them again and render something different. Nuxt solves this with composables that run on the server, put their results into a payload embedded in the page, and let the browser read it back instead of calling the API.

  • useFetch(url) is the shortcut for a URL. It returns refs: data, pending (or status), error and refresh, and it re-fetches when reactive inputs change.
  • useAsyncData(key, fn) is the general form for any async function (a database call, a CMS client).
  • $fetch is a plain request function for user actions such as submitting a form. It does not transfer data between server and browser.

Requests that share the same key are de-duplicated. The demo rebuilds that idea with a key, a shared cache and a request that is made only once, even though two components ask for the same data. It is a teaching stand-in, not Nuxt's code.

A tiny useFetch with a shared key

Two components call useFetch("products", ...), and the counter shows one API call. Press Refresh and it goes to two: refreshing forces a new request, and both components update from the shared result. In real Nuxt, an in-flight request is also shared across the server and browser phases, and key-based caching can be controlled with options such as getCachedData.

Server routes

Files in server/api/ are API endpoints that run on the server. The file name sets the URL and, optionally, the HTTP method:

TypeScript
// server/api/products.get.ts (read-only)
export default defineEventHandler(async (event) => {
  const query = getQuery(event);          // ?limit=3
  const limit = Number(query.limit ?? 10);
  return [
    { id: 1, name: "Keyboard" },
    { id: 2, name: "Mouse" }
  ].slice(0, limit);                       // returned values become JSON
});

This is how a Nuxt app gets a backend for the frontend in the same repository: it can keep secrets (API keys, database passwords) on the server, talk to databases, set cookies, and hide third-party APIs. Secrets belong in runtimeConfig on the server side, never in code that is shipped to the browser. These endpoints are also where the checks from Authentication Patterns must live. Route middleware in middleware/ gives you the front-end guards.

Rendering modes

Nuxt lets you choose how each route is rendered, in nuxt.config.ts:

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  routeRules: {
    "/": { prerender: true },        // built once at build time (SSG)
    "/blog/**": { swr: 3600 },       // served from cache, revalidated hourly
    "/dashboard/**": { ssr: false }, // plain SPA, rendered in the browser
    "/api/**": { cors: true }
  }
});

So one app can mix a pre-rendered home page, cached articles and a client-only dashboard. Setting ssr: false for the whole app gives an SPA, and the nuxt generate command pre-renders every route into static files.

Deployment

nuxt build produces a self-contained output folder. Nitro can target many environments through presets: a plain Node server, static hosting, serverless functions and edge platforms. You choose the preset (often detected automatically on a host) and deploy the output. A static preset needs only a file host or CDN, a Node preset needs a running process, and serverless presets run each request as a short-lived function.

Metadata, layouts and modules

A few more built-ins you will meet quickly: useHead and useSeoMeta set the page title and meta tags (good for SEO, since they are rendered on the server), definePageMeta attaches a layout or middleware to a page, useState creates shared state that survives the server-to-browser handoff, and <NuxtLink> gives client-side navigation with automatic prefetching of linked pages. Modules add features with one line in the config: content from Markdown files, image optimization, a UI library, Pinia state, i18n.

When is Nuxt the right choice?

Pick Nuxt when you want a public, SEO-friendly Vue site or app and prefer conventions to wiring. Pick plain Vue with Vite when you are building a widget, an app behind a login with no SEO needs, or an interface embedded in a server-rendered page of another stack. Both use the same Vue you have learned, so the skills carry over.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file creates the route /blog/:slug in a Nuxt project?

    Square brackets in a file name mark a dynamic segment. The server/api folder defines API endpoints, not pages.
  2. 2. Why does Nuxt put fetched data into a payload inside the HTML?

    The browser reads the data that the server already fetched, so it renders the same content and avoids a second request.
  3. 3. What does routeRules: { '/dashboard/**': { ssr: false } } do?

    ssr: false turns off server rendering for matching routes, so they behave like a client-side app.
  4. 4. Where should an API secret that must not reach the browser live?

    Server routes run only on the server. Anything in components, public files or client bundles can be read by visitors.

Summary

  • Nuxt is a full-stack framework on Vue, Vite and Nitro that adds routing, SSR, data fetching, server routes and deployment presets by convention.
  • Files in pages/ become routes; [param], [[optional]] and [...catchAll] express dynamic parts.
  • Components, composables and Vue APIs are auto-imported at build time.
  • useFetch and useAsyncData fetch on the server, share the result with the browser and de-duplicate by key.
  • server/api files are backend endpoints where secrets and authorization checks belong.
  • routeRules mix SSR, static generation, caching and SPA routes in one app.

Next, in The Vue Ecosystem, you will see the wider set of tools and libraries around Vue and how to choose among them.