Skip to content

Deploying a Blitz App

Blitz is a fullstack React framework built on Next.js that enables rapid development of scalable, production-ready applications. It combines the power of React with a Zero-API data layer, authentication out of the box, intelligent code scaffolding, and development conventions that accelerate your workflow. Blitz is ideal for developers and teams building modern web applications that require both frontend flexibility and backend performance.

This comprehensive guide walks you through deploying a Blitz application to Klutch.sh, covering both automatic Nixpacks-based deployments and Docker-based deployments. You’ll learn installation steps, explore sample code, configure environment variables, and discover best practices for production deployments.

Table of Contents

  • Prerequisites
  • Getting Started: Install Blitz
  • Sample Code Examples
  • Deploying Without a Dockerfile (Nixpacks)
  • Deploying With a Dockerfile
  • Environment Variables & Configuration
  • Scaling & Performance
  • Troubleshooting
  • Resources

Prerequisites

To deploy a Blitz application on Klutch.sh, ensure you have:

  • Node.js 18 or higher - Blitz requires a modern Node.js version
  • npm or yarn - For managing dependencies
  • Git - For version control
  • GitHub account - Klutch.sh integrates with GitHub for continuous deployments
  • Klutch.sh account - Sign up for free

Getting Started: Install Blitz

Create a New Blitz Project

Follow these steps to create a new Blitz application:

  1. Open your terminal and run the Blitz CLI to scaffold a new project:
    Terminal window
    npx create-blitz-app@latest my-blitz-app
    cd my-blitz-app

    This command creates a new directory with all necessary Blitz dependencies and configuration files.

  2. Install dependencies (if not already installed):
    Terminal window
    npm install

    Alternatively, if you prefer yarn:

    Terminal window
    yarn install
  3. Start the development server locally:
    Terminal window
    npm run dev

    Your Blitz application will be available at http://localhost:3000.

  4. Verify the app is running by visiting the URL in your browser. You should see the Blitz welcome page.

Project Structure

A typical Blitz project has the following structure:

my-blitz-app/
├── pages/ # Page components and API routes
├── app/ # Application modules and features
├── public/ # Static files
├── blitz.config.ts # Blitz configuration
├── tsconfig.json # TypeScript configuration
├── package.json # Dependencies and scripts
└── .env.local # Environment variables (local only)

Sample Code Examples

Basic Home Page (pages/index.tsx)

Create a simple home page to display in your Blitz application:

import { BlitzPage } from "@blitzjs/next"
import { useRouter } from "next/router"
const Home: BlitzPage = () => {
const router = useRouter()
return (
<div style={{ padding: "2rem", fontFamily: "system-ui, sans-serif" }}>
<h1>Welcome to Blitz</h1>
<p>Your fullstack React application is running on Klutch.sh</p>
<section style={{ marginTop: "2rem" }}>
<h2>Getting Started</h2>
<ul>
<li>Edit pages to create new routes</li>
<li>Use the <code>app</code> directory for business logic</li>
<li>Deploy to production with Klutch.sh</li>
</ul>
</section>
<footer style={{ marginTop: "3rem", borderTop: "1px solid #ccc", paddingTop: "1rem" }}>
<p>Deployed with <a href="https://klutch.sh?utm_source=docs" target="_blank">Klutch.sh</a></p>
</footer>
</div>
)
}
export default Home

API Route Example (pages/api/hello.ts)

Create a simple API endpoint:

import { BlitzApiRequest, BlitzApiResponse } from "@blitzjs/next"
export default function handler(req: BlitzApiRequest, res: BlitzApiResponse) {
if (req.method === "GET") {
res.status(200).json({ message: "Hello from Blitz API!" })
} else {
res.status(405).json({ error: "Method not allowed" })
}
}

Database Query Example

If you’re using Blitz’s database features, create a simple query:

app/posts/queries/getPosts.ts
import { Ctx } from "blitz"
import db from "db"
export default async function getPosts(_ = null, { session }: Ctx) {
return await db.post.findMany()
}

Deploying Without a Dockerfile

Klutch.sh automatically detects and builds Blitz applications using Nixpacks, eliminating the need for manual Docker configuration.

Deployment Steps

  1. Push your Blitz application to a GitHub repository. Ensure the repository is public or grant Klutch.sh access to your private repositories.
  2. Log in to the Klutch.sh Dashboard.
  3. Navigate to your project or create a new project and assign it a name (e.g., "my-blitz-app").
  4. Create a new application within your project with the following configuration:
    • Repository: Select your Blitz GitHub repository
    • Branch: Choose the branch to deploy (e.g., main or develop)
    • Traffic Type: Select HTTP (Blitz serves HTTP traffic)
    • Internal Port: Set to 3000 (the default Blitz development port)
    • Region: Choose your preferred region for deployment
    • Compute: Select appropriate compute tier based on your needs
    • Instances: Set the number of instances (start with 1 for testing)
    • Environment Variables: Add any required variables (see Configuration section below)
  5. Click the **Create** button to initiate the deployment. Klutch.sh will automatically: - Detect your Blitz project - Install dependencies using npm or yarn - Build your application with optimizations - Deploy the application to your chosen region
  6. Monitor the deployment progress in the dashboard. Your app will be accessible at a URL like `example-app.klutch.sh` within a few minutes.

Customizing Build & Start Commands

If you need to customize how Blitz is built or started, set Nixpacks environment variables:

Custom Build Command:

BUILD_COMMAND=npm run build:custom

Custom Start Command:

START_COMMAND=npm run start:production

Add these in the environment variables section when creating your app.

Example Deployed App

Once deployed, your Blitz app will be available at:

https://example-app.klutch.sh

Deploying With a Dockerfile

For advanced users who prefer Docker-based deployments, Klutch.sh automatically detects a Dockerfile in your repository’s root directory.

Creating a Dockerfile for Blitz

Create a Dockerfile in your project root with the following content:

# Stage 1: Build stage
FROM node:18-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci
# Copy application code
COPY . .
# Build Blitz application
RUN npm run build
# Stage 2: Runtime stage
FROM node:18-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install production dependencies only
RUN npm ci --omit=dev
# Copy built application from builder stage
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/blitz.config.ts ./
# Expose port (match your Blitz app configuration)
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"
# Start the application
CMD ["npm", "start"]

Key Dockerfile Features

  • Multi-stage build: Reduces final image size by separating build and runtime environments
  • Alpine base image: Uses lightweight node:18-alpine for smaller deployments
  • Production dependencies only: The runtime stage installs only production dependencies with --omit=dev
  • Health checks: Enables Klutch.sh to monitor application health
  • Port 3000: Standard Blitz port, adjustable based on your configuration

Deployment Steps with Docker

  1. Create the `Dockerfile` as shown above in your project root directory.
  2. Optionally, create a `.dockerignore` file to exclude unnecessary files:
    node_modules
    npm-debug.log
    .git
    .gitignore
    README.md
    .env.local
    .next
    dist
  3. Commit and push your code (including the Dockerfile) to your GitHub repository:
    Terminal window
    git add Dockerfile .dockerignore
    git commit -m "Add Docker configuration for Blitz deployment"
    git push origin main
  4. Log in to the Klutch.sh Dashboard.
  5. Create a new application with your Blitz repository. Klutch.sh will automatically detect your Dockerfile and use it for deployment.

    Configuration details:

    • Traffic Type: Select HTTP (standard web traffic)
    • Internal Port: Set to 3000 (or your configured port)
    • Region & Compute: Choose based on your requirements
    • Environment Variables: Add production environment variables as needed
  6. Click **Create** to deploy. Klutch.sh will build your Docker image and deploy the application.
  7. Your Blitz app will be live at `example-app.klutch.sh` after the deployment completes.

Docker Compose (Local Development Only)

For local development with services like PostgreSQL, use Docker Compose:

version: '3.8'
services:
blitz-app:
build: .
ports:
- "3000:3000"
environment:
DATABASE_URL: "postgresql://user:password@postgres:5432/blitz_db"
depends_on:
- postgres
postgres:
image: postgres:15-alpine
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: blitz_db
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:

Run locally with:

Terminal window
docker-compose up

Note: Docker Compose is for local development only. Klutch.sh doesn’t support Docker Compose deployments; use individual containers for each service in production.


Environment Variables & Configuration

Setting Environment Variables

Environment variables are essential for production deployments. Configure them in the Klutch.sh dashboard:

  1. Navigate to your app settings in the dashboard
  2. Find the Environment Variables section
  3. Add key-value pairs for your production environment

Common Environment Variables for Blitz

NODE_ENV=production
DATABASE_URL=postgresql://user:password@host:port/database
API_KEY=your-api-key-here
LOG_LEVEL=info

Blitz-Specific Configuration (blitz.config.ts)

Customize your Blitz application’s build and runtime behavior:

import { BlitzConfig, sessionMiddleware, simpleRolesIsAuthorized } from "blitz"
const config: BlitzConfig = {
middleware: [
sessionMiddleware({
sessionExpiryMinutes: 24 * 60,
method: "essential",
isAuthorized: simpleRolesIsAuthorized,
}),
],
/* Blitz options */
cli: {
clear: process.env.NODE_ENV === "production",
},
images: {
domains: ["klutch.sh"], // Add your CDN domains
},
}
export default config

Production Best Practices

  • Set NODE_ENV=production to enable optimizations
  • Use environment-specific configurations for database connections
  • Secure sensitive keys using Klutch.sh’s environment variable management
  • Enable CORS only for trusted domains
  • Use HTTPS for all external communications

Scaling & Performance

Horizontal Scaling

Klutch.sh allows you to run multiple instances of your Blitz application:

  1. In the dashboard, update your app settings.
  2. Increase the **number of instances** (e.g., from 1 to 3).
  3. Traffic will be automatically load-balanced across instances.

Performance Optimization Tips

  • Optimize images: Use Next.js Image optimization
  • Code splitting: Blitz automatically handles route-based code splitting
  • Database indexing: Index frequently queried fields
  • Caching: Implement Redis for session and data caching
  • CDN: Use Klutch.sh’s built-in CDN for static assets

Database Persistence

If your Blitz app requires a database, deploy a separate database service on Klutch.sh:

  1. Deploy a PostgreSQL database or other database as a separate app.
  2. Obtain the database connection string from the database app's details page.
  3. Add the connection string to your Blitz app's environment variables (e.g., `DATABASE_URL`).
  4. Run database migrations during deployment or manually using Blitz's CLI.

Troubleshooting

Common Issues & Solutions

Problem: Application fails to start

  • Check environment variables are correctly set
  • Verify all required dependencies are in package.json
  • Review logs in the Klutch.sh dashboard for error messages

Problem: Database connection errors

  • Confirm DATABASE_URL is correctly formatted
  • Ensure the database service is running and accessible
  • Check network connectivity between app and database services

Problem: Out of memory errors

  • Increase the compute tier in app settings
  • Optimize your application’s memory usage
  • Consider breaking large operations into smaller tasks

Problem: Build failures with Docker

  • Ensure Dockerfile syntax is correct
  • Verify all required files are included (.dockerignore doesn’t exclude essentials)
  • Test locally with docker build . before pushing to GitHub

Problem: Port conflicts or connectivity issues

  • Ensure the internal port matches your Blitz configuration
  • Verify the port isn’t already in use by another service
  • Check Klutch.sh firewall and security settings

Resources

Explore these resources for more information:


Summary

Deploying a Blitz application to Klutch.sh is straightforward and flexible. Whether you choose the automatic Nixpacks approach or prefer Docker-based deployments, Klutch.sh provides the tools and infrastructure to run production-ready Blitz applications at scale.

Key Takeaways:

  • Use Nixpacks for quick, zero-configuration deployments
  • Use Docker for advanced customization and optimization
  • Configure environment variables for production settings
  • Scale horizontally by increasing instance counts
  • Monitor and optimize performance through the dashboard

Get started today by creating your first project on Klutch.sh.