Topics Fastify Fundamentals Introduction to Fastify
beginner 14 min read

Introduction to Fastify

What is Fastify, its architecture, and how it compares to Express.js.

What is Fastify?

Fastify is a fast and low-overhead web framework for Node.js. It is inspired by Hapi and Express, with a focus on performance, schema-based validation, and developer experience.

Key Features

  • High Performance: Up to 2x faster than Express in benchmarks
  • Schema-Based: Built-in JSON Schema validation for routes
  • Plugin System: Encapsulated plugins for modular architecture
  • TypeScript Support: First-class TypeScript integration
  • Logging: Built-in Pino logger
const Fastify = require('fastify');\n\nconst app = Fastify({\n  logger: true, // Built-in Pino logger\n});\n\napp.get('/', async (request, reply) => {\n  return { hello: 'world' };\n});\n\nconst start = async () => {\n  try {\n    await app.listen({ port: 3000 });\n    console.log('Server listening on port 3000');\n  } catch (err) {\n    app.log.error(err);\n    process.exit(1);\n  }\n};\n\nstart();

Examples

const Fastify = require('fastify');

const app = Fastify({
  logger: {
    level: 'info',
    transport: {
      target: 'pino-pretty',
      options: { colorize: true },
    },
  },
});

app.get('/hello/:name', async (request, reply) => {
  const { name } = request.params;
  return { greeting: `Hello, ${name}!` };
});

app.get('/error', async (request, reply) => {
  throw new Error('Something went wrong');
});

const start = async () => {
  try {
    await app.listen({ port: 3000 });
    console.log('Server running at http://localhost:3000');
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.