Nuxt 3, a popular framework for building Vue applications, brings an impressive feature to the table: a complimentary API platform powered by its Nitro engine. This toolset enables developers to manage server-side operations seamlessly, eliminating the need for a separate backend.
Server API Routes
With Nuxt 3, creating API routes is straightforward. For instance, to fetch user data, a simple handler can be defined:
// server/api/users.get.ts
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const users = await db.user.findMany({
take: Number(query.limit) || 10
});
return users;
});
Similarly, to add new users, you can set up a POST route:
// server/api/users.post.ts
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const user = await db.user.create({ data: body });
return user;
});
Dynamic Routes
Dynamic paths are handled efficiently in Nuxt 3. Consider retrieving user details based on an ID:
// server/api/users/[id].get.ts
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
const user = await db.user.findUnique({ where: { id } });
if (!user) throw createError({ statusCode: 404, message: 'Not found' });
return user;
});
Server Middleware
Nuxt 3 supports middleware to manage authentication and other processes:
// server/middleware/auth.ts
export default defineEventHandler(async (event) => {
const token = getHeader(event, 'authorization');
if (event.path.startsWith('/api/admin') && !token) {
throw createError({ statusCode: 401, message: 'Unauthorized' });
}
if (token) {
event.context.user = await verifyToken(token.replace('Bearer ', ''));
}
});
Cached API Routes
Caching can be implemented to enhance performance. Here's a caching example:
// server/api/stats.get.ts
export default defineCachedEventHandler(async () => {
const stats = await computeExpensiveStats();
return stats;
}, {
maxAge: 60 * 10, // Cache for 10 minutes
swr: true // Stale-while-revalidate
});
Server Utilities
Nuxt 3 simplifies database operations with utilities like Prisma:
// server/utils/db.ts
import { PrismaClient } from '@prisma/client';
export const db = new PrismaClient();
Real-World Impact
An agency transitioned from maintaining separate Vue SPA and Express backends to using Nuxt 3. This shift resulted in significant time savings, reducing project setup from two days to just two hours. With server routes and auto-imports eliminating boilerplate, deployment became as simple as executing npx nuxi deploy.
Nuxt 3's Nitro engine is the powerful backend framework seamlessly integrated into your frontend, offering a comprehensive solution for modern web development.