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 FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 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
Next.js TypeScript Best Practices

Next.js TypeScript Best Practices

Build production-ready Next.js applications with TypeScript, focusing on App Router, Server Components, and modern patterns.

Next.jsTypeScriptReactFrontend
by Community
⭐0Stars
👁️44Views
📋9Copies
.antigravity
# Next.js TypeScript Best Practices

Master Next.js development with TypeScript using Google Antigravity IDE. This comprehensive guide covers App Router patterns, server components, and type-safe data fetching.

## Why Next.js TypeScript?

Next.js with TypeScript provides end-to-end type safety for full-stack applications. Google Antigravity IDE's Gemini 3 engine ensures optimal patterns and configurations.

## App Router Types

```typescript
// app/users/[id]/page.tsx
import { Metadata } from "next";
import { notFound } from "next/navigation";
import { cache } from "react";

interface PageProps {
  params: { id: string };
  searchParams: { [key: string]: string | string[] | undefined };
}

// Cache the data fetching function
const getUser = cache(async (id: string) => {
  const response = await fetch(`${process.env.API_URL}/users/${id}`, {
    next: { revalidate: 3600 },
  });
  
  if (!response.ok) return null;
  return response.json() as Promise<User>;
});

// Generate metadata
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const user = await getUser(params.id);
  
  if (!user) {
    return { title: "User Not Found" };
  }
  
  return {
    title: user.name,
    description: `Profile page for ${user.name}`,
    openGraph: {
      title: user.name,
      images: [user.avatar],
    },
  };
}

// Static params for SSG
export async function generateStaticParams(): Promise<{ id: string }[]> {
  const users = await fetch(`${process.env.API_URL}/users`).then((r) => r.json());
  return users.map((user: User) => ({ id: user.id }));
}

// Page component
export default async function UserPage({ params, searchParams }: PageProps) {
  const user = await getUser(params.id);
  
  if (!user) {
    notFound();
  }
  
  const tab = searchParams.tab as string | undefined;
  
  return (
    <main>
      <UserProfile user={user} activeTab={tab} />
    </main>
  );
}
```

## Server Actions

```typescript
// app/actions/user.ts
"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

const updateUserSchema = z.object({
  name: z.string().min(2).max(100),
  email: z.string().email(),
  bio: z.string().max(500).optional(),
});

type ActionResult<T> = 
  | { success: true; data: T }
  | { success: false; error: string };

export async function updateUser(
  formData: FormData
): Promise<ActionResult<User>> {
  const session = await auth();
  
  if (!session?.user) {
    return { success: false, error: "Unauthorized" };
  }
  
  const rawData = {
    name: formData.get("name"),
    email: formData.get("email"),
    bio: formData.get("bio"),
  };
  
  const parsed = updateUserSchema.safeParse(rawData);
  
  if (!parsed.success) {
    return {
      success: false,
      error: parsed.error.errors[0].message,
    };
  }
  
  try {
    const user = await db.user.update({
      where: { id: session.user.id },
      data: parsed.data,
    });
    
    revalidatePath(`/users/${user.id}`);
    return { success: true, data: user };
  } catch (error) {
    return { success: false, error: "Failed to update user" };
  }
}

export async function deleteUser(): Promise<void> {
  const session = await auth();
  
  if (!session?.user) {
    throw new Error("Unauthorized");
  }
  
  await db.user.delete({ where: { id: session.user.id } });
  redirect("/");
}
```

## API Route Types

```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2),
  password: z.string().min(8),
});

type CreateUserInput = z.infer<typeof createUserSchema>;

interface ApiResponse<T> {
  data?: T;
  error?: string;
}

export async function POST(
  request: NextRequest
): Promise<NextResponse<ApiResponse<User>>> {
  try {
    const body = await request.json();
    const data = createUserSchema.parse(body);
    
    const user = await createUser(data);
    
    return NextResponse.json({ data: user }, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: error.errors[0].message },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

// Dynamic route handler
// app/api/users/[id]/route.ts
interface RouteContext {
  params: { id: string };
}

export async function GET(
  request: NextRequest,
  { params }: RouteContext
): Promise<NextResponse<ApiResponse<User>>> {
  const user = await getUser(params.id);
  
  if (!user) {
    return NextResponse.json({ error: "User not found" }, { status: 404 });
  }
  
  return NextResponse.json({ data: user });
}
```

## Middleware Types

```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

interface MiddlewareConfig {
  matcher: string[];
}

export function middleware(request: NextRequest): NextResponse {
  const token = request.cookies.get("auth-token")?.value;
  const pathname = request.nextUrl.pathname;
  
  // Protected routes
  const protectedPaths = ["/dashboard", "/settings", "/profile"];
  const isProtected = protectedPaths.some((path) => pathname.startsWith(path));
  
  if (isProtected && !token) {
    const url = new URL("/login", request.url);
    url.searchParams.set("redirect", pathname);
    return NextResponse.redirect(url);
  }
  
  // Add headers
  const response = NextResponse.next();
  response.headers.set("x-pathname", pathname);
  
  return response;
}

export const config: MiddlewareConfig = {
  matcher: ["/((?!api|_next/static|favicon.ico).*)"],
};
```

## Best Practices

- Use generateStaticParams for SSG
- Apply proper server action types
- Implement type-safe API routes
- Use Zod for runtime validation
- Leverage Next.js caching utilities
- Configure strict TypeScript mode

Google Antigravity IDE provides Next.js TypeScript templates and ensures type safety across your full-stack application.

When to Use This Prompt

This Next.js prompt is ideal for developers working on:

  • Next.js applications requiring modern best practices and optimal performance
  • Projects that need production-ready Next.js code with proper error handling
  • Teams looking to standardize their next.js development workflow
  • Developers wanting to learn industry-standard Next.js 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 next.js 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 Next.js 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 Next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...