Skip to content
nextjs-deployment logo

Next.js Deployment

nextjs-deployment

Complete Next.js deployment system (Next.js 15.5/16). PROACTIVELY activate for: (1) Vercel deployment and configuration, (2) Self-hosted Node.js deployment, (3) Docker containerization, (4) Static export with output:'export', (5) Edge Runtime configuration, (6) Environment variables, (7) CI/CD wi...

SKILL.md

Full skill instructions

Quick Reference

Output ModeConfigUse Case
Default-Vercel/​Node.js hosting
Standaloneoutput: 'standalone'Docker containers
Staticoutput: 'export'Static hosting (no SSR)
PlatformCommandNotes
Vercelvercel --prodAutomatic, recommended
Node.jsnpm run build && npm startSelf-hosted
Dockerdocker build -t app .Container deployment
Staticnpm run build → out/CDN hosting
RuntimeConfigFeatures
Node.jsDefaultFull features
Edgeexport const runtime = 'edge'Fast, limited APIs
EnvironmentFileUsage
Development.env.localLocal dev
Production.env.productionBuild time
RuntimePlatform secretsServer runtime

When to Use This Skill

Use for deployment and production:

  • Deploying to Vercel (easiest path)
  • Self-hosting with Docker or Node.js
  • Static export for CDN hosting
  • Setting up CI/​CD pipelines
  • Production configuration and monitoring

Related skills:

  • For middleware: see nextjs-middleware
  • For caching in production: see nextjs-caching
  • For authentication: see nextjs-authentication

Next.js Deployment

Vercel Deployment

Automatic Deployment

# Install Vercel CLI
npm i -g vercel

# Deploy
vercel

# Production deployment
vercel --prod

Environment Variables

# Set environment variables
vercel env add DATABASE_URL production

# Pull env vars locally
vercel env pull .env.local

vercel.json Configuration

{
  "buildCommand": "npm run build",
  "outputDirectory": ".next",
  "framework": "nextjs",
  "regions": ["iad1", "sfo1"],
  "functions": {
    "app/​api/​**/​*.ts": {
      "memory": 1024,
      "maxDuration": 30
    }
  },
  "headers": [
    {
      "source": "/​api/(.*)",
      "headers": [
        { "key": "Access-Control-Allow-Origin", "value": "*" }
      ]
    }
  ],
  "redirects": [
    {
      "source": "/​old-page",
      "destination": "/​new-page",
      "permanent": true
    }
  ],
  "rewrites": [
    {
      "source": "/​api/​proxy/:path*",
      "destination": "https://api.example.com/:path*"
    }
  ]
}

Self-Hosted Deployment

Node.js Server

# Build the application
npm run build

# Start production server
npm run start

Custom Server

// server.ts
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';

const dev = process.env.NODE_ENV !== 'production';
const hostname = process.env.HOSTNAME || 'localhost';
const port = parseInt(process.env.PORT || '3000', 10);

const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      const parsedUrl = parse(req.url!, true);
      await handle(req, res, parsedUrl);
    } catch (err) {
      console.error('Error occurred handling', req.url, err);
      res.statusCode = 500;
      res.end('Internal Server Error');
    }
  })
    .once('error', (err) => {
      console.error(err);
      process.exit(1);
    })
    .listen(port, () => {
      console.log(`> Ready on http://${hostname}:${port}`);
    });
});

PM2 Process Manager

// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'nextjs-app',
      script: 'npm',
      args: 'start',
      instances: 'max',
      exec_mode: 'cluster',
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      env: {
        NODE_ENV: 'production',
        PORT: 3000,
      },
    },
  ],
};
# Start with PM2
pm2 start ecosystem.config.js

# Monitor
pm2 monit

# Logs
pm2 logs

Docker Deployment

Dockerfile

# Dockerfile
FROM node:20-alpine AS base

# Dependencies stage
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /​app

COPY package.json package-lock.json* ./
RUN npm ci

# Builder stage
FROM base AS builder
WORKDIR /​app
COPY --from=deps /​app/​node_modules ./​node_modules
COPY . .

ENV NEXT_TELEMETRY_DISABLED 1

RUN npm run build

# Runner stage
FROM base AS runner
WORKDIR /​app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /​app/​public ./​public

# Automatically leverage output traces
COPY --from=builder --chown=nextjs:nodejs /​app/​.next/​standalone ./
COPY --from=builder --chown=nextjs:nodejs /​app/​.next/​static ./​.next/​static

USER nextjs

EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

CMD ["node", "server.js"]

next.config.js for Standalone

// next.config.js
/​** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
};

module.exports = nextConfig;

Docker Compose

# docker-compose.yml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - '3000:3000'
    environment:
      - DATABASE_URL=postgresql://user:password@db:5432/​mydb
      - NEXTAUTH_SECRET=your-secret
      - NEXTAUTH_URL=http://localhost:3000
    depends_on:
      - db

  db:
    image: postgres:15-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: mydb
    volumes:
      - postgres_data:/​var/​lib/​postgresql/​data

volumes:
  postgres_data:

Static Export

Configuration

// next.config.js
/​** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  // Optional: Change the output directory
  distDir: 'dist',
  // Optional: Add trailing slashes
  trailingSlash: true,
  // Optional: Disable image optimization
  images: {
    unoptimized: true,
  },
};

module.exports = nextConfig;

Build Static Export

npm run build
# Output in 'out' directory (or distDir if configured)

Limitations

  • No Server-Side Rendering
  • No API Routes
  • No Middleware
  • No ISR
  • Image Optimization requires external service

Edge Runtime

Edge Route Handler

// app/​api/​edge/​route.ts
export const runtime = 'edge';

export async function GET(request: Request) {
  return new Response(JSON.stringify({ message: 'Hello from Edge!' }), {
    headers: { 'content-type': 'application/​json' },
  });
}

Edge Middleware

// middleware.ts
// Runs on Edge by default
import { NextResponse } from 'next/​server';

export function middleware(request: Request) {
  return NextResponse.next();
}

Edge Config (Vercel)

import { get } from '@vercel/​edge-config';

export const runtime = 'edge';

export async function GET() {
  const greeting = await get('greeting');
  return Response.json({ greeting });
}

Production Checklist

Environment Variables

# .env.production
DATABASE_URL=
NEXTAUTH_SECRET=
NEXTAUTH_URL=https://myapp.com
NEXT_PUBLIC_API_URL=https://api.myapp.com

next.config.js Production

/​** @type {import('next').NextConfig} */
const nextConfig = {
  // Strict mode for development
  reactStrictMode: true,

  // Optimize images
  images: {
    domains: ['images.example.com'],
    formats: ['image/​avif', 'image/​webp'],
  },

  // Security headers
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          { key: 'X-Frame-Options', value: 'DENY' },
          { key: 'X-Content-Type-Options', value: 'nosniff' },
          { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
        ],
      },
    ];
  },

  // Redirects
  async redirects() {
    return [
      {
        source: '/​old-blog/:slug',
        destination: '/​blog/:slug',
        permanent: true,
      },
    ];
  },

  // Experimental features
  experimental: {
    // Enable PPR
    ppr: true,
  },
};

module.exports = nextConfig;

Health Check Endpoint

// app/​api/​health/​route.ts
import { NextResponse } from 'next/​server';

export async function GET() {
  try {
    // Check database connection
    await db.$queryRaw`SELECT 1`;

    return NextResponse.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    return NextResponse.json(
      { status: 'unhealthy', error: 'Database connection failed' },
      { status: 503 }
    );
  }
}

Monitoring

Error Tracking (Sentry)

// next.config.js
const { withSentryConfig } = require('@sentry/​nextjs');

const nextConfig = {
  // Your config
};

module.exports = withSentryConfig(nextConfig, {
  silent: true,
  org: 'your-org',
  project: 'your-project',
});
// sentry.client.config.ts
import * as Sentry from '@sentry/​nextjs';

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

Analytics

// app/​layout.tsx
import { Analytics } from '@vercel/​analytics/​react';
import { SpeedInsights } from '@vercel/​speed-insights/​next';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
        <SpeedInsights />
      </​body>
    </​html>
  );
}

CI/​CD

GitHub Actions

# .github/​workflows/​deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/​checkout@v4

      - name: Setup Node.js
        uses: actions/​setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build
        run: npm run build

      - name: Deploy to Vercel
        uses: amondnet/​vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: '--prod'

Best Practices

PracticeDescription
Use output: 'standalone'Smaller Docker images
Set proper env varsUse Vercel/​platform secrets
Enable cachingUse CDN, browser caching
Monitor performanceVercel Analytics, Sentry
Use health checksLoad balancer integration
Enable compressionGzip/​Brotli in reverse proxy

More skills from JosiahSiegel

debugging-troubleshooting-2025 logo
JosiahSiegel/claude-plugin-marketplace

debugging-troubleshooting-2025

Comprehensive bash script debugging and troubleshooting techniques for 2025. PROACTIVELY activate for: (1) debugging a misbehaving bash script, (2) using set -x, set -e, set -u, set -o pipefail (strict mode), (3) customizing PS4 for richer trace output, (4) trap DEBUG, ERR, and EXIT for diagnosti...

58 0
View
tailwindcss-accessibility logo
JosiahSiegel/claude-plugin-marketplace

tailwindcss-accessibility

Tailwind CSS accessibility patterns including WCAG 2.2 compliance, touch targets, focus management, and ARIA. PROACTIVELY activate for: (1) building accessible UI with Tailwind, (2) WCAG 2.2 compliance (Level A, AA, AAA), (3) focus rings and focus-visible styling, (4) minimum touch-target sizes (...

58 0
View
sql-server-2025 logo
JosiahSiegel/claude-plugin-marketplace

sql-server-2025

SQL Server 2025 and SqlPackage 170.2.70 (October 2025) — vector databases, AI integration, and modern features. PROACTIVELY activate for: (1) SQL Server 2025 features, (2) vector type and vector indexes for AI, (3) Vector functions (VECTOR_DISTANCE, etc.), (4) AI integration (Azure OpenAI, embedd...

58 0
View
adf-master logo
JosiahSiegel/claude-plugin-marketplace

adf-master

Azure Data Factory (ADF) CI/CD, deployment, and pipeline development. PROACTIVELY activate for: (1) ADF CI/CD setup (npm validation, ARM template export), (2) ADF ARM template deployment, (3) ADF npm build validation in CI, (4) PrePostDeploymentScript for trigger and resource cleanup, (5) ADF Git...

58 0
View
powershell-security logo
JosiahSiegel/claude-plugin-marketplace

powershell-security

Modern PowerShell security practices for 2025 — SecretManagement, JEA, WDAC, credential protection. PROACTIVELY activate for: (1) Microsoft.PowerShell.SecretManagement and SecretStore for credential storage, (2) Just Enough Administration (JEA) endpoints, (3) Windows Defender Application Control ...

58 0
View
nextjs-middleware logo
JosiahSiegel/claude-plugin-marketplace

nextjs-middleware

Complete Next.js Middleware system (Next.js 15.5/16). PROACTIVELY activate for: (1) Creating middleware.ts (Edge) or proxy.ts (Node.js), (2) Matcher configuration, (3) Authentication protection, (4) Role-based access control, (5) Redirects and rewrites, (6) Internationalization (i18n), (7) Securi...

58 0
View
nextjs-data-fetching logo
JosiahSiegel/claude-plugin-marketplace

nextjs-data-fetching

Complete Next.js data fetching system (Next.js 15.5/16). PROACTIVELY activate for: (1) Server Component data fetching, (2) Parallel and sequential fetching, (3) Streaming with Suspense, (4) Route Handlers (API routes), (5) Client-side fetching with SWR/TanStack Query, (6) generateStaticParams for...

58 0
View
advanced-features-2025 logo
JosiahSiegel/claude-plugin-marketplace

advanced-features-2025

Advanced Claude Code plugin features for hooks, MCP integration, team distribution, and progressive disclosure. PROACTIVELY activate for: (1) progressive disclosure design, (2) hook automation, (3) PreToolUse and PostToolUse hooks, (4) MCP server integration, (5) .mcp.json configuration, (6) team...

58 0
View
azure-sql-optimization logo
JosiahSiegel/claude-plugin-marketplace

azure-sql-optimization

Azure SQL Database optimization and platform-specific features. PROACTIVELY activate for: (1) Azure SQL Database optimization, (2) DTU vs vCore selection and right-sizing, (3) automatic tuning (force last good plan, create/drop index), (4) Hyperscale tier and read replicas, (5) Serverless tier an...

58 0
View
github-actions-2025 logo
JosiahSiegel/claude-plugin-marketplace

github-actions-2025

GitHub Actions 2025-2026 features and modernization. PROACTIVELY activate for: (1) 1 vCPU Linux runners (October 2025 public preview), (2) immutable releases for hardened distribution, (3) Node24 migration from Node20, (4) reusable workflows and composite actions, (5) workflow_dispatch with rich ...

58 0
View
git-2-49-features logo
JosiahSiegel/claude-plugin-marketplace

git-2-49-features

Git 2.49 specific features and performance improvements. PROACTIVELY activate for: (1) git-backfill command (new in 2.49) for partial clones, (2) path-walk API improvements, (3) zlib-ng integration for faster compression, (4) reftables backend stabilization, (5) revision-walk performance, (6) bun...

58 0
View
vitest-3-features logo
JosiahSiegel/claude-plugin-marketplace

vitest-3-features

Vitest 3 features and migration from Vitest 2 (2025). PROACTIVELY activate for: (1) Vitest 3 stable features, (2) workspace mode for monorepos, (3) test annotations and reporter API, (4) projects configuration, (5) browser mode in Vitest 3, (6) inline snapshots and toMatchInlineSnapshot, (7) type...

58 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View