typescriptbeginner
Fastify Server Setup
Create a high-performance Fastify server with schema validation, plugins, and typed routes.
typescriptPress ⌘/Ctrl + Shift + C to copy
import Fastify from 'fastify';
const app = Fastify({ logger: true });
// JSON Schema for validation
const getUserSchema = {
params: {
type: 'object' as const,
properties: { id: { type: 'string' } },
required: ['id'],
},
response: {
200: {
type: 'object' as const,
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
},
},
},
};
// Routes
app.get('/health', async () => ({ status: 'ok', uptime: process.uptime() }));
app.get<{ Params: { id: string } }>(
'/users/:id',
{ schema: getUserSchema },
async (request, reply) => {
const { id } = request.params;
return { id, name: 'Alice', email: 'alice@example.com' };
},
);
app.post<{ Body: { name: string; email: string } }>(
'/users',
{
schema: {
body: {
type: 'object' as const,
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
},
required: ['name', 'email'],
},
},
},
async (request, reply) => {
reply.code(201);
return { id: crypto.randomUUID(), ...request.body };
},
);
app.listen({ port: 3000 }, (err) => {
if (err) { app.log.error(err); process.exit(1); }
});Sponsored
Railway
Use Cases
- High-performance REST APIs
- Type-safe API routes
- Schema-validated endpoints
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
#nodejs#http
typescriptadvanced
GraphQL Server with Type Definitions
Build a GraphQL API server with type definitions, resolvers, and query/mutation support.
Best for: GraphQL API development
#nodejs#graphql
typescriptintermediate
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
#nodejs#validation
typescriptintermediate
Node.js Token Bucket Rate Limiter
Implement an in-memory token bucket rate limiter for controlling API request throughput.
Best for: Protecting APIs from abuse and DDoS
#nodejs#rate-limiting