Build production-ready Next.js applications with TypeScript, focusing on App Router, Server Components, and modern patterns.
# 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.This Next.js 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 next.js 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 Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.