panhandlefamily.com

Mastering Server-Side Development with Fastify: Versioning & Logs

Written on

Chapter 1: Introduction to Fastify

Fastify is a lightweight Node.js framework designed for creating backend web applications. In this section, we will explore how to build backend apps using Fastify effectively.

Section 1.1: Setting API Versioning

To manage API versions, we can utilize the version property. Here’s how you can implement it:

const fastify = require('fastify')();

fastify.route({

method: 'GET',

url: '/',

version: '1.2.0',

handler(request, reply) {

reply.send({ hello: 'world' });

}

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

In this code, the / route checks the Accept-Version header from incoming requests. If it corresponds with 1.x, 1.2.0, or 1.2.x, the response will be:

{ "hello": "world" }

Otherwise, it returns a 404 error.

Section 1.2: Enabling Logging

By default, Fastify has logging turned off. To activate it, set the logger property to true. Here’s an example:

const fastify = require('fastify')({ logger: true });

fastify.get('/', (request, reply) => {

request.log.info('Some info');

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

When logging is enabled, you can view information in the console like this:

{"level":30,"time":1604268389762,"pid":737,"hostname":"9cc07d2eed9d","reqId":2,"msg":"Some info"}

Section 1.3: Customizing Logger Options

You can also provide additional options for the logger. For example:

const fastify = require('fastify')({

logger: {

level: 'info',

file: './log.txt'

}

});

fastify.get('/', (request, reply) => {

request.log.info('Some info');

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

This configuration logs output to a file named log.txt.

Chapter 2: Custom Stream and Serializer

To pass a custom stream to the Pino logger, you can create a stream using:

const split = require('split2');

const stream = split(JSON.parse);

const fastify = require('fastify')({

logger: {

level: 'info',

stream: stream

}

});

fastify.get('/', (request, reply) => {

request.log.info('Some info');

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

Additionally, you can adjust what gets logged using the serializers property. For example:

const fastify = require('fastify')({

logger: {

serializers: {

req(request) {

return { url: request.url };

}

}

}

});

fastify.get('/', (request, reply) => {

request.log.info('Some info');

reply.send({ hello: 'world' });

});

const start = async () => {

try {

await fastify.listen(3000, '0.0.0.0');

} catch (err) {

fastify.log.error(err);

process.exit(1);

}

};

start();

This will allow you to log specific data from the request, enhancing the logging process.

In the video "Design an API with Code using Node.js and Swagger," you can learn how to effectively create APIs using Fastify, including versioning and documentation techniques.

The video "Build an Authentication API with Node.js, TypeScript, Typegoose, ExpressJS & Zod" provides insights on creating robust authentication mechanisms, which complement the Fastify framework perfectly.

Conclusion

In summary, Fastify allows you to implement API versioning and logging easily, making it a powerful tool for backend development.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Creating Work That You Might Not Be Proud Of: A Journey to Overcome Perfectionism

Explore the benefits of embracing imperfection and how to overcome overthinking in your creative pursuits.

# Expanding Our Minds: Breaking Free from Repetitive Thinking

Discover strategies to diversify your thought processes and break free from repetitive thinking patterns for personal growth.

Navigating the Complexities of Modern Dating: A Comprehensive Guide

Explore the eight essential phases of dating and how to navigate them successfully.

Exploring the Science vs. Religion Debate in 'The War of the Worlds'

Analyzing H.G. Wells' 'The War of the Worlds' reveals insights on the intersection of science and religion, highlighting key character lessons.

Reconnecting with Your True Self: Unpacking Authenticity and Emotion

Explore the journey of reconnecting with your authentic self by understanding emotions, trauma, and the need for connection.

How to Effectively Handle Mockery: A Practical Approach

Discover effective strategies to cope with mockery and emerge stronger while maintaining your self-worth.

Maximize Your Success Using the 80/20 Principle Effectively

Discover how the Pareto Principle can transform your life by focusing on what truly matters for success.

Exploring Saturn: The Secrets Behind Its Unique Rings

Discover the intriguing formation of Saturn's rings and why some planets have them while others do not.