Next.js course Β· Module 8: Deployment and Production
Preview Deployments and staging environments
In this lesson6
In Quantum Metropolis 2150, no system goes directly to production servers. Every change goes through a rigorous verification process - from preview deployments for individual Pull Requests, through the staging environment, to a controlled promotion to production. Such a pipeline ensures that residents of Quantum City never experience faulty code.
What are Preview Deployments?
Preview Deployments are automatic application deployments generated for each Pull Request. Every PR receives its own, unique URL at which changes can be tested before being merged into the main branch.
Vercel - the platform created by the Next.js authors - offers the best support for Preview Deployments. But other platforms, like Netlify or AWS Amplify, also support this concept.
How do Preview Deployments work on Vercel?
- You create a Pull Request on GitHub
- Vercel automatically detects the new PR
- Builds the application with code from this PR
- Generates a unique URL (e.g.
project-git-feature-xyz-team.vercel.app) - Adds a comment to the PR with a link to the preview
# Example Preview Deployments URLs:
# PR #42: my-app-git-feature-login-myteam.vercel.app
# PR #43: my-app-git-fix-header-myteam.vercel.app
# PR #44: my-app-git-update-api-myteam.vercel.app
# Each URL is unique and works as long as the PR existsConfiguring Vercel for Preview Deployments
// vercel.json
{
"git": {
"deploymentEnabled": {
"main": true,
"staging": true
}
},
"github": {
"autoAlias": true,
"autoJobCancelation": true,
"silent": false
},
"headers": [
{
"source": "/(.*)",
"headers": [
{
"key": "X-Robots-Tag",
"value": "noindex"
}
]
}
]
}Important note: Preview Deployments should have the header X-Robots-Tag: noindex so that search engines do not index test versions!
Deployment environments (dev β staging β prod)
Professional projects use a multi-level deployment pipeline:
Hierarchy of environments
Development (dev) β Developer's local machine
β
Preview β Automatic per-PR (Vercel Preview)
β
Staging β Production mirror (final tests)
β
Production (prod) β Production servers (end users)Branch-based deployments
Each Git branch can be mapped to a different environment:
# Branch β environment configuration in Vercel:
# main β Production (app.quantum-city.com)
# staging β Staging (staging.quantum-city.com)
# develop β Development (dev.quantum-city.com)
# feature/* β Preview (auto-generated URL)
# Developer workflow:
git checkout -b feature/new-dashboard
# ... coding ...
git push origin feature/new-dashboard
# β Automatically: Preview Deployment!
# After review and merge into staging:
git checkout staging
git merge feature/new-dashboard
git push origin staging
# β Automatically: Staging Deployment!
# After tests on staging, merge into main:
git checkout main
git merge staging
git push origin main
# β Automatically: Production Deployment!Environment variables per environment
Each environment has its own variables:
// Vercel CLI - adding variables per environment
// vercel env add DATABASE_URL development
// vercel env add DATABASE_URL preview
// vercel env add DATABASE_URL production
// In the code, we check the environment:
// app/api/config/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
const environment = process.env.VERCEL_ENV; // 'production' | 'preview' | 'development'
const gitBranch = process.env.VERCEL_GIT_COMMIT_REF; // e.g. 'feature/login'
const commitSha = process.env.VERCEL_GIT_COMMIT_SHA; // commit hash
return NextResponse.json({
environment,
branch: gitBranch,
commit: commitSha?.slice(0, 7),
// Different databases per environment
database: environment === 'production'
? 'prod-cluster'
: environment === 'preview'
? 'preview-cluster'
: 'dev-cluster',
});
}Protected Deployments
In the staging and preview environments, it's worth protecting access so that unauthorized people do not see unpublished changes:
// middleware.ts - protecting preview and staging
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const environment = process.env.VERCEL_ENV;
// Do not protect production
if (environment === 'production') {
return NextResponse.next();
}
// Check authorization for preview/staging
const authHeader = request.headers.get('authorization');
const previewToken = process.env.PREVIEW_ACCESS_TOKEN;
// Allow access with a token or cookie
const hasToken = authHeader === 'Bearer ' + previewToken;
const hasCookie = request.cookies.get('preview-access')?.value === previewToken;
if (!hasToken && !hasCookie) {
// Redirect to the preview login page
return NextResponse.redirect(new URL('/preview-login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!preview-login|api|_next/static|favicon.ico).*)'],
};Deployment Hooks - deployment automation
Deploy Hooks are webhook URLs that trigger a new deployment when called:
# Creating a Deploy Hook in Vercel:
# Settings β Git β Deploy Hooks
# Name: "CMS Content Update"
# Branch: main
# β Generates URL: https://api.vercel.com/v1/integrations/deploy/prj_xxx/yyy
# Usage with CMS (e.g., after publishing an article):
curl -X POST https://api.vercel.com/v1/integrations/deploy/prj_xxx/yyy
# Usage in GitHub Actions:
# - name: Trigger Vercel Deploy
# run: curl -X POST ${{ secrets.VERCEL_DEPLOY_HOOK }}
# Usage with Strapi/Sanity webhook:
# After publishing content β POST to Deploy Hook URL
# β Vercel rebuilds the page with new data (ISR/SSG)Practical workflow with Deploy Hooks
// app/api/webhook/cms/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
// Verifying the webhook from the CMS
const signature = request.headers.get('x-webhook-signature');
const secret = process.env.CMS_WEBHOOK_SECRET;
if (!verifySignature(signature, secret)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
// Trigger revalidation or new deploy
const deployHookUrl = process.env.VERCEL_DEPLOY_HOOK;
if (deployHookUrl) {
await fetch(deployHookUrl, { method: 'POST' });
return NextResponse.json({ status: 'Deploy triggered' });
}
return NextResponse.json({ status: 'No deploy hook configured' });
}
function verifySignature(signature: string | null, secret: string | undefined): boolean {
if (!signature || !secret) return false;
// HMAC verification implementation
return true;
}Environment Promotion (dev β staging β prod)
Environment promotion is the controlled process of moving code between environments:
# Strategy 1: Git-flow with automatic deploy
# develop β auto-deploy to dev
# staging β auto-deploy to staging
# main β auto-deploy to production
# Merge workflow:
git checkout staging
git merge develop # Promote dev β staging
git push origin staging # Auto-deploy to staging
# After tests on staging:
git checkout main
git merge staging # Promote staging β prod
git push origin main # Auto-deploy to production
# Strategy 2: Vercel Promote (without merge)
# Vercel allows promoting an existing deployment:
vercel promote [deployment-url] --scope=team
# This moves EXACTLY the same build to production
# Without rebuilding - guarantee of identity!Summary
Preview Deployments and staging environments are the foundations of a professional deployment process:
- Preview Deployments - automatic per-PR deployments, ideal for code review
- Branch-based deployments - mapping branches to environments (dev/staging/prod)
- Environment promotion - controlled flow of code between environments
- Protected Deployments - protection of preview and staging from unauthorized access
- Deploy Hooks - automatic triggering of deployments from CMS or CI/CD
In Quantum Metropolis 2150, no system goes to production without the full preview β staging β production cycle. This guarantees the stability and quality of services for all residents of the cyberpunk city.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Demo: Preview Deployments and staging environments
interface Deployment {
id: string;
branch: string;
env: 'production' | 'staging' | 'preview';
url: string;
status: 'ready' | 'building' | 'error';
pr?: number;
commit: string;
age: string;
}
const deployments: Deployment[] = [
{ id: '1', branch: 'main', env: 'production', url: 'app.quantum-city.com', status: 'ready', commit: 'a1b2c3d', age: '2h ago' },
{ id: '2', branch: 'staging', env: 'staging', url: 'staging.quantum-city.com', status: 'ready', commit: 'e4f5g6h', age: '1h ago' },
{ id: '3', branch: 'feature/new-dashboard', env: 'preview', url: 'app-git-feature-new-dashboard-team.vercel.app', status: 'ready', pr: 42, commit: 'i7j8k9l', age: '30m ago' },
{ id: '4', branch: 'fix/header-layout', env: 'preview', url: 'app-git-fix-header-layout-team.vercel.app', status: 'building', pr: 43, commit: 'm0n1o2p', age: '5m ago' },
{ id: '5', branch: 'feature/auth-update', env: 'preview', url: 'app-git-feature-auth-team.vercel.app', status: 'error', pr: 44, commit: 'q3r4s5t', age: '15m ago' },
];
const envColors: Record<string, string> = { production: '#4caf50', staging: '#ff9800', preview: '#7c3aed' };
const statusColors: Record<string, string> = { ready: '#4caf50', building: '#2196f3', error: '#f44336' };
const pipeline = [
{ name: 'Development', desc: 'Local machine', icon: '1' },
{ name: 'Preview', desc: 'Auto per PR', icon: '2' },
{ name: 'Staging', desc: 'Final tests', icon: '3' },
{ name: 'Production', desc: 'Users', icon: '4' },
];
export default function PreviewDeploymentsDemo() {
const [filter, setFilter] = useState<'all' | 'production' | 'staging' | 'preview'>('all');
const [showPipeline, setShowPipeline] = useState(true);
const filtered = filter === 'all' ? deployments : deployments.filter(d => d.env === filter);
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
<h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Preview Deployments</h1>
<p style={{ color: '#8892b0', marginBottom: '24px' }}>Pipeline: dev -> preview -> staging -> production</p>
{showPipeline && (
<div style={{ display: 'flex', gap: '4px', marginBottom: '24px', alignItems: 'center' }}>
{pipeline.map((step, i) => (
<React.Fragment key={step.name}>
<div style={{
flex: 1, padding: '12px', borderRadius: '8px', textAlign: 'center',
background: '#1a1a2e', border: '1px solid #333',
}}>
<div style={{ color: '#64ffda', fontWeight: 'bold', fontSize: '20px' }}>{step.icon}</div>
<div style={{ color: '#fff', fontSize: '13px', fontWeight: 'bold' }}>{step.name}</div>
<div style={{ color: '#8892b0', fontSize: '11px' }}>{step.desc}</div>
</div>
{i < pipeline.length - 1 && <span style={{ color: '#64ffda', fontSize: '20px' }}>→</span>}
</React.Fragment>
))}
</div>
)}
<div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
{(['all', 'production', 'staging', 'preview'] as const).map(f => (
<button key={f} onClick={() => setFilter(f)} style={{
padding: '6px 12px', borderRadius: '6px', border: 'none', cursor: 'pointer', fontSize: '13px',
background: filter === f ? (f === 'all' ? '#64ffda' : envColors[f]) : '#1a1a2e',
color: filter === f ? '#0f0f23' : '#8892b0', fontWeight: 'bold',
}}>{f === 'all' ? 'All' : f.charAt(0).toUpperCase() + f.slice(1)}</button>
))}
<button onClick={() => setShowPipeline(!showPipeline)} style={{
padding: '6px 12px', borderRadius: '6px', border: '1px solid #333', background: 'transparent', color: '#8892b0', cursor: 'pointer', fontSize: '13px', marginLeft: 'auto',
}}>{showPipeline ? 'Hide pipeline' : 'Show pipeline'}</button>
</div>
<div style={{ display: 'grid', gap: '8px' }}>
{filtered.map(d => (
<div key={d.id} style={{
padding: '14px', borderRadius: '8px', background: '#1a1a2e',
border: '1px solid ' + envColors[d.env] + '40',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
<span style={{ width: '8px', height: '8px', borderRadius: '50%', background: statusColors[d.status], flexShrink: 0 }} />
<code style={{ color: '#fff', fontWeight: 'bold', fontSize: '13px' }}>{d.branch}</code>
<span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '4px', background: envColors[d.env] + '20', color: envColors[d.env] }}>{d.env}</span>
{d.pr && <span style={{ fontSize: '11px', color: '#8892b0' }}>PR #{d.pr}</span>}
<span style={{ fontSize: '11px', color: '#666', marginLeft: 'auto' }}>{d.age}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<code style={{ color: '#8892b0', fontSize: '12px' }}>{d.url}</code>
<code style={{ color: '#666', fontSize: '11px', marginLeft: 'auto' }}>{d.commit}</code>
</div>
</div>
))}
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Preview Deployments on Vercel are generated automatically:
2. CDN (Content Delivery Network) provides:
These are 2 of 11 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the correct order of environments in the deployment pipeline:
- Vertical ordering
Arrange the elements in the correct order: Define experiment β Split traffic β Track metrics
- Vertical ordering
Arrange the bundle size analysis steps in the correct order:
- Vertical ordering
Arrange the elements in the correct order: Audit dependencies β Set CSP headers β Enable HTTPS
- Vertical ordering
Arrange the elements in the correct order: Code commit to repository β CI/CD pipeline trigger
- Horizontal ordering
Arrange the ESLint configuration export in eslint.config.mjs (after the import: import nextVitals from 'eslint-config-next/core-web-vitals')
- Vertical ordering
Arrange the stages of production incident handling in the correct order
- Click in order
Arrange the Docker build command:
- Code editor
Write a production deployment checklist in Markdown with five sections (headings): security, performance, monitoring, backup and compliance. Add at least two checkbox items (- [ ] ...) to each section.
- Click in order
Arrange the Vercel deploy configuration:
Tasks after this lesson
- QuestionWhat Are Preview Deployments?
- Put in orderDeployment Pipeline: From Code to Production
- QuestionCDN (Content Delivery Network) provides:
- QuestionLoad balancing is used for:
- Put in orderSequence: Define experiment β Split traffic β ...
- QuestionBlue-green deployment means:
- QuestionA/B testing allows for:
- Put in orderBundle Analysis Process in Next.js
- QuestionA rollback strategy in production should:
- QuestionFeature flags allow for:
- Put in orderSequence: Audit dependencies β Set CSP headers β ...
- QuestionNesting Components in App Router
- QuestionMulti-stage Build in Dockerfile
- Put in orderSequence: Code commit to repository β CI/CD pipeline trigger
- QuestionNext.js Performance Optimization
- QuestionConfiguring Paths in tsconfig.json
- Put in orderESLint Configuration in Next.js
- Put in orderIncident Handling: Response Process
- Click in orderDocker Build Command
- Coding taskPractice: Create a Comprehensive Production Deployment Checklist
- Click in orderVercel Deploy Configuration