Deploy Next.js
This guide will help you deploy a Next.js application to Deployxa.
Overview
Next.js is a React framework for building full-stack web applications. Deployxa provides zero-configuration deployments for Next.js with automatic optimization.
Features:
- Automatic framework detection
- Server-side rendering (SSR) support
- Static site generation (SSG) support
- API routes support
- Image optimization
- Automatic HTTPS
Prerequisites
- A Next.js application (version 12 or higher recommended)
- A GitHub repository with your code
- A Deployxa account
Quick Start
1. Create Your Next.js App
If you don't have a Next.js app yet:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
2. Push to GitHub
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-nextjs-app.git
git push -u origin main
3. Deploy to Deployxa
- Go to Deployxa Dashboard
- Click "New Project"
- Select your GitHub repository
- Deployxa will automatically detect Next.js
- Click "Deploy"
Your app will be live in under 60 seconds!
Configuration
Detected Settings
Deployxa automatically detects these settings:
| Setting | Value |
|---|---|
| Framework | Next.js |
| Build Command | npm run build |
| Output Directory | .next |
| Start Command | npm start |
| Port | 3000 |
Custom Configuration
If you need to customize settings:
- Go to Project → Settings → Build
- Modify settings as needed
- Save changes
Example Custom Settings:
{
"buildCommand": "npm run build",
"outputDirectory": ".next",
"installCommand": "npm ci",
"startCommand": "npm start"
}
Environment Variables
Adding Environment Variables
- Go to Project → Environment
- Click "Add Variable"
- Enter key and value
- Select environment (Production, Preview, Development)
- Click "Save"
Common Next.js Environment Variables:
DATABASE_URL=postgresql://user:pass@host:5432/db
NEXT_PUBLIC_API_URL=https://api.example.com
STRIPE_SECRET_KEY=sk_test_1234567890
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_1234567890
Note: Variables prefixed with NEXT_PUBLIC_ are exposed to the browser.
Using Environment Variables
In your Next.js code:
// Server-side only
const dbUrl = process.env.DATABASE_URL;
// Available on both server and client
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
Build Process
What Happens During Build
- Install Dependencies:
npm installornpm ci - Run Build:
npm run build - Generate Static Pages: Pre-render static pages
- Create Server Bundle: Build server-side code
- Optimize Images: Optimize images in
/public - Package Application: Create deployment package
Build Output
Next.js generates:
.next/- Build output directory.next/static/- Static assets.next/server/- Server-side code.next/cache/- Build cache
Deployment Strategies
Static Site Generation (SSG)
For mostly static content:
// pages/index.js
export async function getStaticProps() {
const data = await fetchData();
return { props: { data } };
}
Benefits:
- Fast load times
- CDN caching
- Low resource usage
Server-Side Rendering (SSR)
For dynamic content:
// pages/index.js
export async function getServerSideProps(context) {
const data = await fetchData(context);
return { props: { data } };
}
Benefits:
- Always up-to-date data
- SEO friendly
- Personalized content
API Routes
For backend functionality:
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello World' });
}
Access: https://your-app.deployxa.app/api/hello
Custom Domains
Adding a Custom Domain
- Go to Project → Domains
- Click "Add Domain"
- Enter your domain (e.g.,
example.com) - Configure DNS records
- Wait for verification
DNS Configuration
For Apex Domain (example.com):
Type: A
Name: @
Value: 76.76.21.21
For Subdomain (www.example.com):
Type: CNAME
Name: www
Value: cname.deployxa.com
SSL Certificate
Deployxa automatically provisions SSL certificates:
- Free Let's Encrypt certificates
- Automatic renewal
- HTTPS enforced
- Wildcard support
Performance Optimization
Enable Image Optimization
Next.js automatically optimizes images:
import Image from 'next/image';
<Image
src="/photo.jpg"
alt="Photo"
width={500}
height={500}
/>
Enable Static Generation
For pages that don't change often:
export async function getStaticProps() {
return {
props: { data },
revalidate: 3600, // Revalidate every hour
};
}
Enable Caching
Configure cache headers:
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Cache-Control', value: 's-maxage=60, stale-while-revalidate' },
],
},
];
},
};
Monitoring
Viewing Logs
- Go to Project → Logs
- Select log type:
- Build Logs: Deployment process
- Runtime Logs: Application output
- Error Logs: Application errors
Monitoring Metrics
- Go to Project → Analytics
- View metrics:
- Request count
- Response times
- Error rates
- Bandwidth usage
- CPU/RAM usage
Health Checks
Deployxa automatically monitors your application:
- HTTP health checks every 30 seconds
- Automatic restart on failure
- Alerts on consecutive failures
Troubleshooting
Build Failed: Module Not Found
Problem: Module not found: Can't resolve 'package-name'
Solution:
- Check
package.jsonhas the dependency - Run
npm install package-namelocally - Commit and push changes
- Redeploy
Build Failed: Environment Variable Missing
Problem: Environment variable not found: VARIABLE_NAME
Solution:
- Go to Project → Environment
- Add the missing variable
- Redeploy
Runtime Error: Port Already in Use
Problem: Error: listen EADDRINUSE: address already in use :::3000
Solution:
- Deployxa automatically handles port configuration
- Ensure your code uses
process.env.PORTor defaults to 3000
const port = process.env.PORT || 3000;
app.listen(port);
Pages Not Loading
Problem: Pages return 404 or blank
Solution:
- Check build logs for errors
- Verify file structure
- Ensure
next.config.jsis correct - Check runtime logs for errors
Slow Build Times
Problem: Build takes too long
Solution:
- Use
npm ciinstead ofnpm install - Enable dependency caching
- Reduce build steps
- Consider upgrading plan
Best Practices
Project Structure
my-nextjs-app/
├── pages/
│ ├── api/
│ │ └── hello.js
│ ├── index.js
│ └── about.js
├── public/
│ └── favicon.ico
├── styles/
│ └── globals.css
├── next.config.js
├── package.json
└── README.md
Environment Variables
- Use
.env.localfor local development - Never commit
.envfiles - Use
NEXT_PUBLIC_prefix for client-side variables - Rotate secrets regularly
Performance
- Use
getStaticPropswhen possible - Enable image optimization
- Use code splitting
- Minimize bundle size
- Enable compression
Security
- Never expose secrets in client code
- Use HTTPS only
- Validate all inputs
- Use CSRF protection
- Keep dependencies updated
Advanced Configuration
Custom Next.js Config
// next.config.js
module.exports = {
reactStrictMode: true,
swcMinify: true,
images: {
domains: ['images.example.com'],
},
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
];
},
async rewrites() {
return [
{
source: '/blog/:slug',
destination: '/api/blog/:slug',
},
];
},
};
Custom Server
For advanced use cases:
// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(process.env.PORT || 3000);
});
Update package.json:
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
Examples
Basic Next.js App
// pages/index.js
export default function Home() {
return (
<div>
<h1>Welcome to Next.js on Deployxa!</h1>
</div>
);
}
With Data Fetching
// pages/index.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
revalidate: 60,
};
}
export default function Home({ data }) {
return (
<div>
<h1>Data: {data.title}</h1>
</div>
);
}
API Route
// pages/api/users.js
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ users: [] });
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}
Related Topics
Resources
Need Help? Contact support@deployxa.com or join our community Discord.