Skip to main content

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

  1. Go to Deployxa Dashboard
  2. Click "New Project"
  3. Select your GitHub repository
  4. Deployxa will automatically detect Next.js
  5. Click "Deploy"

Your app will be live in under 60 seconds!

Configuration

Detected Settings

Deployxa automatically detects these settings:

SettingValue
FrameworkNext.js
Build Commandnpm run build
Output Directory.next
Start Commandnpm start
Port3000

Custom Configuration

If you need to customize settings:

  1. Go to ProjectSettingsBuild
  2. Modify settings as needed
  3. Save changes

Example Custom Settings:

{
"buildCommand": "npm run build",
"outputDirectory": ".next",
"installCommand": "npm ci",
"startCommand": "npm start"
}

Environment Variables

Adding Environment Variables

  1. Go to ProjectEnvironment
  2. Click "Add Variable"
  3. Enter key and value
  4. Select environment (Production, Preview, Development)
  5. 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

  1. Install Dependencies: npm install or npm ci
  2. Run Build: npm run build
  3. Generate Static Pages: Pre-render static pages
  4. Create Server Bundle: Build server-side code
  5. Optimize Images: Optimize images in /public
  6. 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

  1. Go to ProjectDomains
  2. Click "Add Domain"
  3. Enter your domain (e.g., example.com)
  4. Configure DNS records
  5. 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

  1. Go to ProjectLogs
  2. Select log type:
    • Build Logs: Deployment process
    • Runtime Logs: Application output
    • Error Logs: Application errors

Monitoring Metrics

  1. Go to ProjectAnalytics
  2. 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:

  1. Check package.json has the dependency
  2. Run npm install package-name locally
  3. Commit and push changes
  4. Redeploy

Build Failed: Environment Variable Missing

Problem: Environment variable not found: VARIABLE_NAME

Solution:

  1. Go to ProjectEnvironment
  2. Add the missing variable
  3. 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.PORT or defaults to 3000
const port = process.env.PORT || 3000;
app.listen(port);

Pages Not Loading

Problem: Pages return 404 or blank

Solution:

  1. Check build logs for errors
  2. Verify file structure
  3. Ensure next.config.js is correct
  4. Check runtime logs for errors

Slow Build Times

Problem: Build takes too long

Solution:

  1. Use npm ci instead of npm install
  2. Enable dependency caching
  3. Reduce build steps
  4. 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.local for local development
  • Never commit .env files
  • Use NEXT_PUBLIC_ prefix for client-side variables
  • Rotate secrets regularly

Performance

  • Use getStaticProps when 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' });
}
}

Resources


Need Help? Contact support@deployxa.com or join our community Discord.