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:
-
Open your terminal and run the Blitz CLI to scaffold a new project:
Terminal window npx create-blitz-app@latest my-blitz-appcd my-blitz-appThis command creates a new directory with all necessary Blitz dependencies and configuration files.
-
Install dependencies (if not already installed):
Terminal window npm installAlternatively, if you prefer yarn:
Terminal window yarn install -
Start the development server locally:
Terminal window npm run devYour Blitz application will be available at http://localhost:3000.
- 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 HomeAPI 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:
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
- Push your Blitz application to a GitHub repository. Ensure the repository is public or grant Klutch.sh access to your private repositories.
- Log in to the Klutch.sh Dashboard.
- Navigate to your project or create a new project and assign it a name (e.g., "my-blitz-app").
-
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.,
mainordevelop) - 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)
- 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
- 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:customCustom Start Command:
START_COMMAND=npm run start:productionAdd 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.shDeploying 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 stageFROM node:18-alpine AS builder
WORKDIR /app
# Copy package filesCOPY package*.json ./
# Install dependenciesRUN npm ci
# Copy application codeCOPY . .
# Build Blitz applicationRUN npm run build
# Stage 2: Runtime stageFROM node:18-alpine
WORKDIR /app
# Copy package filesCOPY package*.json ./
# Install production dependencies onlyRUN npm ci --omit=dev
# Copy built application from builder stageCOPY --from=builder /app/.next ./.nextCOPY --from=builder /app/public ./publicCOPY --from=builder /app/blitz.config.ts ./
# Expose port (match your Blitz app configuration)EXPOSE 3000
# Health checkHEALTHCHECK --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 applicationCMD ["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-alpinefor 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
- Create the `Dockerfile` as shown above in your project root directory.
-
Optionally, create a `.dockerignore` file to exclude unnecessary files:
node_modulesnpm-debug.log.git.gitignoreREADME.md.env.local.nextdist
-
Commit and push your code (including the Dockerfile) to your GitHub repository:
Terminal window git add Dockerfile .dockerignoregit commit -m "Add Docker configuration for Blitz deployment"git push origin main - Log in to the Klutch.sh Dashboard.
-
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
- Click **Create** to deploy. Klutch.sh will build your Docker image and deploy the application.
- 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:
docker-compose upNote: 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:
- Navigate to your app settings in the dashboard
- Find the Environment Variables section
- Add key-value pairs for your production environment
Common Environment Variables for Blitz
NODE_ENV=productionDATABASE_URL=postgresql://user:password@host:port/databaseAPI_KEY=your-api-key-hereLOG_LEVEL=infoBlitz-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 configProduction Best Practices
- Set
NODE_ENV=productionto 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:
- In the dashboard, update your app settings.
- Increase the **number of instances** (e.g., from 1 to 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:
- Deploy a PostgreSQL database or other database as a separate app.
- Obtain the database connection string from the database app's details page.
- Add the connection string to your Blitz app's environment variables (e.g., `DATABASE_URL`).
- 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_URLis 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
Dockerfilesyntax is correct - Verify all required files are included (
.dockerignoredoesn’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:
- Klutch.sh Official Website
- Blitz.js Official Documentation
- Next.js Documentation
- Nixpacks Documentation
- PostgreSQL Documentation
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.