High-performance APIs with Fastify including schema validation, hooks, and plugins
# Fastify API Patterns for Google Antigravity
Build high-performance APIs with Fastify using Google Antigravity's Gemini 3 engine. This guide covers schema validation, hooks, plugins, and error handling patterns.
## Fastify Server Setup
```typescript
// src/app.ts
import Fastify, { FastifyInstance } from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { usersRoutes } from './routes/users';
import { productsRoutes } from './routes/products';
import { authRoutes } from './routes/auth';
import { errorHandler } from './plugins/error-handler';
import { authenticate } from './plugins/authenticate';
export async function createApp(): Promise<FastifyInstance> {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV === 'development'
? { target: 'pino-pretty' }
: undefined,
},
trustProxy: true,
}).withTypeProvider<TypeBoxTypeProvider>();
// Register plugins
await app.register(cors, {
origin: process.env.ALLOWED_ORIGINS?.split(',') || true,
credentials: true,
});
await app.register(helmet);
await app.register(rateLimit, {
max: 100,
timeWindow: '1 minute',
});
// Custom plugins
await app.register(errorHandler);
await app.register(authenticate);
// Health check
app.get('/health', async () => ({
status: 'healthy',
timestamp: new Date().toISOString(),
}));
// Register routes
await app.register(authRoutes, { prefix: '/api/v1/auth' });
await app.register(usersRoutes, { prefix: '/api/v1/users' });
await app.register(productsRoutes, { prefix: '/api/v1/products' });
return app;
}
// src/server.ts
import { createApp } from './app';
async function start() {
const app = await createApp();
const port = parseInt(process.env.PORT || '3000');
try {
await app.listen({ port, host: '0.0.0.0' });
} catch (err) {
app.log.error(err);
process.exit(1);
}
}
start();
```
## Route Definitions with TypeBox
```typescript
// src/routes/users.ts
import { FastifyPluginAsync } from 'fastify';
import { Type, Static } from '@sinclair/typebox';
// Schema definitions
const UserSchema = Type.Object({
id: Type.String({ format: 'uuid' }),
email: Type.String({ format: 'email' }),
name: Type.String({ minLength: 1, maxLength: 100 }),
role: Type.Union([
Type.Literal('admin'),
Type.Literal('user'),
]),
createdAt: Type.String({ format: 'date-time' }),
});
const CreateUserSchema = Type.Object({
email: Type.String({ format: 'email' }),
name: Type.String({ minLength: 1, maxLength: 100 }),
password: Type.String({ minLength: 8 }),
role: Type.Optional(Type.Union([
Type.Literal('admin'),
Type.Literal('user'),
])),
});
const UpdateUserSchema = Type.Partial(
Type.Omit(CreateUserSchema, ['password'])
);
const UserParamsSchema = Type.Object({
id: Type.String({ format: 'uuid' }),
});
const ListQuerySchema = Type.Object({
page: Type.Optional(Type.Number({ minimum: 1, default: 1 })),
limit: Type.Optional(Type.Number({ minimum: 1, maximum: 100, default: 20 })),
search: Type.Optional(Type.String()),
});
type User = Static<typeof UserSchema>;
type CreateUserInput = Static<typeof CreateUserSchema>;
type UpdateUserInput = Static<typeof UpdateUserSchema>;
export const usersRoutes: FastifyPluginAsync = async (app) => {
// List users
app.get<{
Querystring: Static<typeof ListQuerySchema>;
}>('/', {
schema: {
querystring: ListQuerySchema,
response: {
200: Type.Object({
data: Type.Array(UserSchema),
pagination: Type.Object({
page: Type.Number(),
limit: Type.Number(),
total: Type.Number(),
pages: Type.Number(),
}),
}),
},
},
preHandler: [app.authenticate, app.authorize(['admin'])],
}, async (request, reply) => {
const { page = 1, limit = 20, search } = request.query;
const result = await app.userService.findAll({ page, limit, search });
return {
data: result.users,
pagination: {
page: result.page,
limit: result.limit,
total: result.total,
pages: result.pages,
},
};
});
// Get user by ID
app.get<{
Params: Static<typeof UserParamsSchema>;
}>('/:id', {
schema: {
params: UserParamsSchema,
response: {
200: Type.Object({ data: UserSchema }),
404: Type.Object({ error: Type.String() }),
},
},
preHandler: [app.authenticate],
}, async (request, reply) => {
const user = await app.userService.findById(request.params.id);
if (!user) {
return reply.status(404).send({ error: 'User not found' });
}
return { data: user };
});
// Create user
app.post<{
Body: CreateUserInput;
}>('/', {
schema: {
body: CreateUserSchema,
response: {
201: Type.Object({ data: UserSchema }),
},
},
preHandler: [app.authenticate, app.authorize(['admin'])],
}, async (request, reply) => {
const user = await app.userService.create(request.body);
return reply.status(201).send({ data: user });
});
// Update user
app.put<{
Params: Static<typeof UserParamsSchema>;
Body: UpdateUserInput;
}>('/:id', {
schema: {
params: UserParamsSchema,
body: UpdateUserSchema,
response: {
200: Type.Object({ data: UserSchema }),
},
},
preHandler: [app.authenticate],
}, async (request, reply) => {
const { id } = request.params;
// Check authorization
if (request.user.id !== id && request.user.role !== 'admin') {
return reply.status(403).send({ error: 'Not authorized' });
}
const user = await app.userService.update(id, request.body);
return { data: user };
});
// Delete user
app.delete<{
Params: Static<typeof UserParamsSchema>;
}>('/:id', {
schema: {
params: UserParamsSchema,
response: {
204: Type.Null(),
},
},
preHandler: [app.authenticate, app.authorize(['admin'])],
}, async (request, reply) => {
await app.userService.delete(request.params.id);
return reply.status(204).send();
});
};
```
## Custom Plugins
```typescript
// src/plugins/authenticate.ts
import { FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';
import fp from 'fastify-plugin';
import jwt from 'jsonwebtoken';
interface JwtPayload {
userId: string;
email: string;
role: string;
}
declare module 'fastify' {
interface FastifyInstance {
authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
authorize: (roles: string[]) => (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
interface FastifyRequest {
user: JwtPayload;
}
}
const authenticatePlugin: FastifyPluginAsync = async (app) => {
app.decorate('authenticate', async function (
request: FastifyRequest,
reply: FastifyReply
) {
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return reply.status(401).send({ error: 'Missing authorization header' });
}
const token = authHeader.substring(7);
try {
const payload = jwt.verify(
token,
process.env.JWT_SECRET!
) as JwtPayload;
request.user = payload;
} catch (error) {
return reply.status(401).send({ error: 'Invalid or expired token' });
}
});
app.decorate('authorize', function (roles: string[]) {
return async function (request: FastifyRequest, reply: FastifyReply) {
if (!request.user) {
return reply.status(401).send({ error: 'Not authenticated' });
}
if (!roles.includes(request.user.role)) {
return reply.status(403).send({ error: 'Not authorized' });
}
};
});
};
export const authenticate = fp(authenticatePlugin, {
name: 'authenticate',
});
// src/plugins/error-handler.ts
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
const errorHandlerPlugin: FastifyPluginAsync = async (app) => {
app.setErrorHandler((error, request, reply) => {
request.log.error(error);
// Validation errors
if (error.validation) {
return reply.status(400).send({
error: 'Validation failed',
details: error.validation,
});
}
// Custom app errors
if (error.statusCode) {
return reply.status(error.statusCode).send({
error: error.message,
});
}
// Generic errors
const message = process.env.NODE_ENV === 'production'
? 'Internal server error'
: error.message;
return reply.status(500).send({ error: message });
});
app.setNotFoundHandler((request, reply) => {
reply.status(404).send({
error: 'Not Found',
message: `Cannot ${request.method} ${request.url}`,
});
});
};
export const errorHandler = fp(errorHandlerPlugin, {
name: 'error-handler',
});
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Fastify patterns: Use TypeBox for schema validation and TypeScript inference. Implement plugins for reusable functionality. Leverage hooks for cross-cutting concerns. Use the logger for structured logging. Enable schema serialization for faster responses.This Fastify 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 fastify 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 Fastify projects, consider mentioning your framework version, coding style, and any specific libraries you're using.