How to Deploy Nextjs App
How to Deploy Next.js App Deploying a Next.js application is a critical step in bringing your modern web application from development to production. Next.js, a powerful React framework developed by Vercel, offers server-side rendering (SSR), static site generation (SSG), API routes, and optimized performance out of the box. But building a high-performing app is only half the battle—deploying it co
How to Deploy Next.js App
Deploying a Next.js application is a critical step in bringing your modern web application from development to production. Next.js, a powerful React framework developed by Vercel, offers server-side rendering (SSR), static site generation (SSG), API routes, and optimized performance out of the box. But building a high-performing app is only half the battledeploying it correctly ensures scalability, security, and seamless user experiences across devices and geographies.
In this comprehensive guide, well walk you through every aspect of deploying a Next.js application. Whether youre a beginner deploying your first project or an experienced developer optimizing for enterprise-grade performance, this tutorial covers everything from basic setup to advanced configurations. Youll learn how to choose the right hosting platform, configure environment variables, optimize assets, and troubleshoot common deployment issuesall with real-world examples and industry best practices.
By the end of this guide, youll have a clear, actionable roadmap to deploy your Next.js app with confidenceno matter your infrastructure preferences or team size.
Step-by-Step Guide
Prerequisites
Before you begin deploying your Next.js application, ensure you have the following installed and configured:
- Node.js (version 18 or higher recommended)
- npm or yarn (package manager)
- A Next.js project (created via
create-next-app) - A code repository (GitHub, GitLab, or Bitbucket)
- A terminal or command-line interface
To verify your environment, open your terminal and run:
node -v
npm -v
If Node.js is not installed, download it from nodejs.org. For new Next.js projects, create one using:
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
This will spin up a local development server at http://localhost:3000. Confirm your app loads correctly before proceeding to deployment.
Build Your Next.js App
Next.js provides a built-in build command that compiles your application into optimized static files or server-side rendered bundles. Run the following command in your project root:
npm run build
This command generates a .next folder containing:
- Compiled JavaScript and CSS bundles
- Server-side rendering files (for SSR and ISR pages)
- Static HTML files (for SSG pages)
- API route handlers
During the build process, Next.js automatically:
- Minifies JavaScript and CSS
- Optimizes images using the
next/imagecomponent - Pre-renders pages based on your export configuration
- Generates a production-ready manifest for efficient caching
After the build completes successfully, youll see a message like: Compiled successfully and Automatic static optimization for pages that dont require server data.
Choose Your Deployment Method
Next.js supports multiple deployment strategies, each suited for different use cases:
- Static Export (SSG): Entire site is pre-rendered as static HTML. Ideal for blogs, marketing sites, documentation.
- Server-Side Rendering (SSR): Pages are rendered on-demand per request. Best for dynamic content like dashboards, e-commerce, or user-specific views.
- Incremental Static Regeneration (ISR): Combines SSG and SSRstatic pages are regenerated in the background after a set time. Perfect for content that updates frequently but doesnt require real-time rendering.
To export your app statically, update your next.config.js file:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true,
}
module.exports = nextConfig
Then run:
npm run build
npm run export
This generates a out folder containing fully static HTML, CSS, and JS files ready for deployment on any static host.
For SSR or ISR, you do not run export. Instead, you deploy the .next folder to a server or platform that supports Node.js runtime environments (e.g., Vercel, AWS, Render).
Deploying to Vercel (Recommended)
Vercel is the company behind Next.js and offers the most seamless deployment experience. It automatically detects Next.js projects and applies optimal configurations without manual setup.
- Push your code to a public or private Git repository (GitHub, GitLab, or Bitbucket).
- Go to vercel.com and sign up or log in.
- Click Add New Project ? Import Project.
- Select your repository from the list.
- Vercel auto-detects your project as Next.js and configures the build settings automatically.
- Click Deploy.
Vercel will:
- Run
npm run build - Automatically detect if youre using SSR, SSG, or ISR
- Deploy to a global CDN with edge caching
- Assign a random subdomain (e.g.,
your-app.vercel.app)
After deployment, you can:
- Preview changes in pull requests
- Set custom domains
- Configure environment variables
- Enable analytics and monitoring
For custom domains, go to your project settings ? Domains ? Add Domain. Follow DNS verification steps (typically adding a CNAME or A record with your domain registrar).
Deploying to Netlify
Netlify is another excellent option for static Next.js apps. While it doesnt natively support SSR out of the box, it works flawlessly with static exports.
- Ensure your
next.config.jsincludesoutput: 'export'. - Run
npm run buildfollowed bynpm run export. - Push the
outfolder to your Git repository. - Go to netlify.com and sign in.
- Click Deploy Site ? Drag & Drop your
outfolder or connect your Git repo. - Set the build command to
npm run build && npm run exportand publish directory toout. - Click Deploy site.
Netlify will host your static site globally and provide free SSL, custom domains, and form handling.
Deploying to AWS (Amazon S3 + CloudFront)
For full control and enterprise-grade scalability, deploy your static Next.js app to AWS.
- Export your app:
npm run build && npm run export - Install the AWS CLI:
npm install -g aws-cli - Create an S3 bucket via the AWS Console or CLI:
aws s3 mb s3://your-nextjs-bucket-name
- Sync the
outfolder to S3:
aws s3 sync out/ s3://your-nextjs-bucket-name --delete
- Enable static website hosting in the S3 bucket properties:
- Set Index Document to
index.html - Set Error Document to
index.html(required for client-side routing) - Create a CloudFront distribution:
- Set Origin Domain to your S3 buckets website endpoint
- Enable HTTP to HTTPS redirection
- Set TTL values for caching (e.g., 24 hours for HTML, 1 year for assets)
- Attach an SSL certificate via ACM (AWS Certificate Manager)
- Assign a custom domain via Route 53 or your registrar
This setup provides enterprise-grade performance, global CDN delivery, and full control over caching policies.
Deploying to Render
Render is a developer-friendly platform that supports both static and server-rendered Next.js apps.
- Push your code to a Git repository.
- Go to render.com and sign up.
- Click New + ? Web Service.
- Connect your repository.
- Set the following:
- Build Command:
npm run build - Start Command:
npm start - Environment: Node.js
- Region: Choose closest to your audience
Render automatically detects Next.js and runs the build. It serves your app via a Node.js server, supporting SSR and API routes. You can add custom domains, environment variables, and scale vertically/horizontally.
Deploying to Docker + Nginx (Self-Hosted)
If you prefer full infrastructure control, containerize your Next.js app using Docker and serve it via Nginx.
Create a Dockerfile in your project root:
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
RUN addgroup -g 1001 -S nodejs
RUN adduser -u 1001 -S nextjs --shell /bin/bash
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
Create a docker-compose.yml:
version: '3.8'
services:
nextjs:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
Build and run:
docker-compose build
docker-compose up
To serve with Nginx for better performance, create an nginx.conf:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://nextjs: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;
}
location /_next/static/ {
alias /app/.next/static;
expires 1y;
add_header Cache-Control "public, immutable";
}
location /public/ {
alias /app/public;
expires 1y;
add_header Cache-Control "public, immutable";
}
}
Then update your Dockerfile to include Nginx:
FROM node:18-alpine AS builder
... (previous builder steps)
FROM nginx:alpine
COPY --from=builder /app/.next/standalone /app/
COPY --from=builder /app/.next/static /app/.next/static
COPY --from=builder /app/public /app/public
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
This setup gives you full control over caching, SSL termination, and reverse proxyingideal for teams managing their own infrastructure.
Best Practices
Optimize Your Build for Performance
Next.js comes with many performance optimizations, but you can enhance them further:
- Use
next/imagefor all imagesthis enables automatic format conversion, lazy loading, and responsive sizing. - Preload critical resources using
<Link>withprefetch={true}for navigation-heavy pages. - Avoid importing large third-party libraries client-side. Use dynamic imports with
next/dynamic:
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('../components/HeavyComponent'), {
loading: () => <p>Loading...</p>,
ssr: false,
})
- Minimize bundle size by removing unused dependencies. Use tools like
source-map-explorerto analyze bundle contents. - Enable gzip or Brotli compression on your server or CDN.
Configure Environment Variables Securely
Never commit secrets like API keys or database credentials to your repository. Use environment variables:
- Store public variables in
.env.local(e.g.,NEXT_PUBLIC_API_URL) - Use
NEXT_PUBLIC_prefix for client-side access - Keep sensitive variables (e.g., database passwords) without the prefixtheyre only available on the server
Example .env.local:
NEXT_PUBLIC_API_URL=https://api.yourdomain.com
DATABASE_URL=secret://db
Access in code:
const apiUrl = process.env.NEXT_PUBLIC_API_URL // Safe on client
const dbUrl = process.env.DATABASE_URL // Only available on server
In deployment platforms like Vercel or Render, add environment variables via the dashboardnot in code.
Implement Proper Caching Strategies
Cache is one of the most powerful tools for reducing latency and server load:
- For static assets (JS, CSS, images): Set long cache headers (1 year) with content hashes.
- For HTML pages: Use short TTLs (15 minutes) if using ISR, or cache indefinitely for SSG.
- Use ETags and Last-Modified headers for conditional requests.
- Configure CDN caching rules based on file type and path.
Example Nginx cache headers:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
Enable HTTPS and Security Headers
Always serve your app over HTTPS. Most platforms (Vercel, Netlify, Render) provide free SSL certificates automatically.
Add security headers via middleware or server config:
// middleware.js (Next.js 13+)
import { NextResponse } from 'next/server'
export function middleware(request) {
const response = NextResponse.next()
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
response.headers.set('Content-Security-Policy', "default-src 'self'; script-src 'self' https://trusted.cdn.com")
return response
}
Monitor Performance and Errors
Use real user monitoring (RUM) to track performance in production:
- Integrate Vercel Analytics for free performance metrics
- Use Next.js Performance API to log page load times
- Set up error tracking with Sentry or LogRocket
- Enable logging for server-side errors in your deployment platform
Test Deployments Before Going Live
Always test your deployment in a staging environment:
- Use Vercels Preview Deployments for every pull request
- Test on multiple devices and network conditions
- Verify all routes work (especially dynamic routes and 404 pages)
- Run Lighthouse audits to check SEO, accessibility, and performance
Tools and Resources
Deployment Platforms
- Vercel Best for Next.js. Zero-config, global CDN, preview deployments, analytics.
- Netlify Excellent for static sites. Great form handling and serverless functions.
- Render Simple UI, supports Node.js apps with minimal setup.
- AWS (S3 + CloudFront) Full control, enterprise scalability, cost-efficient at scale.
- Google Cloud Run Container-based deployment with auto-scaling.
- Heroku Legacy option; no longer recommended for new Next.js projects due to pricing and performance.
- Railway Modern alternative to Heroku with excellent Next.js support.
Performance and SEO Tools
- Lighthouse Built into Chrome DevTools. Measures performance, accessibility, SEO.
- Web Vitals Core metrics: LCP, FID, CLS. Use
next/routerto track them. - Google Search Console Monitor indexing, crawl errors, and search performance.
- PageSpeed Insights Analyzes page speed on mobile and desktop.
- GTmetrix Detailed waterfall analysis and optimization suggestions.
Code Quality and Optimization
- ESLint Enforce code standards. Next.js includes a default config.
- Prettier Auto-format code consistently.
- BundlePhobia Check package size before installing.
- source-map-explorer Analyze bundle size and identify bloat.
- next-sitemap Auto-generate sitemaps for SEO.
CI/CD and Automation
- GitHub Actions Automate builds and deployments on push.
- GitLab CI Similar to GitHub Actions, with built-in Docker support.
- Bitbucket Pipelines Integrated CI/CD for Bitbucket users.
- Dependabot Automatically update dependencies.
Documentation and Learning
- Next.js Official Documentation The definitive source for all features.
- Next.js Learn Free interactive tutorials.
- Vercel Docs Deployment, environment variables, edge functions.
- Next.js Examples Repository Real-world code samples.
- Vercel YouTube Channel Tutorials and live demos.
Real Examples
Example 1: Personal Blog (Static Export)
Project: A Markdown-based blog using next-mdx-remote and next/image.
Deployment: Deployed to Netlify using static export.
Configuration:
// next.config.js
module.exports = {
output: 'export',
trailingSlash: true,
images: {
domains: ['res.cloudinary.com'],
},
}
Results:
- Page load time: 0.8s on mobile
- Lighthouse score: 98/100
- Hosting cost: $0 (free tier)
- SSL: Automatic
- Custom domain:
blog.johndoe.comconfigured via Netlify
Example 2: E-commerce Dashboard (SSR + API Routes)
Project: A product dashboard fetching real-time inventory data from a REST API.
Deployment: Deployed to Vercel with ISR on product pages.
Configuration:
// pages/products/[id].js
export async function getStaticProps({ params }) {
const res = await fetch(https://api.example.com/products/${params.id})
const product = await res.json()
return {
props: { product },
revalidate: 60, // Revalidate every 60 seconds
}
}
Results:
- Initial load: 1.2s
- Subsequent loads: 0.3s (from cache)
- Server errors: Reduced by 70% due to ISR fallback
- SEO: All product pages indexed by Google
- Cost: $0 (Vercel Pro plan with 100GB bandwidth)
Example 3: Enterprise SaaS Platform (Docker + Nginx on AWS)
Project: A multi-tenant analytics dashboard with user authentication and real-time data.
Deployment: Containerized with Docker, deployed on AWS ECS behind CloudFront.
Configuration:
- Custom domain:
app.company.com - SSL: ACM certificate
- Caching: 1 year for static assets, 5 minutes for HTML
- Logging: CloudWatch for server errors
- Monitoring: Prometheus + Grafana for performance metrics
Results:
- Uptime: 99.99%
- Latency: 400ms globally
- Scalability: Auto-scaled from 2 to 20 containers during peak traffic
- Cost: $120/month (including storage, bandwidth, and monitoring)
FAQs
Can I deploy a Next.js app for free?
Yes. Platforms like Vercel, Netlify, and Render offer generous free tiers. Vercel allows unlimited static sites and 100GB/month bandwidth. Netlify supports static exports with 100GB bandwidth. Render offers free Node.js instances with 512MB RAM. For simple blogs or portfolios, free hosting is more than sufficient.
Whats the difference between SSR and SSG in Next.js deployment?
SSG (Static Site Generation) renders pages at build time and serves pre-built HTML files. Its fast, secure, and ideal for content that doesnt change often. SSR (Server-Side Rendering) renders pages on every request using Node.js. Its ideal for dynamic content like user dashboards but requires a Node.js server. ISR (Incremental Static Regeneration) combines both: serves static pages but regenerates them in the background after a set time.
Do I need a server to deploy Next.js?
Only if youre using SSR or API routes. For static exports (SSG), you can deploy to any static host like GitHub Pages, Netlify, or AWS S3. If your app uses getServerSideProps or API routes, you need a Node.js runtime environment (e.g., Vercel, Render, AWS Lambda, or your own server).
How do I fix 404 Not Found after deploying?
This often happens with client-side routing. For static exports, ensure your next.config.js has trailingSlash: true and that youve configured your server to serve index.html for all routes (e.g., in S3 or Nginx). For SSR platforms, check that your build command is correct and that the server is running.
Why is my Next.js app slow after deployment?
Potential causes: Unoptimized images, large JavaScript bundles, missing caching headers, or incorrect SSR configuration. Use Lighthouse to identify bottlenecks. Ensure youre using next/image, dynamic imports, and proper caching. Also verify that your CDN is properly configured.
Can I use a custom domain with free hosting?
Yes. Vercel, Netlify, and Render allow custom domains on free plans. You just need to update your DNS records (CNAME or A record) to point to their servers. SSL certificates are issued automatically.
How do I handle environment variables in production?
Never hardcode them. Use platform-specific secret managers: Vercels Environment Variables, Netlifys Site Settings, Renders Environments, or AWS Secrets Manager. Always prefix client-side variables with NEXT_PUBLIC_.
Whats the best way to deploy a Next.js app with a database?
Use SSR or ISR with a backend API. Deploy your Next.js app to Vercel or Render, and connect to a managed database like Supabase, MongoDB Atlas, or PostgreSQL on AWS RDS. Never expose your database connection string on the client.
How do I deploy a Next.js app with authentication?
Use NextAuth.js or Clerk for authentication. Store session tokens in HTTP-only cookies. Deploy your app to a platform that supports server-side code (Vercel, Render, etc.). Avoid client-side session storage for sensitive data.
Can I deploy Next.js to GitHub Pages?
Yes, but only if you use static export (output: 'export'). GitHub Pages doesnt support Node.js servers, so SSR and API routes wont work. Use the out folder generated by npm run export and push it to the gh-pages branch or /docs folder.
Conclusion
Deploying a Next.js application is no longer a complex or intimidating task. With the right tools and practices, you can go from local development to a globally accessible, high-performance web application in minutes. Whether you choose the simplicity of Vercel, the flexibility of AWS, or the control of Docker, the key is understanding your apps needs: static content? dynamic data? real-time updates? user authentication?
By following the step-by-step guide in this tutorial, youve learned how to build, optimize, and deploy Next.js apps using industry-standard methods. Youve explored best practices for performance, security, and scalability. Youve seen real-world examples that demonstrate how different architectures serve different use cases. And youve been equipped with the tools and knowledge to troubleshoot common issues.
Remember: deployment isnt a one-time event. Its part of an ongoing cycle of optimization. Monitor your apps performance, update dependencies, test on real devices, and refine caching strategies. The goal isnt just to launchits to deliver a seamless, fast, and reliable experience to every user, everywhere.
Next.js makes modern web development accessible. Deploying it correctly ensures your work reaches its full potential. Now that you know how, its time to build something remarkableand ship it with confidence.