Full-stack development with Nuxt 3 server routes for Google Antigravity projects including API endpoints, middleware, and server utilities.
# Nuxt 3 Server API Patterns for Google Antigravity
Build full-stack applications with Nuxt 3 server routes in your Google Antigravity IDE projects. This comprehensive guide covers API endpoints, middleware, server utilities, and authentication patterns optimized for Gemini 3 agentic development.
## Server Route Configuration
Create type-safe API endpoints with Nuxt 3:
```typescript
// server/api/prompts/index.get.ts
import { db } from '~/server/utils/db';
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const page = Number(query.page) || 1;
const limit = Math.min(Number(query.limit) || 20, 100);
const search = query.search as string | undefined;
const category = query.category as string | undefined;
const offset = (page - 1) * limit;
const where: Record<string, unknown> = { isApproved: true };
if (search) {
where.OR = [
{ title: { contains: search, mode: 'insensitive' } },
{ description: { contains: search, mode: 'insensitive' } },
];
}
if (category) {
where.tags = { has: category };
}
const [prompts, total] = await Promise.all([
db.prompt.findMany({
where,
orderBy: { createdAt: 'desc' },
take: limit,
skip: offset,
include: {
author: {
select: { id: true, name: true, image: true },
},
},
}),
db.prompt.count({ where }),
]);
return {
prompts,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit),
},
};
});
```
## Route Parameters and Validation
Handle dynamic routes with validation:
```typescript
// server/api/prompts/[slug].get.ts
import { z } from 'zod';
import { db } from '~/server/utils/db';
const paramsSchema = z.object({
slug: z.string().min(1).max(255),
});
export default defineEventHandler(async (event) => {
// Validate params
const result = paramsSchema.safeParse(event.context.params);
if (!result.success) {
throw createError({
statusCode: 400,
message: 'Invalid slug parameter',
data: result.error.flatten(),
});
}
const { slug } = result.data;
const prompt = await db.prompt.findUnique({
where: { slug },
include: {
author: {
select: { id: true, name: true, image: true },
},
},
});
if (!prompt) {
throw createError({
statusCode: 404,
message: 'Prompt not found',
});
}
// Increment view count asynchronously
db.prompt.update({
where: { id: prompt.id },
data: { viewCount: { increment: 1 } },
}).catch(console.error);
return prompt;
});
// server/api/prompts/[slug].patch.ts
const updateSchema = z.object({
title: z.string().min(5).max(200).optional(),
description: z.string().min(20).max(500).optional(),
content: z.string().min(100).optional(),
tags: z.array(z.string()).min(1).max(5).optional(),
});
export default defineEventHandler(async (event) => {
const session = await requireAuth(event);
const { slug } = event.context.params!;
const body = await readValidatedBody(event, updateSchema.parse);
const prompt = await db.prompt.findUnique({
where: { slug },
select: { id: true, authorId: true },
});
if (!prompt) {
throw createError({ statusCode: 404, message: 'Prompt not found' });
}
if (prompt.authorId !== session.user.id && session.user.role !== 'admin') {
throw createError({ statusCode: 403, message: 'Not authorized' });
}
const updated = await db.prompt.update({
where: { id: prompt.id },
data: { ...body, updatedAt: new Date() },
});
return updated;
});
```
## Server Middleware
Implement request middleware for authentication and logging:
```typescript
// server/middleware/auth.ts
import { verifyToken } from '~/server/utils/jwt';
export default defineEventHandler(async (event) => {
// Skip auth for public routes
const publicPaths = ['/api/prompts', '/api/auth'];
const path = getRequestURL(event).pathname;
if (publicPaths.some((p) => path.startsWith(p) && event.method === 'GET')) {
return;
}
const authHeader = getHeader(event, 'authorization');
if (authHeader?.startsWith('Bearer ')) {
const token = authHeader.slice(7);
try {
const payload = await verifyToken(token);
event.context.user = payload;
} catch {
// Token invalid, continue without user
}
}
});
// server/middleware/logging.ts
export default defineEventHandler(async (event) => {
const start = Date.now();
const url = getRequestURL(event);
// Log request
console.log(`--> ${event.method} ${url.pathname}`);
// Continue to handler
await event.node.res.on('finish', () => {
const duration = Date.now() - start;
const status = event.node.res.statusCode;
console.log(`<-- ${event.method} ${url.pathname} ${status} ${duration}ms`);
});
});
```
## Server Utilities
Create reusable server utilities:
```typescript
// server/utils/auth.ts
import { H3Event } from 'h3';
export async function requireAuth(event: H3Event) {
const user = event.context.user;
if (!user) {
throw createError({
statusCode: 401,
message: 'Authentication required',
});
}
return { user };
}
export async function requireRole(event: H3Event, roles: string[]) {
const { user } = await requireAuth(event);
if (!roles.includes(user.role)) {
throw createError({
statusCode: 403,
message: 'Insufficient permissions',
});
}
return { user };
}
// server/utils/db.ts
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const db = globalForPrisma.prisma ?? new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query'] : [],
});
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = db;
}
// server/utils/cache.ts
import { useStorage } from '#imports';
const cache = useStorage('cache');
export async function cached<T>(
key: string,
fn: () => Promise<T>,
ttl: number = 60
): Promise<T> {
const cached = await cache.getItem<T>(key);
if (cached !== null) {
return cached;
}
const result = await fn();
await cache.setItem(key, result, { ttl });
return result;
}
export async function invalidateCache(pattern: string) {
const keys = await cache.getKeys(pattern);
await Promise.all(keys.map((key) => cache.removeItem(key)));
}
```
## Error Handling
Implement consistent error handling:
```typescript
// server/utils/errors.ts
import { H3Error } from 'h3';
export class AppError extends H3Error {
constructor(
public code: string,
message: string,
statusCode: number = 400,
public details?: Record<string, unknown>
) {
super(message);
this.statusCode = statusCode;
}
}
export const errors = {
notFound: (resource: string) =>
new AppError('NOT_FOUND', `${resource} not found`, 404),
unauthorized: () =>
new AppError('UNAUTHORIZED', 'Authentication required', 401),
forbidden: () =>
new AppError('FORBIDDEN', 'Access denied', 403),
validation: (details: Record<string, string[]>) =>
new AppError('VALIDATION_ERROR', 'Validation failed', 400, { details }),
rateLimit: () =>
new AppError('RATE_LIMITED', 'Too many requests', 429),
};
// server/middleware/error.ts
export default defineEventHandler(async (event) => {
try {
// Continue to route handler
} catch (error) {
if (error instanceof AppError) {
return sendError(event, createError({
statusCode: error.statusCode,
message: error.message,
data: {
code: error.code,
details: error.details,
},
}));
}
// Log unexpected errors
console.error('Unexpected error:', error);
return sendError(event, createError({
statusCode: 500,
message: 'Internal server error',
}));
}
});
```
## Best Practices
1. **Use file-based routing** with HTTP method suffixes
2. **Validate all inputs** with Zod schemas
3. **Implement proper authentication** middleware
4. **Create reusable utilities** for common operations
5. **Handle errors consistently** across all endpoints
6. **Use caching** for expensive operations
7. **Log requests** for debugging and monitoringThis nuxt prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their nuxt implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For nuxt projects, consider mentioning your framework version, coding style, and any specific libraries you're using.