Build and maintain Express.js API servers with TypeScript, AI SDK integration, and comprehensive validation. Includes hot reload development, structured routing, and OpenAI-powered endpoints.
Expert guidance for building production-ready Express.js API servers with TypeScript, AI SDK integration, and comprehensive input validation using Zod.
This skill provides comprehensive instructions for working with Express.js applications that integrate OpenAI's AI SDK, implement robust validation, and follow TypeScript best practices. Based on the `p0ntan/ai-express` architecture.
```
src/
├── app.ts # Express server entry point
├── routes/
│ └── v1/ # Versioned API routes
│ ├── image/ # Image processing endpoints
│ └── seo/ # SEO enhancement endpoints
├── models/ # Zod validation schemas
│ ├── image/
│ └── seo/
├── validation/ # Validation middleware
└── middleware/ # Custom middleware (error handling, etc.)
```
**Express Server (`app.ts`)**:
**TypeScript Configuration**:
**Available Commands**:
**Code Style (ESLint)**:
Create validation schemas in `src/models/` organized by domain:
```typescript
// src/models/image/AltFromUrlSchema.ts
import { z } from 'zod';
export const AltFromUrlSchema = z.object({
imageUrl: z.string().url(),
language: z.string().optional(),
customInstructions: z.string().optional()
});
export type AltFromUrlRequest = z.infer<typeof AltFromUrlSchema>;
```
Use the `validate()` middleware for route-level validation:
```typescript
import { validate } from '../../validation';
import { AltFromUrlSchema } from '../../models';
// Body validation
router.post('/alt-from-url',
validate({ body: AltFromUrlSchema }),
async (req, res) => {
// req.body is validated and typed
const { imageUrl, language } = req.body;
}
);
// Parameter validation
router.get('/user/:userId',
validate({ params: UserParamsSchema }),
async (req, res) => {
const { userId } = (req as any).validatedParams || req.params;
}
);
// Query validation
router.get('/search',
validate({ query: SearchQuerySchema }),
async (req, res) => {
const { q, limit } = (req as any).validatedQuery || req.query;
}
);
// File upload validation
router.post('/upload',
upload.single('image'),
validate({
file: {
fieldName: 'image',
maxSize: 10 * 1024 * 1024, // 10MB
allowedMimeTypes: ['image/jpeg', 'image/png']
}
}),
handler
);
```
**Validation Features**:
**Environment Configuration**:
```env
OPENAI_API_KEY=sk-...
PORT=3000
```
**AI SDK Usage Pattern**:
```typescript
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
const result = await generateText({
model: openai('gpt-4-turbo'),
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userInput }
]
});
```
**Endpoint Structure** (`/v1/image/alt-from-url`):
1. Validate request body (image URL, language, custom instructions)
2. Construct system prompt with instructions
3. Call AI SDK with image URL in user message
4. Return generated alt text
**Endpoint Structure** (`/v1/image/alt-from-image`):
1. Accept multipart/form-data with image file (Multer)
2. Validate file (size, MIME type)
3. Convert image buffer to base64
4. Send to AI SDK with vision model
5. Return alt text response
**Endpoint Structure** (`/v1/seo/improve-text`):
1. Validate input text and optional parameters
2. Build prompt preserving language and meaning
3. Generate improved version via AI SDK
4. Return enhanced text
```typescript
// Error handler with @ts-expect-error for Express typing
app.use((err, req, res, next) => {
// @ts-expect-error - Express error handler signature
console.error(err.stack);
res.status(500).json({ error: 'Internal server error' });
});
```
**Error Types to Handle**:
```typescript
import multer from 'multer';
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024 } // 10MB
});
// Use in routes
router.post('/alt-from-image',
upload.single('image'),
validate({
file: {
fieldName: 'image',
maxSize: 10 * 1024 * 1024,
allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp']
}
}),
handler
);
```
**Image Processing**:
1. Create Zod schema in `src/models/<domain>/`
2. Define route handler in `src/routes/v1/<domain>/`
3. Add validation middleware to route
4. Implement business logic with AI SDK if needed
5. Add error handling
6. Test with TypeScript type checking
1. Create new Zod schema or extend existing
2. Export TypeScript type with `z.infer<>`
3. Apply to route with `validate()` middleware
4. Access validated data from `req.body`, `req.params`, or `req.query`
1. Define system prompt and input structure
2. Create validation schema for inputs
3. Call `generateText()` or `streamText()` from AI SDK
4. Handle errors (rate limits, API failures)
5. Return structured response
**Core**:
**AI**:
**Validation**:
**Utilities**:
**Dev Tools**:
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/express-typescript-ai-sdk-api-server/raw