Next.js course ยท Module 8: Deployment and Production
Deployment on Vercel, Netlify, and other platforms
In this lesson8
After creating a Next.js application, a key stage is deploying it to the production environment. In this module, we will look at various hosting platforms that offer an optimized environment for Next.js applications, with a particular focus on Vercel - the platform created by the Next.js authors.
Deployment on Vercel
Vercel is a platform that offers the best native support for Next.js applications, as both technologies are developed by the same company. This ensures optimal support for all Next.js features, automated deployments, and a global CDN.
Project preparation
Before deploying, ensure that your project is ready for production:
- Checking environment variables - ensure that all environment variables are properly configured
- Initial optimization - run
next buildlocally to check for potential errors - Version control - ensure that your project is in a Git repository (GitHub, GitLab or Bitbucket)
Step by step: Deployment on Vercel
Create an account on Vercel
- Go to vercel.com and sign up, preferably using a GitHub/GitLab/Bitbucket account
Import the project
- After logging in, click "Add New..." > "Project"
- Select your repository from the list
Deployment configuration
- Vercel automatically detects that the project is a Next.js application
- You can customize the project name, deployment branch, and environment variables
- For standard Next.js projects, the default settings are usually sufficient
Deployment
- Click "Deploy"
- Vercel will build and deploy your application, optimizing it for production
Deployment verification
- After a successful deployment, you will receive a unique URL
- Check your application and ensure that everything works correctly
Custom domain configuration
To configure a custom domain for your project on Vercel:
- Go to the project panel
- Select the tab "Domains"
- Click "Add" and enter your domain name
- Follow the instructions to configure the DNS records:
- For root domains (e.g., example.com): Create an A record pointing to Vercel's IP
- For subdomains (e.g., www.example.com): Create a CNAME record pointing to the Vercel domain
Automatic deployments and previews
One of Vercel's greatest strengths is the automatic deployment system:
Automatic production deployments
- Each push to the main branch (e.g.,
main) triggers an automatic deployment
- Each push to the main branch (e.g.,
Preview Deployments
- Each pull request automatically creates a unique preview environment
- This allows testing changes before merging with the main branch
// Example of Next.js configuration optimized for Vercel
// next.config.js
module.exports = {
// Image optimization - automatically handled by Vercel Image Optimization
images: {
domains: ['example.com', 'images.unsplash.com'],
},
// Integrated Vercel analytics
vercelAnalytics: {
enabled: true,
},
// Internationalization settings
i18n: {
locales: ['pl', 'en', 'de'],
defaultLocale: 'pl',
},
};Advanced Vercel features
Vercel offers a range of advanced features worth using:
- Edge Functions - running code close to the user on Vercel's global edge network
- Serverless Functions - automatic conversion of API Routes into serverless functions
- Edge Middleware - running middleware at the network edge
- Edge Config - storing configuration at the edge with ultra-fast reads
- Analytics - built-in analytics tools
- Speed Insights - monitoring Core Web Vitals
Deployment on Netlify
Netlify is another popular platform that offers excellent support for Next.js applications, especially after the introduction of the Netlify Next.js Runtime feature.
Project preparation for Netlify
- Create the netlify.toml configuration file in the project's main directory:
# netlify.toml
[build]
command = "npm run build"
publish = ".next"
[[plugins]]
package = "@netlify/plugin-nextjs"- Install the Next.js plugin for Netlify:
npm install -D @netlify/plugin-nextjs
# or
yarn add -D @netlify/plugin-nextjsStep by step: Deployment on Netlify
Create an account on Netlify
- Go to netlify.com and sign up
Import the project
- Click "Add new site" > "Import an existing project"
- Connect to your Git provider and select your repository
Deployment configuration
- Netlify should automatically detect the Next.js project settings
- Make sure the build command is
npm run buildoryarn build - The publish directory should be set to
.next
Configure environment variables
- Go to "Site settings" > "Build & deploy" > "Environment"
- Add all needed environment variables
Deployment
- Click "Deploy site"
Netlify-specific features
Netlify offers a range of unique features that can be useful in Next.js projects:
- Netlify Functions - the equivalent of API Routes
- Netlify Edge Functions - similar to Next.js Middleware, but running at the edge
- Netlify Forms - built-in form handling without the need to create API endpoints
- Netlify Identity - user authentication service
// Example of using Netlify Functions with Next.js
// /netlify/functions/hello-world.js
exports.handler = async function(event, context) {
return {
statusCode: 200,
body: JSON.stringify({ message: "Hello World" }),
headers: {
'Content-Type': 'application/json'
}
};
};
// Access from the Next.js application
// pages/api-example.js
import { useState, useEffect } from 'react';
export default function ApiExample() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/.netlify/functions/hello-world')
.then(res => res.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>API Example</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}Deployment on AWS Amplify
AWS Amplify is a service from Amazon that also offers good support for Next.js applications, especially if you already use the AWS ecosystem.
Project preparation for AWS Amplify
- Create the amplify.yml file in the project's main directory:
# amplify.yml
version: 1
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- npm run build
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*Step by step: Deployment on AWS Amplify
Create an AWS account or log in to an existing one
Go to the AWS Amplify console
- Select "Host web app"
Connect the repository
- Select a repository provider (GitHub, GitLab, BitBucket, or AWS CodeCommit repository)
- Log in and select your repository
Build settings configuration
- Amplify should automatically detect the Next.js framework
- You can adjust or confirm the build settings
Configure environment variables
- Add all needed environment variables in the "Environment variables" section
Deployment
- Click "Save and deploy"
Integration with AWS services
One of the main strengths of AWS Amplify is easy integration with other AWS services:
// Example: Integration with AWS Lambda and DynamoDB
// pages/api/users.js
import { DynamoDB } from 'aws-sdk';
const dynamoDB = new DynamoDB.DocumentClient();
export default async function handler(req, res) {
if (req.method === 'GET') {
const params = {
TableName: process.env.DYNAMODB_TABLE_NAME,
};
try {
const data = await dynamoDB.scan(params).promise();
res.status(200).json(data.Items);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch users' });
}
}
}Deployment on Digital Ocean App Platform
Digital Ocean App Platform is another hosting option that offers good support for Next.js applications.
Step by step: Deploying on Digital Ocean
Create a Digital Ocean account or log in to an existing one
Go to Digital Ocean App Platform
- Click "Create App"
Select the code source
- Connect your GitHub, GitLab repository, or choose another source
Application configuration
- Select the branch to deploy
- Select the application type as "Web Service"
- In the build settings, select "Next.js" as the example application
Adjust the settings
- Set the build command to
npm run buildoryarn build - Set the run command to
npm startoryarn start
- Set the build command to
Finalization
- Select a pricing plan
- Click "Launch App"
Other hosting options for Next.js
GitHub Pages with GitHub Actions
For statically generated Next.js applications, you can use GitHub Pages with GitHub Actions:
- Create a GitHub Actions workflow file:
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Build and export
run: npm run build && npm run export
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./out- Adjust next.config.js:
// next.config.js
module.exports = {
output: 'export',
basePath: '/repository-name', // If the page is not on the main domain
images: {
unoptimized: true, // For GitHub Pages
},
};- Add a script to package.json:
{
"scripts": {
"export": "next export"
}
}Firebase Hosting
Firebase Hosting is another option, especially if you use other Firebase services:
- Install the Firebase CLI:
npm install -g firebase-tools- Initialize the Firebase project:
firebase login
firebase init hosting- Configure the firebase.json file:
{
"hosting": {
"public": "out",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}- Build and deploy the application:
npm run build
npm run export
firebase deploySelf-hosting on your own server
If you prefer to host the application on your own server:
Node.js server
- Prepare the start script in package.json:
{
"scripts": {
"start": "next start -p $PORT"
}
}- Use PM2 to manage the process:
npm install -g pm2
pm2 start npm --name "next-app" -- start- Configuring Nginx as a reverse proxy:
server {
listen 80;
server_name yourpage.com www.yourpage.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}Containerization with Docker
- Create a Dockerfile:
# Dockerfile
FROM node:24-alpine AS base
# Dependency installation stage
FROM base AS deps
WORKDIR /app
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN if [ -f yarn.lock ]; then yarn --frozen-lockfile; elif [ -f package-lock.json ]; then npm ci; elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i; else echo "No lockfile present" && exit 1; fi
# Build stage
FROM base AS builder
WORKDIR /app
COPY /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Production stage
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY /app/public ./public
COPY /app/.next/standalone ./
COPY /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]- Configure next.config.js:
// next.config.js
module.exports = {
output: 'standalone',
};- Build and run the container:
docker build -t next-app .
docker run -p 3000:3000 next-appBest practices
Environment variables
Manage environment variables according to Next.js best practices:
Distinguish between client and server variables:
- Variables that should be available in the browser should have the prefix
NEXT_PUBLIC_ - The remaining variables are available only in server code
- Variables that should be available in the browser should have the prefix
Environment files:
.env.local- variables for the local environment, not committed to the repository.env.development- variables for the development environment.env.production- variables for the production environment.env.test- variables for the test environment
Deployment optimization
Cache and CDN:
- Configure appropriate cache headers for static resources
- Use a CDN to speed up the delivery of static resources
Compression:
- Enable Gzip or Brotli compression on the server
Core Web Vitals:
- Monitor Web Vitals metrics after deployment
- Use tools like Lighthouse or PageSpeed Insights
// next.config.js - production optimization
module.exports = {
// Compression
compress: true,
// Image optimization
images: {
domains: ['images.example.com'],
formats: ['image/avif', 'image/webp'],
},
// Static generator - maximum performance for ISR/SSG pages
staticPageGenerationTimeout: 120,
// Production optimization
productionBrowserSourceMaps: false, // Disable source maps in production
// webpack configuration
webpack: (config, { dev, isServer }) => {
// webpack optimizations...
return config;
},
};Deployment automation
Consider implementing Continuous Deployment (CD) to automate the deployment process:
# GitHub Actions - deploy.yml
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build project
run: npm run build
- name: Deploy to production
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.ORG_ID }}
vercel-project-id: ${{ secrets.PROJECT_ID }}
vercel-args: '--prod'Summary
Next.js application deployment can be done in many ways, depending on the project's needs and the team's preferences:
- Vercel - the best native support, optimized for Next.js
- Netlify - strong competitor with good Next.js support and additional features
- AWS Amplify - good choice for users of the AWS ecosystem
- Digital Ocean App Platform - simple PaaS platform with good Next.js support
- Self-hosting - ability to have full control over the infrastructure
The choice of hosting platform should be tailored to:
- The specifics of the project and its technical requirements
- Budget and expected costs
- The team's experience with the given platform
- Needs related to scalability and performance
- Additional services and integrations that may be needed
Regardless of the chosen platform, it's worth following best practices for managing environments, environment variables, security, and deployment automation.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Demo: Deploying to Vercel, Netlify and other platforms
interface Platform {
id: string;
name: string;
icon: string;
color: string;
features: string[];
pricing: string;
deployCommand: string;
envSetup: string;
pros: string[];
cons: string[];
}
const platforms: Platform[] = [
{
id: 'vercel', name: 'Vercel', icon: 'V', color: '#000',
features: ['Edge Functions', 'ISR', 'Analytics', 'Preview Deploys', 'Serverless'],
pricing: 'Free tier / $20/mo Pro',
deployCommand: 'vercel deploy --prod',
envSetup: 'vercel env add DATABASE_URL\nvercel env add NEXTAUTH_SECRET',
pros: ['Native Next.js support', 'Automatic CI/CD', 'Edge Network', 'Preview on every PR'],
cons: ['Vendor lock-in', 'Costs at scale', 'Serverless limits'],
},
{
id: 'netlify', name: 'Netlify', icon: 'N', color: '#00ad9f',
features: ['Edge Functions', 'Forms', 'Identity', 'Split Testing', 'Plugins'],
pricing: 'Free tier / $19/mo Pro',
deployCommand: 'netlify deploy --prod',
envSetup: 'netlify env:set DATABASE_URL "value"\nnetlify env:set NEXTAUTH_SECRET "value"',
pros: ['Easy configuration', 'Built-in forms', 'Split testing', 'Plugin ecosystem'],
cons: ['Slower SSR', 'Limited Next.js features', 'Build limits'],
},
{
id: 'docker', name: 'Docker / VPS', icon: 'D', color: '#2496ed',
features: ['Full control', 'Custom runtime', 'Scaling', 'No limits'],
pricing: 'VPS from $5/mo',
deployCommand: 'docker build -t myapp .\ndocker run -p 3000:3000 myapp',
envSetup: '# .env.production\nDATABASE_URL=postgresql://...\nNEXTAUTH_SECRET=...',
pros: ['Full control', 'No vendor lock-in', 'Lower costs at scale', 'Custom configuration'],
cons: ['More work', 'DevOps knowledge required', 'No auto-scaling', 'Self-managed monitoring'],
},
{
id: 'aws', name: 'AWS Amplify', icon: 'A', color: '#ff9900',
features: ['CloudFront CDN', 'Lambda@Edge', 'DynamoDB', 'S3', 'CI/CD'],
pricing: 'Pay-as-you-go',
deployCommand: 'amplify push\namplify publish',
envSetup: 'amplify add env staging\n# Configure in Amplify Console',
pros: ['AWS ecosystem', 'Scaling', 'Multiple regions', 'Integration with other AWS services'],
cons: ['Complexity', 'Learning curve', 'Costs hard to predict'],
},
];
type DeployStep = 'idle' | 'building' | 'testing' | 'deploying' | 'done';
function DeploymentDemo() {
const [selectedPlatform, setSelectedPlatform] = useState<Platform>(platforms[0]);
const [deployStep, setDeployStep] = useState<DeployStep>('idle');
const [showComparison, setShowComparison] = useState(false);
const simulateDeploy = async () => {
setDeployStep('building');
await new Promise(r => setTimeout(r, 1500));
setDeployStep('testing');
await new Promise(r => setTimeout(r, 1000));
setDeployStep('deploying');
await new Promise(r => setTimeout(r, 2000));
setDeployStep('done');
};
const stepLabels: Record<DeployStep, string> = {
idle: 'Ready to deploy',
building: 'Building application...',
testing: 'Running tests...',
deploying: 'Deploying to ' + selectedPlatform.name + '...',
done: 'Deployed successfully!',
};
const stepColors: Record<DeployStep, string> = {
idle: '#8892b0', building: '#f59e0b', testing: '#3b82f6', deploying: '#8b5cf6', done: '#10b981',
};
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
<h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Deployment Platforms</h1>
<p style={{ color: '#8892b0', marginBottom: '24px' }}>Deploying a Next.js application to various platforms</p>
<div style={{ display: 'flex', gap: '12px', marginBottom: '24px', flexWrap: 'wrap' }}>
{platforms.map(p => (
<button key={p.id} onClick={() => { setSelectedPlatform(p); setDeployStep('idle'); }} style={{
padding: '14px 20px', borderRadius: '12px', cursor: 'pointer', border: '2px solid',
borderColor: selectedPlatform.id === p.id ? '#64ffda' : '#333',
background: selectedPlatform.id === p.id ? '#1a2a3e' : '#1a1a2e', color: '#fff',
}}>
<div style={{ fontSize: '20px', fontWeight: 'bold', color: '#64ffda' }}>{p.icon}</div>
<div style={{ fontSize: '14px' }}>{p.name}</div>
</button>
))}
<button onClick={() => setShowComparison(!showComparison)} style={{ padding: '14px 20px', borderRadius: '12px', background: showComparison ? '#7c3aed' : '#1a1a2e', color: '#fff', border: '1px solid #333', cursor: 'pointer', marginLeft: 'auto' }}>
Compare
</button>
</div>
{!showComparison ? (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333', marginBottom: '16px' }}>
<h3 style={{ color: '#64ffda', marginTop: 0 }}>{selectedPlatform.name}</h3>
<p style={{ color: '#8892b0', fontSize: '13px' }}>Pricing: {selectedPlatform.pricing}</p>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', marginBottom: '12px' }}>
{selectedPlatform.features.map(f => (
<span key={f} style={{ fontSize: '11px', padding: '3px 8px', borderRadius: '4px', background: '#333', color: '#8892b0' }}>{f}</span>
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
<div>
<strong style={{ color: '#10b981', fontSize: '13px' }}>Advantages:</strong>
<ul style={{ fontSize: '12px', paddingLeft: '16px', color: '#8892b0', margin: '4px 0' }}>
{selectedPlatform.pros.map((p, i) => <li key={i}>{p}</li>)}
</ul>
</div>
<div>
<strong style={{ color: '#ef4444', fontSize: '13px' }}>Cons:</strong>
<ul style={{ fontSize: '12px', paddingLeft: '16px', color: '#8892b0', margin: '4px 0' }}>
{selectedPlatform.cons.map((c, i) => <li key={i}>{c}</li>)}
</ul>
</div>
</div>
</div>
<div style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
<strong style={{ color: '#f59e0b', fontSize: '13px' }}>Deploy command:</strong>
<pre style={{ fontSize: '12px', color: '#64ffda', margin: '8px 0 0', whiteSpace: 'pre-wrap' }}>{selectedPlatform.deployCommand}</pre>
</div>
</div>
<div>
<div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
<h3 style={{ color: '#64ffda', marginTop: 0, fontSize: '16px' }}>Deploy simulation</h3>
<div style={{ marginBottom: '16px', padding: '12px', borderRadius: '8px', background: stepColors[deployStep] + '20', border: '1px solid ' + stepColors[deployStep] }}>
<span style={{ color: stepColors[deployStep] }}>{stepLabels[deployStep]}</span>
</div>
<button onClick={simulateDeploy} disabled={deployStep !== 'idle' && deployStep !== 'done'} style={{ padding: '10px 20px', borderRadius: '8px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
Deploy
</button>
</div>
</div>
</div>
) : (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '13px' }}>
<thead>
<tr>{['', ...platforms.map(p => p.name)].map((h, i) => <th key={i} style={{ padding: '10px', textAlign: 'left', borderBottom: '1px solid #333', color: '#64ffda' }}>{h}</th>)}</tr>
</thead>
<tbody>
{['pricing', 'features'].map(field => (
<tr key={field}>
<td style={{ padding: '10px', borderBottom: '1px solid #222', color: '#8892b0' }}>{field}</td>
{platforms.map(p => (
<td key={p.id} style={{ padding: '10px', borderBottom: '1px solid #222', color: '#e0e0e0' }}>
{field === 'pricing' ? p.pricing : p.features.slice(0, 3).join(', ')}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
export default DeploymentDemo;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. Vercel is:
2. Netlify offers:
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Click in order
Arrange the syntax of the FROM instruction in a Dockerfile
- Code editor
Create a Dockerfile for a Next.js app with a multi-stage build: install the dependencies and build the app in a stage based on a node image, copy only the build output into the final stage (COPY --from), set NODE_ENV=production, run the app as a non-root user (USER) and start it with CMD.
- Horizontal ordering
Arrange the elements in the correct order for the build and production start command:
- Click in order
Arrange the syntax for configuring the bundle analyzer in Next.js
- Click in order
Click in the correct order to arrange the Vercel CLI deploy command:
Tasks after this lesson
- QuestionVercel is:
- QuestionNetlify offers:
- QuestionDocker in the context of Next.js is used for:
- Click in orderSequence: FROM โ node:18-alpine โ AS
- Coding taskPractice: Create a Dockerfile for a Next.js Application
- Put in orderSequence: Build and Production Start in Next.js
- Click in orderConfiguring next.config.js with Analyzer
- Click in orderVercel Deploy via npx
- QuestionServerless functions in Next.js work:
- QuestionEdge functions are optimal for: