How to Deploy Nextjs on Vercel
How to Deploy Next.js on Vercel Next.js is one of the most popular React frameworks for building modern, high-performance web applications. Its server-side rendering (SSR), static site generation (SSG), and API route capabilities make it ideal for everything from marketing sites to complex web apps. Vercel, the company behind Next.js, offers a seamless, optimized deployment platform that integrate
How to Deploy Next.js on Vercel
Next.js is one of the most popular React frameworks for building modern, high-performance web applications. Its server-side rendering (SSR), static site generation (SSG), and API route capabilities make it ideal for everything from marketing sites to complex web apps. Vercel, the company behind Next.js, offers a seamless, optimized deployment platform that integrates natively with the framework—delivering instant global CDN caching, automatic SSL, edge functions, and zero-configuration deployments.
Deploying a Next.js application on Vercel is not just convenient—it’s the most efficient way to ship production-ready apps with minimal overhead. Whether you’re a solo developer, part of a startup, or working within a large engineering team, Vercel streamlines the entire deployment lifecycle: from pushing code to seeing your site live in seconds. This tutorial provides a comprehensive, step-by-step guide to deploying Next.js on Vercel, covering best practices, real-world examples, essential tools, and answers to common questions.
Step-by-Step Guide
Prerequisites
Before you begin, ensure you have the following installed and configured:
- Node.js (version 18 or higher recommended)
- npm or yarn (package manager)
- Git (for version control and connecting to Vercel)
- A Vercel account (free tier available)
If you don’t have a Next.js project yet, you can create one using the official create-next-app CLI:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
Follow the prompts to configure your project (e.g., TypeScript, ESLint, Tailwind CSS, etc.). Once complete, test your app locally:
npm run dev
Open http://localhost:3000 in your browser to verify the app is running.
Step 1: Initialize a Git Repository
Vercel connects to your code via Git. Even if you’re working locally, initializing a Git repository is required for deployment.
git init
git add .
git commit -m "Initial commit"
While Vercel can deploy from local directories, it’s strongly recommended to push your code to a remote repository (GitHub, GitLab, or Bitbucket). This ensures version control, collaboration, and automatic deployments on future pushes.
Create a new repository on GitHub (or your preferred platform), then link it:
git remote add origin https://github.com/your-username/my-nextjs-app.git
git branch -M main
git push -u origin main
Step 2: Sign Up or Log In to Vercel
Visit https://vercel.com and sign up using your GitHub, GitLab, or Google account. Vercel will automatically import your repositories.
After logging in, you’ll land on the Vercel dashboard. Click the New Project button.
Step 3: Import Your Next.js Project
Vercel will scan your connected Git accounts. Select the repository you just pushed (e.g., my-nextjs-app).
On the next screen, Vercel automatically detects that this is a Next.js project. You’ll see the following defaults:
- Framework Preset: Next.js
- Build Command:
npm run build(oryarn build) - Output Directory:
.next
These are correct for standard Next.js apps. Do not change them unless you’re using a custom configuration.
Click Deploy. Vercel will begin building your project.
Step 4: Monitor the Build Process
Once you click Deploy, Vercel clones your repository, installs dependencies, runs the build command, and generates static files or server-side rendered pages.
You’ll see a live log in your browser showing:
- Cloning the repository
- Installing packages
- Running
next build - Optimizing images (if using
next/image) - Generating static pages
- Uploading to the edge network
This process typically takes 30–90 seconds for small to medium apps. Larger apps with many pages or complex API routes may take longer.
Step 5: Access Your Live Deployment
Once the build completes successfully, Vercel provides you with a unique URL in the format:
https://my-nextjs-app-xyz123.vercel.app
Click the link to view your live site. You’ll notice:
- Instant loading times due to global CDN caching
- Automatic HTTPS encryption
- Optimized asset delivery
Every time you push new code to your main branch (e.g., main or master), Vercel automatically triggers a new build and deployment. This is called Git Integration and is one of Vercel’s most powerful features.
Step 6: Deploying from a Branch (Preview Deployments)
Vercel automatically creates a unique preview URL for every pull request or branch you push. For example:
https://feature-login-abc789.vercel.app
This allows you and your team to test changes in isolation before merging into production. Preview deployments are especially useful for:
- Reviewing UI changes
- Testing API integrations
- Validating SEO metadata
To test this, create a new branch:
git checkout -b feature/header-update
Make changes to your header component
git add .
git commit -m "Update header design"
git push origin feature/header-update
Go back to your Vercel dashboard. You’ll see a new Preview Deployment created automatically. Click it to view your changes live.
Step 7: Configure Custom Domain (Optional)
By default, Vercel assigns a .vercel.app domain. To use your own domain (e.g., mywebsite.com), follow these steps:
- In your Vercel dashboard, go to the project settings.
- Click Domains under the Settings tab.
- Click Add and enter your domain (e.g.,
mywebsite.com). - Vercel will provide you with DNS records (CNAME or A records).
- Log in to your domain registrar (e.g., Namecheap, Google Domains, Cloudflare).
- Update the DNS settings with the records provided by Vercel.
- Wait up to 48 hours for DNS propagation (usually much faster).
- Once propagated, Vercel will show a green checkmark and issue an SSL certificate automatically.
Once configured, your site will be accessible via your custom domain. Vercel also supports wildcard subdomains and can automatically redirect www to non-www (or vice versa) based on your preference.
Step 8: Environment Variables
Many Next.js apps rely on environment variables for API keys, database URLs, or feature flags. Vercel lets you securely manage these via its dashboard.
In your Vercel project dashboard, go to Settings > Environment Variables.
Click Add and enter:
- Name:
NEXT_PUBLIC_API_URL - Value:
https://api.yourdomain.com - Toggle Deploy Hook if you want to trigger a rebuild on change (recommended for sensitive keys)
Important: Prefix variables with NEXT_PUBLIC_ if they need to be accessible in the browser (e.g., API endpoints for client-side fetches). Variables without this prefix are only available on the server side (e.g., in getServerSideProps or API routes).
In your Next.js code, access them like this:
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
Never commit environment variables to your Git repository. Always use Vercel’s UI to manage them securely.
Step 9: Deploying with Next.js App Router
If you’re using the newer App Router (introduced in Next.js 13+), the deployment process remains identical. Vercel automatically detects and optimizes App Router projects.
Ensure your folder structure follows the App Router convention:
app/
├── page.js
├── layout.js
├── api/
│ └── route.js
└── about/
└── page.js
Vercel will:
- Automatically generate static pages from
page.js - Render server components on the edge
- Optimize image and font loading
- Enable streaming and server actions
No additional configuration is needed. Vercel’s build system is fully compatible with React Server Components, Suspense, and other App Router features.
Step 10: Troubleshooting Common Issues
Even with Vercel’s automation, issues can arise. Here are the most common ones and how to fix them:
1. Build Fails with “Module Not Found”
Ensure all dependencies are listed in package.json. Run npm install locally to verify. Avoid using local file paths or unlisted packages.
2. Environment Variables Not Loading
Check that variables are prefixed with NEXT_PUBLIC_ if used client-side. Also, verify they’re added in the Vercel dashboard, not in a local .env file (which is ignored during deployment).
3. Images Not Loading
Ensure you’re using next/image and that your external domains are whitelisted in next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['images.example.com', 'cdn.myapi.com'],
},
}
4. 404 Errors on Refresh
If you’re using client-side routing with next/router, ensure you’re not relying on server-side routes that don’t exist. For dynamic routes, confirm you have app/[slug]/page.js or pages/[slug].js.
5. Slow Build Times
Optimize your dependencies. Remove unused packages. Use npm ls to audit. Consider enabling Vercel’s Build Cache (enabled by default) and upgrading to a Pro plan for faster builders if needed.
Best Practices
Use Static Generation (SSG) Where Possible
Next.js supports three rendering methods: Static Site Generation (SSG), Server-Side Rendering (SSR), and Client-Side Rendering (CSR). For maximum performance and SEO, prefer SSG.
Use getStaticProps (Pages Router) or server components (App Router) to pre-render pages at build time. This reduces server load, improves Core Web Vitals, and ensures your pages are cached globally on Vercel’s edge network.
Only use SSR (getServerSideProps) when data changes frequently (e.g., real-time dashboards). Even then, consider combining it with revalidation using the revalidate option:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
return {
props: { posts },
revalidate: 60, // Revalidate every 60 seconds
}
}
Optimize Images and Assets
Always use next/image for images. It automatically:
- Converts images to WebP
- Resizes images for device screens
- Implements lazy loading
- Delivers via CDN
For fonts, use @next/font to self-host Google Fonts without layout shifts:
import { Inter } from '@next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
)
}
Enable Build Caching
Vercel caches dependencies and build artifacts by default. To maximize speed:
- Pin your Node.js version in
package.jsonusingengines:
"engines": {
"node": "18.x"
}
- Use
npm ciinstead ofnpm installin production (Vercel does this automatically). - Avoid large node_modules by using
.gitignoreto excludenode_modules/.
Use Environment-Specific Configurations
Define different environment variables for development, preview, and production. Vercel automatically injects NODE_ENV=production during builds. Use this to conditionally load settings:
const apiUrl = process.env.NODE_ENV === 'production'
? process.env.NEXT_PUBLIC_API_URL
: 'http://localhost:3001/api'
Implement Redirects and Rewrites
Use next.config.js to handle redirects (e.g., old URLs) and rewrites (e.g., proxying API paths):
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
]
},
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.yourdomain.com/:path*',
},
]
},
}
Monitor Performance with Vercel Analytics
Vercel provides built-in analytics for every deployment. Enable it in your project settings to track:
- Page load times
- Core Web Vitals (LCP, FID, CLS)
- Bandwidth usage
- Visitor geography
This data helps you identify slow pages, optimize assets, and improve user experience.
Use Deploy Hooks for CI/CD Integration
If you use external CI tools (e.g., GitHub Actions), trigger Vercel builds via deploy hooks:
- In Vercel, go to Project Settings > Deploy Hooks.
- Create a new hook with a descriptive name (e.g., “GitHub CI Trigger”).
- Copy the webhook URL.
- In your CI workflow, make a POST request to this URL after tests pass.
This ensures your site deploys only after all tests pass, maintaining quality.
Tools and Resources
Official Next.js Documentation
The authoritative source for all Next.js features, including App Router, middleware, and API routes. Always refer here for updates and best practices.
Vercel Documentation
Comprehensive guides on deployment, domains, environment variables, edge functions, and analytics.
Next.js Starter Templates
https://github.com/vercel/next.js/tree/canary/examples
Official examples covering e-commerce, blogs, dashboards, and more. Use these as blueprints for your projects.
Netlify vs. Vercel Comparison
While Netlify is a strong alternative, Vercel offers superior Next.js integration, faster builds, and better edge computing support. Use Vercel if you’re building with Next.js; use Netlify for static HTML or non-Next.js React apps.
VS Code Extensions
- Next.js Snippets – Auto-complete for Next.js hooks and components
- ESLint – Enforce code quality
- Prettier – Format code consistently
- Vercel for VS Code – Deploy directly from the editor
Performance Testing Tools
- Lighthouse (Chrome DevTools) – Audit performance, accessibility, SEO
- WebPageTest – Test load times from global locations
- Google PageSpeed Insights – Get SEO and speed scores
- GTmetrix – Detailed waterfall analysis
GitHub Actions for Automated Testing
Combine Vercel with GitHub Actions to run tests before deployment:
name: Test and Deploy
on:
push:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm test
- run: npm run build
deploy:
needs: test
runs-on: ubuntu-latest
steps:
- 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 }}
scope: ${{ secrets.VERCEL_SCOPE }}
This ensures only passing builds are deployed.
Real Examples
Example 1: Personal Blog with Markdown
A developer builds a blog using Next.js App Router, fetching blog posts from Markdown files in /content. They use next-mdx-remote to render content and next/image for featured images.
Deployment:
- Code pushed to GitHub
- Vercel detects Next.js and auto-configures build
- Each blog post is statically generated at build time
- Custom domain:
blog.johndoe.devconfigured - Analytics show 95+ Lighthouse scores across all pages
Result: Zero server costs, instant loading, perfect SEO.
Example 2: E-Commerce Product Catalog
An online store uses Next.js with SSR for product pages that update daily. They use getServerSideProps to fetch inventory data from a headless CMS and set revalidate: 3600 to refresh every hour.
Deployment:
- Product pages are regenerated every hour without full rebuilds
- Images are optimized via
next/imagewith CDN delivery - Environment variables for Stripe and CMS API keys are stored securely in Vercel
- Preview deployments allow marketing team to review new product pages before launch
Result: 80% reduction in server costs compared to traditional Node.js hosting.
Example 3: SaaS Dashboard with Authentication
A startup builds a dashboard app using Next.js App Router, NextAuth.js, and Prisma. Pages are protected with server-side authentication.
Deployment:
- Auth middleware routes users based on session
- API routes are deployed as edge functions for low-latency responses
- Database connection string stored in Vercel environment variables
- Custom domain:
app.mysaas.comwith automatic SSL - Deploy hooks trigger rebuilds when schema changes in CI
Result: Global users experience sub-200ms response times thanks to edge functions and CDN caching.
FAQs
Is Vercel free to use for Next.js projects?
Yes. Vercel offers a generous free tier that includes unlimited deployments, 100 GB bandwidth per month, 10 GB of storage, and 100 build minutes per month. Most personal and small business projects stay well within these limits.
Can I deploy a Next.js app without Git?
Technically yes—Vercel allows uploading a ZIP file via its dashboard. However, this disables automatic deployments and preview environments. Git integration is strongly recommended for all serious projects.
How long does a Vercel deployment take?
Typically 30–90 seconds for small to medium apps. Large apps with hundreds of pages or complex builds may take 3–5 minutes. Build times improve with caching and optimized dependencies.
Does Vercel support API routes in Next.js?
Yes. All API routes in /app/api or /pages/api are automatically deployed as serverless functions or edge functions (depending on your configuration). Vercel scales them automatically.
Can I use a database with Vercel?
Yes. Vercel is a frontend hosting platform, not a backend. You can connect to any external database (PostgreSQL, MongoDB, Supabase, Firebase, etc.) via API routes or server components. Never store database credentials in your code—use Vercel’s environment variables.
Do I need to configure nginx or a server?
No. Vercel handles all server configuration, SSL certificates, CDN, and scaling automatically. You focus on code; Vercel handles infrastructure.
What happens if my build fails?
Vercel sends an email notification and displays the error log in your dashboard. Common causes include missing dependencies, incorrect environment variables, or syntax errors. Fix the issue locally, commit, and push again.
Can I use Vercel with a monorepo?
Yes. Vercel supports monorepos using tools like Turborepo or Nx. You can specify the subdirectory containing your Next.js app in the project settings under “Root Directory.”
How do I rollback a deployment?
In your Vercel dashboard, go to the “Deployments” tab. Click the three dots next to a previous deployment and select “Promote.” This makes that version live again.
Is Vercel suitable for enterprise applications?
Absolutely. Vercel offers Enterprise plans with SSO, audit logs, dedicated support, and advanced security features. Companies like Netflix, Hulu, and Uber use Vercel for production applications.
Conclusion
Deploying Next.js on Vercel is not just the easiest way to launch a modern web application—it’s the most performant, scalable, and developer-friendly option available today. From automatic build optimization and global CDN delivery to seamless Git integration and preview deployments, Vercel removes the complexity of infrastructure so you can focus on building great user experiences.
By following this guide, you’ve learned how to deploy a Next.js app from zero to production in minutes. You now understand best practices for performance, security, and scalability—and how to leverage Vercel’s advanced features like environment variables, custom domains, and analytics.
As web applications continue to evolve, the line between frontend and backend blurs. Next.js, paired with Vercel, represents the future of web development: fast, secure, and serverless by default. Whether you’re building a personal portfolio, a startup MVP, or a global enterprise app, deploying on Vercel ensures your site loads instantly, scales effortlessly, and stays secure—without you managing a single server.
Start deploying today. Your users will thank you.