Why Choose Nuxt 3?
Nuxt 3 represents a significant leap forward in the realm of full-stack Vue frameworks. It introduces several cutting-edge features that streamline the development process and optimize deployment. Here’s why it's a compelling choice for developers:
- Auto-Imports: Automatically import components, composables, and utilities, eliminating the need for manual imports.
- Hybrid Rendering: Enjoy the flexibility of Server-Side Rendering (SSR), Static Site Generation (SSG), Incremental Static Regeneration (ISR), and Single Page Application (SPA) configurations per route.
- Nitro Server: Deploy your applications seamlessly across over 15 platforms including Vercel, Cloudflare, and Deno.
- File-Based Routing: Simplify navigation with intuitive, file-based routing, where a file like
pages/about.vuecorresponds to the/aboutroute.
Quick Start Guide
Getting started with Nuxt 3 is straightforward. Follow these steps to initialize your project:
npx nuxi@latest init myapp
cd myapp
npm install
npm run dev
Building Pages
Creating pages in Nuxt 3 is a breeze. Below are examples of how to set up a simple index page and a dynamic user page:
<!-- pages/index.vue -->
<template>
<div>
<h1>Welcome</h1>
<p>Count: {{ count }}</p>
<button @click="count++">Increment</button>
</div>
</template>
<script setup>
const count = ref(0); // ref is auto-imported!
</script>
<!-- pages/users/[id].vue -->
<template>
<div>
<h1>{{ user.name }}</h1>
<p>{{ user.email }}</p>
</div>
</template>
<script setup>
const route = useRoute();
const { data: user } = await useFetch(`/api/users/${route.params.id}`);
</script>
Server-Side Capabilities with Nitro
Nuxt 3 leverages the power of the Nitro server to handle API requests efficiently. Here are some examples of server routes:
// server/api/users/index.get.ts
export default defineEventHandler(async () => {
return await db.select().from(users);
});
// server/api/users/index.post.ts
export default defineEventHandler(async (event) => {
const body = await readBody(event);
return await db.insert(users).values(body).returning();
});
// server/api/users/[id].get.ts
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
return await db.select().from(users).where(eq(users.id, id));
});
Leveraging Composables
Nuxt 3’s composables enhance code reusability. An example is the authentication composable:
// composables/useAuth.ts
export const useAuth = () => {
const user = useState('user', () => null);
const isLoggedIn = computed(() => !!user.value);
const login = async (email, password) => {
const data = await $fetch('/api/auth/login', {
method: 'POST',
body: { email, password },
});
user.value = data.user;
};
const logout = async () => {
await $fetch('/api/auth/logout', { method: 'POST' });
user.value = null;
};
return { user, isLoggedIn, login, logout };
};
Middleware for Route Protection
Implement middleware to protect routes and ensure users are authenticated:
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
const { isLoggedIn } = useAuth();
if (!isLoggedIn.value && to.path !== '/login') {
return navigateTo('/login');
}
});
Embracing Hybrid Rendering
Nuxt 3 supports hybrid rendering, allowing developers to choose the optimal rendering strategy for each route:
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true }, // Static at build
'/blog/**': { isr: 3600 }, // Revalidate hourly
'/dashboard/**': { ssr: false }, // SPA only
'/api/**': { cors: true }, // CORS headers
},
});
Nuxt 3 is a powerful framework offering a comprehensive set of tools to build fast, efficient, and scalable web applications. Whether you're deploying to Vercel or Cloudflare, or using file-based routing, Nuxt 3 has it all covered.