Fastify: The Fast and Low Overhead Node.js Web Framework
Fastify is a highly efficient web framework for Node.js, designed to deliver maximum performance by minimizing overhead. Whether you are building an API gateway, a microservice, or a full-fledged server-side application, Fastify offers a plethora of features to streamline development while ensuring scalability and reliability.
Getting Started with Fastify
To begin, you need to install Fastify using npm or yarn:
npm install fastify --save
or
yarn add fastify
Basic Fastify Server
Here’s a basic Fastify server setup:
const fastify = require('fastify')({ logger: true });
fastify.get('/', async (request, reply) => {
return { message: 'Hello Fastify!' };
});
const start = async () => {
try {
await fastify.listen(3000);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
Route Parameters and Queries
Fastify allows you to handle route parameters and query strings with ease:
fastify.get('/user/:id', async (request, reply) => {
const { id } = request.params;
const { name } = request.query;
return { id, name };
});
Handling POST Requests
Handling POST requests with Fastify is straightforward:
fastify.post('/user', async (request, reply) => {
const { username, email } = request.body;
return { username, email };
});
Schema Validation
Fastify embraces JSON Schema for payload validation:
const userSchema = {
type: 'object',
required: ['username', 'email'],
properties: {
username: { type: 'string' },
email: { type: 'string' }
}
};
fastify.post('/signup', { schema: { body: userSchema } }, async (request, reply) => {
const { username, email } = request.body;
return { status: 'success', username, email };
});
Request Lifecycle Hooks
Fastify provides several hooks to handle different stages of the request lifecycle:
fastify.addHook('preHandler', async (request, reply) => {
request.log.info('A request is being processed');
});
fastify.addHook('onSend', async (request, reply, payload) => {
reply.header('Custom-Header', 'FastifyDemo');
return payload;
});
Plugins in Fastify
Plugins are a core feature of Fastify, enabling code reusability and separation of concerns:
fastify.register(require('fastify-auth'));
fastify.addHook('preHandler', fastify.auth([
async (request, reply) => {
const apiKey = request.headers['api-key'];
if (!apiKey || apiKey !== 'secret') {
reply.code(401).send({ error: 'Unauthorized' });
}
}
]));
Example Application
Here’s a more comprehensive example combining several Fastify features:
const fastify = require('fastify')({ logger: true });
fastify.register(require('fastify-auth'));
const userSchema = {
type: 'object',
required: ['username', 'email'],
properties: {
username: { type: 'string' },
email: { type: 'string' }
}
};
fastify.addHook('preHandler', fastify.auth([
async (request, reply) => {
const apiKey = request.headers['api-key'];
if (!apiKey || apiKey !== 'valid-key') {
reply.code(401).send({ error: 'Unauthorized' });
}
}
]));
fastify.post('/signup', { schema: { body: userSchema } }, async (request, reply) => {
const { username, email } = request.body;
return { status: 'success', username, email };
});
fastify.get('/user/:id', async (request, reply) => {
const { id } = request.params;
return { id, username: 'John Doe', email: 'john.doe@example.com' };
});
const start = async () => {
try {
await fastify.listen(3000);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
With these features, Fastify becomes an indispensable tool for building high-performance Node.js applications.
Feel free to explore more about Fastify here.
Hash: cbe57ef09af99dedd2a3763e104c9b96dbefe893eb9cf216786263679492a5aa