Next.js course ยท Module 8: Deployment and Production
Project: Full deployment of a Next.js application to production
In this lesson10
Welcome to the final project of the deployment module! In Quantum Metropolis 2150, every system goes through a rigorous process of preparing for production - from building and optimization, through SEO configuration, all the way to monitoring and testing. In this project, we will combine all the skills gained throughout the module to go through the full deployment cycle of a Next.js application.
Project goal
Your task is to prepare a complete Next.js application for a production deployment. The project covers all the key aspects we discussed in this module:
- Building and optimization (from the build and analyze lesson)
- SEO and metadata (from the dynamic metadata lesson)
- Open Graph and social sharing (from the OG lesson)
- Sitemap and robots.txt (from the sitemaps lesson)
- Web Analytics (from the analytics lesson)
- Deploying to hosting platforms (from the Vercel/Netlify lesson)
- Environment variables and production configuration (from the env vars lesson)
- CI/CD (from the automation lesson)
- Monitoring (from the monitoring lesson)
- PWA and Service Workers (from the PWA lesson)
- Preview Deployments and staging (from the environments lesson)
Step 1: Configuring next.config.js
Start with a full Next.js configuration with production optimizations:
// next.config.ts
import type { NextConfig } from 'next';
import withBundleAnalyzer from '@next/bundle-analyzer';
const config: NextConfig = {
// Image optimization
images: {
formats: ['image/avif', 'image/webp'],
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.quantum-city.com',
pathname: '/images/**',
},
],
minimumCacheTTL: 60 * 60 * 24 * 30, // 30 days cache
},
// Compression
compress: true,
// Bundle optimization
experimental: {
optimizePackageImports: ['lucide-react', '@quantum/ui'],
},
// Security headers
async headers() {
return [
{
source: '/:path*',
headers: [
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-XSS-Protection', value: '1; mode=block' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()',
},
],
},
];
},
// Redirects
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true, // 301 redirect
},
];
},
};
const withAnalyzer = withBundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
});
export default withAnalyzer(config);Step 2: SEO and dynamic metadata
Configure metadata for each page using the Metadata API:
// app/layout.tsx
import type { Metadata } from 'next';
export const metadata: Metadata = {
metadataBase: new URL('https://quantum-city.com'),
title: {
default: 'Quantum City - Metropolis Portal',
template: '%s | Quantum City',
},
description: 'The official portal of Quantum Metropolis 2150',
openGraph: {
type: 'website',
locale: 'pl_PL',
url: 'https://quantum-city.com',
siteName: 'Quantum City',
images: [
{
url: '/og-default.png',
width: 1200,
height: 630,
alt: 'Quantum City',
},
],
},
twitter: {
card: 'summary_large_image',
creator: '@QuantumCity',
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
};
// app/products/[id]/page.tsx - dynamic metadata
import type { Metadata } from 'next';
type Props = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const product = await fetch(
`https://api.quantum-city.com/products/${(await params).id}`
).then(r => r.json());
return {
title: product.name,
description: product.description,
openGraph: {
title: product.name,
description: product.description,
images: [{ url: product.imageUrl, width: 800, height: 600 }],
},
};
}Step 3: Sitemap and robots.txt
Generate a dynamic sitemap:
// app/sitemap.ts
import { MetadataRoute } from 'next';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const baseUrl = 'https://quantum-city.com';
// Fetch dynamic pages
const products = await fetch('https://api.quantum-city.com/products')
.then(r => r.json());
const posts = await fetch('https://api.quantum-city.com/blog')
.then(r => r.json());
const productPages = products.map((product: any) => ({
url: `${baseUrl}/products/${product.slug}`,
lastModified: new Date(product.updatedAt),
changeFrequency: 'weekly' as const,
priority: 0.8,
}));
const blogPages = posts.map((post: any) => ({
url: `${baseUrl}/blog/${post.slug}`,
lastModified: new Date(post.updatedAt),
changeFrequency: 'monthly' as const,
priority: 0.6,
}));
return [
{ url: baseUrl, lastModified: new Date(), changeFrequency: 'daily', priority: 1 },
{ url: `${baseUrl}/products`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.9 },
...productPages,
...blogPages,
];
}
// app/robots.ts
import { MetadataRoute } from 'next';
export default function robots(): MetadataRoute.Robots {
return {
rules: [
{
userAgent: '*',
allow: '/',
disallow: ['/admin/', '/api/', '/dashboard/'],
},
],
sitemap: 'https://quantum-city.com/sitemap.xml',
};
}Step 4: Web Analytics and monitoring
Integrate an analytics and error-monitoring system:
// lib/analytics.ts
export function trackEvent(name: string, properties?: Record<string, any>) {
if (typeof window === 'undefined') return;
// Custom analytics
fetch('/api/analytics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event: name, properties, timestamp: Date.now() }),
}).catch(console.error);
}
// lib/monitoring.ts
export function initErrorMonitoring() {
if (typeof window === 'undefined') return;
window.addEventListener('error', (event) => {
fetch('/api/errors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: event.message,
filename: event.filename,
lineno: event.lineno,
stack: event.error?.stack,
url: window.location.href,
timestamp: new Date().toISOString(),
}),
}).catch(console.error);
});
}Step 5: CI/CD Pipeline
Configure an automatic deployment pipeline:
# .github/workflows/deploy.yml
name: Deploy to Production
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm run type-check
- run: npm test
e2e:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm run build
- name: Cypress E2E Tests
uses: cypress-io/github-action@v6
with:
start: npm start
wait-on: 'http://localhost:3000'
browser: chrome
deploy:
needs: [test, e2e]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Vercel
run: npx vercel --prod --token=VERCEL_TOKENStep 6: PWA and offline support
Add Progressive Web App functionality:
// app/manifest.ts
import { MetadataRoute } from 'next';
export default function manifest(): MetadataRoute.Manifest {
return {
name: 'Quantum City Portal',
short_name: 'QC Portal',
description: 'The official portal of Quantum Metropolis 2150',
start_url: '/',
display: 'standalone',
background_color: '#0a0a1a',
theme_color: '#64ffda',
icons: [
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
],
};
}Step 7: E2E tests with Cypress
Write tests covering critical user paths:
// cypress/e2e/production-readiness.cy.ts
describe('Production Readiness Check', () => {
it('home page loads in under 3 seconds', () => {
cy.visit('/', { timeout: 3000 });
cy.get('h1').should('be.visible');
});
it('SEO meta tags are correct', () => {
cy.visit('/');
cy.get('head title').should('contain', 'Quantum City');
cy.get('meta[name="description"]').should('have.attr', 'content');
});
it('security headers are set', () => {
cy.request('/').then((response) => {
expect(response.headers).to.have.property('x-frame-options');
expect(response.headers).to.have.property('x-content-type-options');
});
});
});Step 8: Pre-deployment checklist
Before every production deployment, go through these checkpoints:
Performance
- The
next buildcommand finishes without errors - JS bundle size below 200KB (gzipped)
- LCP below 2.5 seconds, CLS below 0.1
- Images optimized (WebP/AVIF)
SEO
- Every page has a unique title and description
- Open Graph tags are correct
- Sitemap.xml and robots.txt are generated
Security
- Security headers (HSTS, CSP, X-Frame-Options)
- CSRF protection and rate limiting
- Input validation with Zod
Monitoring
- Error tracking configured
- Web Vitals monitored
- Alerts for critical errors
CI/CD
- Unit and E2E tests pass
- Linting and type-checking with no errors
- Automatic deploy after merge to main
Summary
In this project, you combined all the key skills for deploying a Next.js application to production. Each of these elements is essential for creating a professional, performant, and secure web application.
Remember - in Quantum Metropolis 2150 there is no room for half-measures. Every system must be fully optimized, secured, and monitored. Now you are ready to deploy your Next.js applications at the highest level!
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Project: Full production deployment of Next.js application
interface ChecklistItem {
id: string;
label: string;
category: string;
done: boolean;
}
const initialChecklist: ChecklistItem[] = [
{ id: '1', label: 'next.config.js - image optimization and compression', category: 'Build', done: false },
{ id: '2', label: 'Security headers (HSTS, CSP, X-Frame-Options)', category: 'Build', done: false },
{ id: '3', label: 'Metadata API - title, description, OG tags', category: 'SEO', done: false },
{ id: '4', label: 'Dynamic metadata for subpages', category: 'SEO', done: false },
{ id: '5', label: 'Sitemap.xml generated', category: 'SEO', done: false },
{ id: '6', label: 'Robots.txt configured', category: 'SEO', done: false },
{ id: '7', label: 'Web Analytics integrated', category: 'Monitoring', done: false },
{ id: '8', label: 'Error monitoring configured', category: 'Monitoring', done: false },
{ id: '9', label: 'Web Vitals monitored', category: 'Monitoring', done: false },
{ id: '10', label: 'CI/CD pipeline configured', category: 'Deploy', done: false },
{ id: '11', label: 'E2E tests (Cypress) passing', category: 'Deploy', done: false },
{ id: '12', label: 'PWA manifest and Service Worker', category: 'Deploy', done: false },
{ id: '13', label: 'Deployment on Vercel/Netlify', category: 'Deploy', done: false },
];
const categoryColors: Record<string, string> = {
Build: '#64ffda',
SEO: '#bb86fc',
Monitoring: '#ff9800',
Deploy: '#4caf50',
};
export default function DeploymentChecklist() {
const [items, setItems] = useState(initialChecklist);
const toggle = (id: string) => {
setItems(prev => prev.map(item => item.id === id ? { ...item, done: !item.done } : item));
};
const total = items.length;
const done = items.filter(i => i.done).length;
const pct = Math.round((done / total) * 100);
const categories = Array.from(new Set(items.map(i => i.category)));
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#fff', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda', fontSize: 20, marginBottom: 4 }}>Production Deployment Checklist</h1>
<p style={{ color: '#888', fontSize: 13, marginBottom: 16 }}>Quantum City - Next.js Deployment</p>
<div style={{ background: '#151530', borderRadius: 8, padding: 16, marginBottom: 20 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 13 }}>
<span style={{ color: '#aaa' }}>Progress: {done}/{total}</span>
<span style={{ color: pct === 100 ? '#4caf50' : '#64ffda' }}>{pct}%</span>
</div>
<div style={{ height: 10, background: '#1a2744', borderRadius: 5, overflow: 'hidden' }}>
<div style={{ width: pct + '%', height: '100%', background: pct === 100 ? '#4caf50' : '#64ffda', borderRadius: 5, transition: 'width 0.4s ease' }} />
</div>
{pct === 100 && <p style={{ color: '#4caf50', marginTop: 8, fontSize: 14 }}>Application ready for deployment!</p>}
</div>
{categories.map(cat => (
<div key={cat} style={{ marginBottom: 16 }}>
<h3 style={{ color: categoryColors[cat] || '#fff', fontSize: 14, marginBottom: 8 }}>{cat}</h3>
{items.filter(i => i.category === cat).map(item => (
<div key={item.id} onClick={() => toggle(item.id)} style={{
display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', marginBottom: 4,
background: item.done ? '#1a3a2a' : '#151530', borderRadius: 6, cursor: 'pointer',
border: '1px solid ' + (item.done ? '#4caf5044' : '#334'),
}}>
<span style={{ fontSize: 16 }}>{item.done ? '\u2705' : '\u2B1C'}</span>
<span style={{ color: item.done ? '#888' : '#ccc', fontSize: 13, textDecoration: item.done ? 'line-through' : 'none' }}>
{item.label}
</span>
</div>
))}
</div>
))}
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?