Troubleshooting
Common issues and solutions for Capricorn Next.js templates.
Installation Issues
Port 3000 Already in Use
Problem: Error: listen EADDRINUSE: address already in use :::3000
Solution 1: Use Different Port
npm run dev -- -p 3001Solution 2: Kill Process Using Port
# Find process
lsof -i :3000
# Kill process (replace PID with actual process ID)
kill -9 PID
# On Windows
netstat -ano | findstr :3000
taskkill /PID <PID> /FInstallation Fails
Problem: npm install fails with errors
Solution:
# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm cache clean --force
npm install
# If still fails, try with legacy peer deps
npm install --legacy-peer-depsNode Version Issues
Problem: Error: The engine "node" is incompatible
Solution:
# Check your Node version
node --version
# Should be 18.17 or later
# Install correct version using nvm
nvm install 18
nvm use 18Build Issues
Build Fails
Problem: npm run build fails
Solution 1: Clear Next.js Cache
rm -rf .next
npm run buildSolution 2: Check for TypeScript Errors
# Run type check
npx tsc --noEmit
# Fix any TypeScript errors shownSolution 3: Increase Memory
# Add to package.json scripts
"build": "NODE_OPTIONS='--max-old-space-size=4096' next build"Image Optimization Errors
Problem: Error: Invalid src prop or image not loading
Solution:
// Make sure images are in public folder
// Wrong
<Image src="images/hero.jpg" />
// Correct
<Image src="/images/hero.jpg" />
// For external images, add domains to next.config.js
module.exports = {
images: {
domains: ['example.com', 'cdn.example.com'],
},
}Module Not Found
Problem: Module not found: Can't resolve 'component'
Solution:
# Reinstall dependencies
npm install
# Check import paths
# Wrong
import { Button } from 'components/ui/button'
# Correct (check your tsconfig paths)
import { Button } from '@/components/ui/button'Runtime Issues
Page Not Found (404)
Problem: Pages return 404 error
Solution 1: Check File Structure
app/
├── page.tsx → /
├── about/
│ └── page.tsx → /about
└── services/
└── page.tsx → /servicesSolution 2: Restart Dev Server
# Stop server (Ctrl+C) and restart
npm run devSolution 3: Clear Cache
rm -rf .next
npm run devStyles Not Loading
Problem: Tailwind CSS styles not working
Solution 1: Check tailwind.config.ts
// Make sure content paths are correct
export default {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
],
}Solution 2: Import Global Styles
// In app/layout.tsx
import './globals.css'Solution 3: Restart Dev Server
npm run devEnvironment Variables Not Working
Problem: process.env.NEXT_PUBLIC_VAR is undefined
Solution:
# 1. Check variable name has NEXT_PUBLIC_ prefix
# Wrong
API_URL=https://api.example.com
# Correct
NEXT_PUBLIC_API_URL=https://api.example.com
# 2. Restart dev server after adding variables
npm run dev
# 3. For server-only variables (API routes, server components)
# No prefix needed
DATABASE_URL=postgresql://...Hydration Errors
Problem: Warning: Text content did not match or Hydration failed
Solution 1: Check for Client-Only Code
// Wrong - using window on server
export default function Component() {
const width = window.innerWidth // ❌
return <div>{width}</div>
}
// Correct - check if window exists
export default function Component() {
const [width, setWidth] = useState(0)
useEffect(() => {
setWidth(window.innerWidth)
}, [])
return <div>{width}</div>
}Solution 2: Use ‘use client’ Directive
'use client'
export default function ClientComponent() {
// Client-only code here
const data = localStorage.getItem('key')
return <div>{data}</div>
}Solution 3: Ensure Matching HTML
// Wrong - different content on server/client
<div>{isClient ? 'Client' : 'Server'}</div>
// Correct - use suppressHydrationWarning if intentional
<div suppressHydrationWarning>
{isClient ? 'Client' : 'Server'}
</div>Component Issues
Component Not Rendering
Problem: Component appears blank or doesn’t render
Solution 1: Check Import/Export
// Wrong
export function Button() { }
// Correct - match import style
export default function Button() { }
// or
export function Button() { }
// then import { Button } from './button'Solution 2: Check for Errors
# Open browser console (F12)
# Look for JavaScript errorsSolution 3: Add Error Boundary
// components/error-boundary.tsx
'use client'
export default function ErrorBoundary({
error,
reset,
}: {
error: Error
reset: () => void
}) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}Form Submission Not Working
Problem: Forms don’t submit or redirect
Solution:
// Add proper form handling
async function handleSubmit(e: React.FormEvent) {
e.preventDefault() // Prevent default form submission
const formData = new FormData(e.target as HTMLFormElement)
try {
const response = await fetch('/api/contact', {
method: 'POST',
body: formData,
})
if (response.ok) {
// Handle success
}
} catch (error) {
console.error('Error:', error)
}
}
<form onSubmit={handleSubmit}>
{/* form fields */}
</form>Data Fetching Issues
API Route Not Working
Problem: /api/endpoint returns 404 or error
Solution 1: Check File Location
app/
└── api/
└── contact/
└── route.ts → /api/contactSolution 2: Verify Export
// route.ts
export async function POST(request: Request) {
const data = await request.json()
// Process data
return Response.json({ success: true })
}
// Must export GET, POST, PUT, DELETE, etc.Solution 3: Check CORS (if calling from different domain)
export async function POST(request: Request) {
return Response.json(
{ success: true },
{
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
},
}
)
}Data Not Updating
Problem: Data doesn’t refresh after changes
Solution 1: Use Router Refresh
'use client'
import { useRouter } from 'next/navigation'
export default function Component() {
const router = useRouter()
async function handleUpdate() {
// Make changes
await updateData()
// Refresh page data
router.refresh()
}
}Solution 2: Revalidate Cache
// In Server Action or Route Handler
import { revalidatePath } from 'next/cache'
export async function updateData() {
// Update data
// Revalidate specific path
revalidatePath('/dashboard')
}Deployment Issues
Build Succeeds Locally But Fails in Production
Problem: Build works on your machine but fails on hosting platform
Solution 1: Check Environment Variables
# Make sure all required env vars are set in production
# Check platform settings (Vercel, Netlify, etc.)Solution 2: Check Node Version
// Add to package.json
{
"engines": {
"node": ">=18.17.0"
}
}Solution 3: Lock Dependencies
# Use package-lock.json
npm ci # Instead of npm installStatic Export Issues
Problem: output: 'export' fails
Solution:
// Remove incompatible features:
// ❌ API routes
// ❌ Server Components with dynamic data
// ❌ Image optimization (need unoptimized: true)
// next.config.js
module.exports = {
output: 'export',
images: {
unoptimized: true,
},
}Images Not Loading in Production
Problem: Images work locally but not in production
Solution 1: Check Image Paths
// Use absolute paths from public folder
<Image src="/images/hero.jpg" alt="Hero" />Solution 2: Configure Image Domains
// next.config.js
module.exports = {
images: {
domains: ['yourdomain.com'],
},
}Solution 3: Check File Case
# File system may be case-sensitive in production
# hero.jpg ≠ Hero.jpgPerformance Issues
Slow Page Load
Problem: Pages load slowly
Solution 1: Optimize Images
// Use Next.js Image component
import Image from 'next/image'
<Image
src="/hero.jpg"
alt="Hero"
width={1920}
height={1080}
priority // For above-fold images
/>Solution 2: Use Dynamic Imports
// Lazy load heavy components
import dynamic from 'next/dynamic'
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <p>Loading...</p>,
})Solution 3: Enable React Strict Mode
// next.config.js
module.exports = {
reactStrictMode: true,
}Memory Issues
Problem: Build or runtime memory errors
Solution:
# Increase Node memory limit
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build
# Or add to package.json
"build": "NODE_OPTIONS='--max-old-space-size=4096' next build"TypeScript Issues
Type Errors
Problem: TypeScript compilation errors
Solution 1: Update Types
npm install --save-dev @types/react @types/nodeSolution 2: Fix Common Type Issues
// Event types
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const value = e.target.value
}
// Component props
interface ButtonProps {
onClick: () => void
children: React.ReactNode
}
// API responses
interface ApiResponse {
data: {
id: string
name: string
}
}Solution 3: Disable Type Checking (temporary)
// next.config.js
module.exports = {
typescript: {
ignoreBuildErrors: true, // Not recommended
},
}Common Error Messages
Error: ENOSPC: System limit for number of file watchers reached
Solution (Linux):
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -pError: Cannot find module
Solution:
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm installError: Invalid hook call
Solution:
// Make sure hooks are only used in functional components
// Add 'use client' directive if needed
'use client'
import { useState } from 'react'
export default function Component() {
const [state, setState] = useState('')
// ...
}Getting More Help
Check Logs
Development:
# Terminal output shows build errors
# Browser console (F12) shows runtime errorsProduction:
# Vercel
vercel logs
# Netlify
netlify logs
# Self-hosted
pm2 logs
# or
sudo journalctl -u your-app -n 50Debug Mode
# Run with debug output
DEBUG=* npm run dev
# Or Next.js specific
NODE_OPTIONS='--inspect' npm run devStill Stuck?
If you’ve tried the solutions above and still have issues:
-
Check Documentation
-
Search Similar Issues
- Next.js GitHub Issues
- Stack Overflow
-
Contact Support
- Email: support@capricorn.engineering
- Include:
- Error message (full stack trace)
- Steps to reproduce
- Your environment (Node version, OS, etc.)
- What you’ve already tried
Prevent Future Issues
Best Practices
-
Keep Dependencies Updated
npm outdated npm update -
Use Version Control
git init git add . git commit -m "Working version" -
Test Before Deploying
npm run build npm run start -
Use Environment Variables
- Never commit secrets
- Use
.env.localfor local development - Set variables in production platform
-
Monitor Production
- Set up error tracking
- Monitor performance
- Check logs regularly
Remember: Most issues are solved by:
- Restarting the dev server
- Clearing
.nextcache - Reinstalling
node_modules - Checking the browser console
Still need help? Email support@capricorn.engineering