Fast and low overhead web framework for Node.js with powerful plugin architecture
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Route registration and handling for all HTTP methods with support for route options, constraints, and dynamic routing.
Fastify provides convenient shortcut methods for all standard HTTP methods.
/**
* Register GET route handler
* @param url - Route URL pattern with optional parameters
* @param options - Route configuration options
* @param handler - Route handler function
* @returns FastifyInstance for method chaining
*/
get(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
get(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register POST route handler
*/
post(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
post(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register PUT route handler
*/
put(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
put(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register DELETE route handler
*/
delete(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
delete(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register PATCH route handler
*/
patch(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
patch(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register HEAD route handler
*/
head(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
head(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register OPTIONS route handler
*/
options(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
options(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register TRACE route handler
*/
trace(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
trace(url: string, handler: RouteHandlerMethod): FastifyInstance;
/**
* Register handler for all HTTP methods
*/
all(url: string, options?: RouteShorthandOptions, handler?: RouteHandlerMethod): FastifyInstance;
all(url: string, handler: RouteHandlerMethod): FastifyInstance;Usage Examples:
// Simple route handlers
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
fastify.post('/users', async (request, reply) => {
const user = await createUser(request.body);
reply.code(201).send(user);
});
// Routes with parameters
fastify.get('/users/:id', async (request, reply) => {
const userId = request.params.id;
const user = await getUserById(userId);
return user;
});
// Routes with options
fastify.post('/users', {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
}
}
}, async (request, reply) => {
return await createUser(request.body);
});Register routes with complete configuration objects.
/**
* Register route with full configuration object
* @param options - Complete route configuration
* @returns FastifyInstance for method chaining
*/
route(options: RouteOptions): FastifyInstance;interface RouteOptions {
method: HTTPMethods | HTTPMethods[];
url: string;
handler: RouteHandlerMethod;
schema?: FastifySchema;
attachValidation?: boolean;
exposeHeadRoute?: boolean;
validatorCompiler?: FastifySchemaCompiler;
serializerCompiler?: FastifySerializerCompiler;
bodyLimit?: number;
logLevel?: LogLevel;
config?: FastifyContextConfig;
constraints?: RouteConstraint;
prefixTrailingSlash?: 'slash' | 'no-slash' | 'both';
errorHandler?: Function;
childLoggerFactory?: Function;
schemaErrorFormatter?: Function;
// Hook handlers
onRequest?: onRequestHookHandler | onRequestHookHandler[];
preParsing?: preParsingHookHandler | preParsingHookHandler[];
preValidation?: preValidationHookHandler | preValidationHookHandler[];
preHandler?: preHandlerHookHandler | preHandlerHookHandler[];
preSerialization?: preSerializationHookHandler | preSerializationHookHandler[];
onSend?: onSendHookHandler | onSendHookHandler[];
onResponse?: onResponseHookHandler | onResponseHookHandler[];
onTimeout?: onTimeoutHookHandler | onTimeoutHookHandler[];
onError?: onErrorHookHandler | onErrorHookHandler[];
onRequestAbort?: onRequestAbortHookHandler | onRequestAbortHookHandler[];
}
interface RouteShorthandOptions {
schema?: FastifySchema;
attachValidation?: boolean;
exposeHeadRoute?: boolean;
validatorCompiler?: FastifySchemaCompiler;
serializerCompiler?: FastifySerializerCompiler;
bodyLimit?: number;
logLevel?: LogLevel;
config?: FastifyContextConfig;
constraints?: RouteConstraint;
prefixTrailingSlash?: 'slash' | 'no-slash' | 'both';
errorHandler?: Function;
childLoggerFactory?: Function;
schemaErrorFormatter?: Function;
// Hook handlers (same as RouteOptions)
onRequest?: onRequestHookHandler | onRequestHookHandler[];
preParsing?: preParsingHookHandler | preParsingHookHandler[];
preValidation?: preValidationHookHandler | preValidationHookHandler[];
preHandler?: preHandlerHookHandler | preHandlerHookHandler[];
preSerialization?: preSerializationHookHandler | preSerializationHookHandler[];
onSend?: onSendHookHandler | onSendHookHandler[];
onResponse?: onResponseHookHandler | onResponseHookHandler[];
onTimeout?: onTimeoutHookHandler | onTimeoutHookHandler[];
onError?: onErrorHookHandler | onErrorHookHandler[];
onRequestAbort?: onRequestAbortHookHandler | onRequestAbortHookHandler[];
}Usage Examples:
// Full route configuration
fastify.route({
method: 'POST',
url: '/users',
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' }
}
}
}
},
config: {
requireAuth: true
},
preHandler: async (request, reply) => {
// Authentication check
if (!request.headers.authorization) {
reply.code(401).send({ error: 'Unauthorized' });
}
},
handler: async (request, reply) => {
const user = await createUser(request.body);
reply.code(201).send(user);
}
});
// Multiple HTTP methods
fastify.route({
method: ['GET', 'POST'],
url: '/health',
handler: async (request, reply) => {
return { status: 'ok' };
}
});The functions that process HTTP requests.
/**
* Route handler function signature
* @param request - Fastify request object
* @param reply - Fastify reply object
* @returns Promise resolving to response data or undefined
*/
type RouteHandlerMethod = (
request: FastifyRequest,
reply: FastifyReply
) => Promise<any> | any;Handler Examples:
// Async handler returning data
const getUserHandler = async (request, reply) => {
const user = await getUserById(request.params.id);
return user; // Automatically serialized and sent
};
// Handler using reply object
const createUserHandler = async (request, reply) => {
const user = await createUser(request.body);
reply.code(201).send(user);
};
// Error handling in handlers
const errorHandler = async (request, reply) => {
try {
const data = await riskyOperation();
return data;
} catch (error) {
reply.code(500).send({ error: 'Internal Server Error' });
}
};Methods for finding and checking existing routes.
/**
* Check if a route exists
* @param options - Route matching criteria
* @returns Boolean indicating if route exists
*/
hasRoute(options: { method: string; url: string; constraints?: object }): boolean;
/**
* Find a registered route
* @param options - Route matching criteria
* @returns Route object or null if not found
*/
findRoute(options: { method: string; url: string; constraints?: object }): object | null;
/**
* Get formatted list of all registered routes
* @param opts - Formatting options
* @returns String representation of routes
*/
printRoutes(opts?: PrintRoutesOptions): string;interface PrintRoutesOptions {
method?: HTTPMethods;
includeMeta?: boolean | (string | symbol)[];
commonPrefix?: boolean;
includeHooks?: boolean;
}Usage Examples:
// Check if route exists
const exists = fastify.hasRoute({
method: 'GET',
url: '/users/:id'
});
// Find specific route
const route = fastify.findRoute({
method: 'POST',
url: '/users'
});
// Print all routes
console.log(fastify.printRoutes());
// Print routes with metadata
console.log(fastify.printRoutes({
includeMeta: true,
includeHooks: true
}));Advanced routing with constraint-based matching.
interface RouteConstraint {
version?: string;
host?: RegExp | string;
[name: string]: unknown;
}
/**
* Add constraint strategy for routing
* @param strategy - Constraint strategy implementation
*/
addConstraintStrategy(strategy: ConstraintStrategy): void;
/**
* Check if constraint strategy exists
* @param strategyName - Name of the constraint strategy
* @returns Boolean indicating if strategy exists
*/
hasConstraintStrategy(strategyName: string): boolean;Usage Examples:
// Version-based routing
fastify.route({
method: 'GET',
url: '/users',
constraints: { version: '1.0.0' },
handler: async () => ({ version: 'v1' })
});
fastify.route({
method: 'GET',
url: '/users',
constraints: { version: '2.0.0' },
handler: async () => ({ version: 'v2' })
});
// Host-based routing
fastify.route({
method: 'GET',
url: '/admin',
constraints: { host: 'admin.example.com' },
handler: async () => ({ admin: true })
});Support for additional HTTP methods beyond the standard ones.
/**
* Add support for additional HTTP methods
* @param method - HTTP method name
* @param options - Method configuration
* @returns FastifyInstance for method chaining
*/
addHttpMethod(method: string, options?: { hasBody?: boolean }): FastifyInstance;Usage Examples:
// Add support for PURGE method
fastify.addHttpMethod('PURGE');
// Now you can use it
fastify.purge('/cache/:key', async (request, reply) => {
await clearCache(request.params.key);
return { purged: true };
});
// Method with body support
fastify.addHttpMethod('COPY', { hasBody: true });Fastify includes built-in support for WebDAV HTTP methods.
interface FastifyInstance {
propfind: RouteShorthandMethod;
proppatch: RouteShorthandMethod;
mkcalendar: RouteShorthandMethod;
mkcol: RouteShorthandMethod;
copy: RouteShorthandMethod;
move: RouteShorthandMethod;
lock: RouteShorthandMethod;
unlock: RouteShorthandMethod;
}Usage Examples:
// WebDAV methods
fastify.propfind('/dav/*', async (request, reply) => {
// Handle PROPFIND request
return { properties: [] };
});
fastify.mkcol('/dav/collection', async (request, reply) => {
// Create collection
reply.code(201).send();
});