Learn FASTIFY with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
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.
2
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.
3
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.
4
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.
5
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.
6
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.
7
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.
8
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.
9
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.
10
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.