Learn Fastify - 10 Code Examples & CST Typing Practice Test
Fastify is a high-performance, low-overhead web framework for Node.js. It emphasizes speed, schema-based validation, and a developer-friendly plugin system for building APIs and backend services.
View all 10 Fastify code examples →
Learn FASTIFY with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
Fastify Simple Counter API
const fastify = require('fastify')({ logger: true })
let count = 0
fastify.get('/counter', async (request, reply) => {
return { count }
})
fastify.post('/counter/increment', async (request, reply) => {
count++
return { count }
})
fastify.post('/counter/decrement', async (request, reply) => {
count--
return { count }
})
fastify.post('/counter/reset', async (request, reply) => {
count = 0
return { count }
})
const start = async () => {
try {
await fastify.listen({ port: 3000 })
console.log('Fastify server running on http://localhost:3000')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
Demonstrates a simple Fastify REST API with a counter using routes and state management.
Fastify Query Params Example
const fastify = require('fastify')({ logger: true })
fastify.get('/greet', async (request, reply) => {
const name = request.query.name || 'Guest'
return `Hello, ${name}!`
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Handle query parameters in GET requests.
Fastify URL Params Example
const fastify = require('fastify')({ logger: true })
fastify.get('/user/:id', async (request, reply) => {
const userId = request.params.id
return `User ID: ${userId}`
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Handle dynamic URL parameters in Fastify routes.
Fastify JSON Body Example
const fastify = require('fastify')({ logger: true })
fastify.register(require('@fastify/formbody'))
fastify.post('/echo', async (request, reply) => {
return { received: request.body }
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Parse JSON body data in POST requests.
Fastify Middleware Example
const fastify = require('fastify')({ logger: true })
fastify.addHook('preHandler', async (request, reply) => {
console.log(`${request.method} ${request.url}`)
})
fastify.get('/', async (request, reply) => {
return 'Middleware example'
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Custom preHandler middleware logging requests.
Fastify Static Files Example
const fastify = require('fastify')({ logger: true })
fastify.register(require('@fastify/static'), { root: __dirname + '/public' })
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Serve static files using Fastify.
Fastify Router Example
const fastify = require('fastify')({ logger: true })
const plugin = async (instance, options) => {
instance.get('/hello', async (request, reply) => {
return 'Hello from plugin'
})
}
fastify.register(plugin, { prefix: '/api' })
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Organize routes using Fastify plugin.
Fastify Error Handling Example
const fastify = require('fastify')({ logger: true })
fastify.get('/error', async (request, reply) => {
throw new Error('Something went wrong')
})
fastify.setErrorHandler(async (error, request, reply) => {
console.error(error.message)
reply.status(500).send('Server Error')
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Custom error handling in Fastify.
Fastify CORS Example
const fastify = require('fastify')({ logger: true })
fastify.register(require('@fastify/cors'))
fastify.get('/', async (request, reply) => {
return 'CORS enabled'
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Enable CORS for all routes.
Fastify Environment Variables Example
require('dotenv').config()
const fastify = require('fastify')({ logger: true })
const port = process.env.PORT || 3000
fastify.get('/', async (request, reply) => {
return `Server running on port ${port}`
})
fastify.listen({ port }, (err, address) => {
if (err) throw err
console.log(`Server running at ${address}`)
})
Access environment variables in Fastify.
Frequently Asked Questions about Fastify
What is Fastify?
Fastify is a high-performance, low-overhead web framework for Node.js. It emphasizes speed, schema-based validation, and a developer-friendly plugin system for building APIs and backend services.
What are the primary use cases for Fastify?
Building RESTful and JSON APIs. High-performance backend for web/mobile apps. Microservices architecture. Server-side processing for IoT or real-time systems. Integrating with TypeScript for strongly-typed APIs
What are the strengths of Fastify?
High throughput and low latency. Strong TypeScript support. Plugin system simplifies modular development. Built-in JSON validation ensures reliable APIs. Automatic performance optimizations for routes
What are the limitations of Fastify?
Smaller ecosystem compared to Express.js. Requires learning Fastify hooks and plugin system. Some middleware from Express may require adaptation. Not ideal for simple static websites. Verbose schema definitions for complex APIs
How can I practice Fastify typing speed?
CodeSpeedTest offers 10+ real Fastify code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.