Next.js Turbopack Stuck on Compiling How to Fix
Turbopack stuck on compiling in Next.js 15? Learn the exact causes and 5 proven fixes to get your dev server running in minutes.
Next.js Turbopack Stuck on Compiling How to Fix#
Turbopack stuck on "Compiling..." is one of the most frustrating issues in Next.js 15 development. Your dev server starts, shows "Compiling /page", and then... nothing. It hangs indefinitely, blocking your entire development workflow. This guide provides 5 proven solutions that work in production.
This article is part of our comprehensive Deploying Next.js + Supabase to Production guide.
Why Turbopack Gets Stuck#
Turbopack can hang for several reasons:
- Corrupted Cache -
.nextcache conflicts with Turbopack - Circular Dependencies - Import cycles cause infinite loops
- Large Files - Huge files or node_modules slow compilation
- Memory Issues - Insufficient RAM for compilation
- Incompatible Dependencies - Packages not compatible with Turbopack
Quick Diagnostic Steps#
## Check if it's actually stuck or just slow
## Wait 2-3 minutes first - large projects take time
## Check Node.js version (requires 18.17+)
node --version
## Check memory usage
## Windows: Task Manager > Performance
## Mac: Activity Monitor
## Linux: htop or top
## Check for error messages
## Look in terminal for warnings/errors
Solution 1: Clear All Caches (Works 80% of Time)#
The most common fix is clearing caches:
## Stop the dev server (Ctrl+C)
## Delete all cache directories
rm -rf .next
rm -rf node_modules/.cache
rm -rf .turbo
## Clear npm cache
npm cache clean --force
## Reinstall dependencies
rm -rf node_modules
rm package-lock.json
npm install
## Start dev server
npm run dev
For Windows Users#
## Stop dev server (Ctrl+C)
## Delete cache directories
Remove-Item -Recurse -Force .next
Remove-Item -Recurse -Force node_modules\.cache
Remove-Item -Recurse -Force .turbo
## Clear npm cache
npm cache clean --force
## Reinstall
Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm install
## Start server
npm run dev
Solution 2: Disable Turbopack Temporarily#
If clearing cache doesn't work, disable Turbopack:
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
// Remove or comment out turbopack option
// experimental: {
// turbo: {},
// },
}
export default nextConfig
Start Without Turbopack Flag#
## Instead of: npm run dev --turbo
## Use: npm run dev
## Or update package.json:
{
"scripts": {
"dev": "next dev", // Remove --turbo flag
"dev:turbo": "next dev --turbo", // Keep as separate command
"build": "next build",
"start": "next start"
}
}
Solution 3: Fix Circular Dependencies#
Circular imports cause Turbopack to hang:
Detect Circular Dependencies#
## Install circular dependency checker
npm install --save-dev madge
## Check for circular dependencies
npx madge --circular --extensions ts,tsx,js,jsx src/
## Output shows circular imports:
## Circular dependency found:
## src/components/A.tsx > src/components/B.tsx > src/components/A.tsx
Fix Circular Imports#
// BAD: Circular dependency
// components/UserProfile.tsx
import { UserSettings } from './UserSettings'
export function UserProfile() {
return <UserSettings />
}
// components/UserSettings.tsx
import { UserProfile } from './UserProfile' // ❌ Circular!
export function UserSettings() {
return <UserProfile />
}
// GOOD: Break the cycle
// components/UserProfile.tsx
import { UserSettings } from './UserSettings'
export function UserProfile() {
return <UserSettings />
}
// components/UserSettings.tsx
// Remove import of UserProfile
// Use composition or context instead
export function UserSettings() {
return <div>Settings</div>
}
Solution 4: Optimize Large Files and Dependencies#
Check File Sizes#
## Find large files in your project
find . -type f -size +1M -not -path "./node_modules/*" -not -path "./.next/*"
## Check node_modules size
du -sh node_modules
## Analyze bundle size
npm install --save-dev @next/bundle-analyzer
## Add to next.config.mjs:
import bundleAnalyzer from '@next/bundle-analyzer'
const withBundleAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})
export default withBundleAnalyzer(nextConfig)
## Run analysis
ANALYZE=true npm run build
Optimize Dependencies#
// next.config.mjs
const nextConfig = {
// Exclude large dependencies from server bundle
serverExternalPackages: ['sharp', 'canvas', 'pdf-lib'],
// Optimize package imports
modularizeImports: {
'lodash': {
transform: 'lodash/{{member}}',
},
'@mui/material': {
transform: '@mui/material/{{member}}',
},
},
}
Solution 5: Increase Memory Limit#
Turbopack may need more memory for large projects:
// package.json
{
"scripts": {
"dev": "NODE_OPTIONS='--max-old-space-size=4096' next dev --turbo",
"build": "NODE_OPTIONS='--max-old-space-size=4096' next build"
}
}
For Windows#
// package.json
{
"scripts": {
"dev": "set NODE_OPTIONS=--max-old-space-size=4096 && next dev --turbo",
"build": "set NODE_OPTIONS=--max-old-space-size=4096 && next build"
}
}
Cross-Platform Solution#
## Install cross-env
npm install --save-dev cross-env
## Update package.json
{
"scripts": {
"dev": "cross-env NODE_OPTIONS='--max-old-space-size=4096' next dev --turbo",
"build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' next build"
}
}
Solution 6: Update Dependencies#
Outdated packages can cause compatibility issues:
## Check for outdated packages
npm outdated
## Update Next.js to latest
npm install next@latest react@latest react-dom@latest
## Update all dependencies (careful!)
npm update
## Or use npm-check-updates
npx npm-check-updates -u
npm install
Check Turbopack Compatibility#
## Some packages don't work with Turbopack yet
## Check Next.js docs for compatibility:
## https://nextjs.org/docs/architecture/turbopack
## Common incompatible packages:
## - Some Webpack-specific loaders
## - Custom Webpack configurations
## - Some PostCSS plugins
Solution 7: Debug with Verbose Logging#
Enable detailed logging to identify the issue:
## Run with debug mode
DEBUG=* npm run dev --turbo
## Or set environment variable
export DEBUG=*
npm run dev --turbo
## Check specific Next.js logs
DEBUG=next:* npm run dev --turbo
Create Debug Configuration#
// next.config.mjs
const nextConfig = {
// Enable detailed logging
logging: {
fetches: {
fullUrl: true,
},
},
// Show more build info
productionBrowserSourceMaps: true,
}
Common Mistakes#
-
Mistake #1: Not waiting long enough - First compile can take 2-3 minutes for large projects
-
Mistake #2: Using incompatible Webpack config - Turbopack doesn't support all Webpack features
-
Mistake #3: Not checking Node.js version - Requires Node 18.17 or higher
-
Mistake #4: Ignoring circular dependencies - These cause infinite compilation loops
-
Mistake #5: Running multiple dev servers - Kill all Node processes before restarting
FAQ#
How long should Turbopack compilation take?#
First compilation: 30 seconds to 3 minutes depending on project size. Subsequent hot reloads: 1-5 seconds. If it takes longer, something is wrong.
Is Turbopack stable for production?#
Turbopack is for development only in Next.js 15. Production builds still use Webpack. It's stable for dev but may have edge cases.
Should I use Turbopack or Webpack?#
Turbopack is faster for development but less mature. If you encounter issues, fall back to Webpack (npm run dev without --turbo flag).
Can I use Turbopack with custom Webpack config?#
Limited support. Many Webpack plugins and loaders don't work with Turbopack. Check Next.js docs for compatibility.
How do I completely disable Turbopack?#
Remove --turbo flag from dev script and remove any turbo configuration from next.config.mjs.
Advanced Debugging Techniques#
Using Chrome DevTools for Turbopack Issues#
// Enable detailed logging in next.config.mjs
const nextConfig = {
logging: {
fetches: {
fullUrl: true,
},
},
// Show webpack build info
webpack: (config, { dev, isServer }) => {
if (!dev) {
console.log('Building for:', isServer ? 'server' : 'client')
}
return config
},
}
export default nextConfig
Profiling Turbopack Performance#
## Generate performance profile
node --prof node_modules/.bin/next dev --turbo
## Analyze the profile
node --prof-process isolate-*.log > profile.txt
## Check which functions take the most time
grep -E "ticks|name" profile.txt | head -50
Monitoring Compilation Time#
// Create a simple timer to track compilation
const startTime = Date.now()
// In your middleware or API route
export async function middleware(request) {
const compilationTime = Date.now() - startTime
console.log(`Compilation took ${compilationTime}ms`)
if (compilationTime > 5000) {
console.warn('Slow compilation detected!')
}
}
Turbopack Configuration Optimization#
Optimize for Large Projects#
// next.config.mjs
const nextConfig = {
experimental: {
turbo: {
// Exclude large files from compilation
excludeFiles: [
'**/*.test.ts',
'**/*.spec.ts',
'**/node_modules/**',
'**/.next/**',
],
// Resolve aliases for faster imports
resolveAlias: {
'@': './src',
'@/components': './src/components',
'@/lib': './src/lib',
'@/utils': './src/utils',
},
// Optimize package imports
resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
// Enable caching
cacheDir: '.turbo',
},
},
}
export default nextConfig
Disable Turbopack for Specific Routes#
// next.config.mjs
const nextConfig = {
experimental: {
turbo: {
// Disable for routes that cause issues
excludeFiles: [
'app/api/heavy-computation/**',
'app/admin/**',
],
},
},
}
export default nextConfig
Preventing Turbopack Issues#
Best Practices for Stable Development#
-
Keep dependencies updated
npm update npm install next@latest -
Avoid circular dependencies
npx madge --circular --extensions ts,tsx src/ -
Monitor file sizes
find . -type f -size +1M -not -path "./node_modules/*" -
Use consistent import patterns
// ✅ GOOD: Consistent absolute imports import { Button } from '@/components/Button' import { formatDate } from '@/lib/utils' // ❌ BAD: Mixed relative and absolute import { Button } from '../components/Button' import { formatDate } from '@/lib/utils' -
Limit custom Webpack configuration
// ❌ AVOID: Complex webpack config webpack: (config) => { config.plugins.push(new CustomPlugin()) config.module.rules.push(customRule) return config } // ✅ PREFER: Use Next.js built-in features // Use modularizeImports instead of custom loaders
Monitoring and Alerting#
Set Up Compilation Time Alerts#
// lib/compilation-monitor.ts
let lastCompilationTime = 0
const SLOW_COMPILATION_THRESHOLD = 5000 // 5 seconds
export function monitorCompilation() {
if (typeof window === 'undefined') return
// Monitor page load time
window.addEventListener('load', () => {
const navigationTiming = performance.getEntriesByType('navigation')[0]
const loadTime = navigationTiming.loadEventEnd - navigationTiming.loadEventStart
if (loadTime > SLOW_COMPILATION_THRESHOLD) {
console.warn(`Slow page load detected: ${loadTime}ms`)
// Send to monitoring service
reportSlowLoad(loadTime)
}
})
}
function reportSlowLoad(time: number) {
// Send to your monitoring service
fetch('/api/monitoring', {
method: 'POST',
body: JSON.stringify({ type: 'slow-load', time })
})
}
Create a Health Check Endpoint#
// app/api/health/route.ts
import { NextResponse } from 'next/server'
export async function GET() {
const startTime = Date.now()
try {
// Simulate a compilation check
const result = await import('@/lib/utils')
const compilationTime = Date.now() - startTime
return NextResponse.json({
status: 'healthy',
compilationTime,
timestamp: new Date().toISOString(),
})
} catch (error) {
return NextResponse.json(
{
status: 'unhealthy',
error: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
)
}
}
Troubleshooting Checklist#
Use this checklist when Turbopack gets stuck:
□ Wait 2-3 minutes (first compile is slow)
□ Check Node.js version (requires 18.17+)
□ Check available memory (need 2GB+)
□ Clear .next directory
□ Clear node_modules/.cache
□ Clear .turbo directory
□ Reinstall dependencies
□ Check for circular dependencies
□ Check for large files (>1MB)
□ Disable Turbopack temporarily
□ Check for incompatible packages
□ Update Next.js to latest
□ Check deployment logs for errors
□ Enable debug logging
□ Profile with Node.js profiler
□ Check for network issues
□ Restart dev server
Related Articles#
- Fix Next.js Build Error Module Not Found After Deploy
- Resolve Next.js Hydration Mismatch Errors Complete Guide
- Deploy Next.js 15 to Vercel Without Environment Variable Errors
- Next.js Performance Optimization: 10 Essential Techniques
- Building SaaS with Next.js and Supabase
Conclusion#
Turbopack stuck on compiling is usually caused by corrupted cache, circular dependencies, or memory issues. The fastest fix is clearing all caches (.next, node_modules/.cache, .turbo) and reinstalling dependencies.
If that doesn't work, check for circular imports using madge, increase memory limits, or temporarily disable Turbopack. For production projects, always have a fallback to standard Webpack mode.
Monitor your compilation times and file sizes to prevent future issues. Turbopack is powerful but still maturing, so don't hesitate to fall back to Webpack if needed.
Frequently Asked Questions
Continue Reading
Fix Supabase Auth Session Not Persisting After Refresh
Supabase auth sessions mysteriously disappearing after page refresh? Learn the exact cause and fix it in 5 minutes with this tested solution.
Next.js 15 Caching Explained: Why Your Data Keeps Showing as Stale
Upgraded to Next.js 15 and suddenly your data is stale — or refreshing too often? The caching model changed completely. Here is what actually happens and how to control it.
Next.js 15 vs Next.js 14: Performance Comparison and Migration Guide 2026
Comprehensive comparison of Next.js 15 and 14 performance improvements, new features, breaking changes, and whether you should upgrade your production app.