Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Nuxt 3 Server API Patterns

Nuxt 3 Server API Patterns

Full-stack development with Nuxt 3 server routes for Google Antigravity projects including API endpoints, middleware, and server utilities.

nuxtvueserverapifullstack
by Antigravity Team
⭐0Stars
.antigravity
# 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 monitoring

When to Use This Prompt

This nuxt prompt is ideal for developers working on:

  • nuxt applications requiring modern best practices and optimal performance
  • Projects that need production-ready nuxt code with proper error handling
  • Teams looking to standardize their nuxt development workflow
  • Developers wanting to learn industry-standard nuxt patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the nuxt code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this nuxt prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...