Nuxt 3 is revolutionizing the way developers approach full-stack Vue applications by offering a comprehensive free API that simplifies the development process. Its standout features include auto-imports, file-based routing, and a powerful server engine.
Auto-Imports: Simplified Code Management
Nuxt 3 eliminates the need for boilerplate code through its auto-import feature. This means developers can focus on logic and functionality without worrying about importing components manually. Here's a quick example:
<script setup>
const count = ref(0);
const doubled = computed(() => count.value * 2);
const { data: products } = await useFetch("/api/products");
const route = useRoute();
const router = useRouter();
const config = useRuntimeConfig();
</script>
Universal Data Fetching with useFetch
The useFetch hook provides a streamlined approach to data fetching that is both SSR-safe and capable of caching. It allows developers to retrieve data while ensuring efficient performance.
<script setup>
const { data, pending, error, refresh } = await useFetch("/api/products", {
query: { category: "electronics", limit: 20 },
transform: (data) => data.map(p => ({ ...p, priceFormatted: `$${p.price}` })),
default: () => [],
watch: [category],
});
const { data: analytics } = useLazyFetch("/api/analytics");
</script>
Nitro-Powered Server Routes
Nuxt 3's server routes, powered by Nitro, facilitate efficient data handling and API management.
Example of Server Route for GET Request
// server/api/products.get.ts
export default defineEventHandler(async (event) => {
const { category, limit } = getQuery(event);
return await db.select().from(products).where(eq(products.category, category)).limit(+limit);
});
Example of Server Route for POST Request
// server/api/products.post.ts
export default defineEventHandler(async (event) => {
const body = await readBody(event);
return await db.insert(products).values(body).returning();
});
Composables for Shared State Management
Nuxt 3 promotes the use of composables for managing shared states, making it easier to maintain and reuse logic across components.
// composables/useProducts.ts
export function useProducts() {
const products = useState<Product[]>("products", () => []);
const loading = ref(false);
async function fetchProducts(category: string) {
loading.value = true;
const { data } = await useFetch(`/api/products?category=${category}`);
products.value = data.value ?? [];
loading.value = false;
}
return { products: readonly(products), loading, fetchProducts };
}
Middleware for Route Protection
Nuxt 3's middleware capabilities ensure that route protection and user authentication are seamlessly integrated into applications.
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
const user = useUser();
if (!user.value && to.path !== "/login") {
return navigateTo("/login");
}
});
// middleware/admin.ts
export default defineNuxtRouteMiddleware(() => {
const user = useUser();
if (user.value?.role !== "admin") {
return abortNavigation({ statusCode: 403 });
}
});
Enhancing SEO with useHead and useSeoMeta
Optimizing your app for search engines is made simple with Nuxt 3's useHead and useSeoMeta features.
<script setup>
useSeoMeta({
title: () => product.value?.title,
description: () => product.value?.description,
ogImage: () => product.value?.image,
twitterCard: "summary_large_image",
});
</script>
Nuxt 3's robust features and free API make it an excellent choice for developers seeking to create efficient, scalable Vue applications.