← Back to blog
· 4 min read · By Judson Cairo
Building Scalable APIs with Node.js and Fastify
Node.js TypeScript Tutorial
Introduction
Fastify is one of the fastest Node.js web frameworks available. In this tutorial, we'll build a scalable REST API from scratch.
Setting Up the Project
Bash
mkdir my-api && cd my-api
npm init -y
npm install fastify @fastify/cors
npm install -D typescript @types/node
Creating the Server
Text
# Builder stage
FROM node:24-alpine AS builder
# Build dependencies
RUN apk update && apk add --no-cache python3 build-base git
RUN corepack enable && corepack prepare pnpm@10.6.5 --activate
WORKDIR /app
# Faster, reproducible installs
RUN pnpm config set store-dir /root/.pnpm-store && pnpm config set prefer-frozen-lockfile true
COPY package.json pnpm-lock.yaml ./
COPY .npmrc* .pnpmfile.cjs* ./
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
# Production stage
FROM node:24-alpine AS production
RUN addgroup -g 1001 nodejs && adduser -S -u 1001 -G nodejs api
RUN corepack enable && corepack prepare pnpm@10.6.5 --activate
# Runtime deps: ffmpeg + yt-dlp prerequisites
RUN apk update && apk add --no-cache ffmpeg python3 py3-pip ca-certificates curl
RUN pip3 install --break-system-packages --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider
WORKDIR /app
ENV NODE_ENV=production CI=false
COPY .npmrc* .pnpmfile.cjs* ./
COPY package.json pnpm-lock.yaml ./
RUN pnpm config set store-dir /root/.pnpm-store && \
pnpm config set prefer-frozen-lockfile true && \
pnpm install --frozen-lockfile --prod && \
pnpm store prune && \
npm cache clean --force && \
rm -rf /root/.npm /root/.pnpm-store /tmp/*
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/src/views ./src/views
COPY --from=builder /app/drizzle.config.ts ./drizzle.config.ts
COPY --from=builder /app/src/db/migrations ./src/db/migrations
RUN mkdir -p /app/uploads /uploads && \
chown -R api:nodejs /app/uploads /uploads && \
chmod -R 775 /app/uploads /uploads && \
chown -R api:nodejs /app
USER api
EXPOSE 6795
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:6795/health || exit 1
CMD ["pnpm", "start:prod"]
Adding Routes and Validation
Fastify uses JSON Schema for request validation, making it both fast and type-safe.
Conclusion
Fastify provides an excellent foundation for building production-ready APIs.