-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext.config.js
More file actions
582 lines (538 loc) · 18.9 KB
/
next.config.js
File metadata and controls
582 lines (538 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// Note: Console suppression removed to prevent Next.js build issues with URL validation
// Sensitive data protection is handled by environment variables and security headers
const { withSentryConfig } = require('@sentry/nextjs')
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
eslint: {
ignoreDuringBuilds: true,
},
typescript: {
ignoreBuildErrors: true,
},
// Sentry configuration moved to instrumentation.ts and sentry.*.config.ts
// Performance optimizations for legal platform
experimental: {
optimizePackageImports: [
'lucide-react',
'@supabase/supabase-js',
'framer-motion',
'recharts',
'd3',
],
// Disable Next.js automatic scroll restoration - we handle it manually
scrollRestoration: false,
// Netlify build optimizations - reduce concurrency to prevent timeouts
workerThreads: false,
cpus: 1,
},
// Externalize packages for server components (moved from experimental)
// Externalize AI packages that may have CommonJS/ESM compatibility issues
// REMOVED @clerk/nextjs from externals to fix "Invalid hook call" error
serverExternalPackages: ['@heroui/react', '@heroui/styles', 'react-aria-components', '@sentry/nextjs', '@google/generative-ai', 'openai'],
// Performance budgets for production builds
webpack: (config, { isServer, dev }) => {
// Set up @ alias for all builds
config.resolve.alias = {
...config.resolve.alias,
'@': require('path').resolve(__dirname),
}
// CommonJS/ESM compatibility for server bundles
if (isServer) {
// CRITICAL: Debug and skip Edge Runtime entirely
// Edge Runtime (middleware) requires ESM and breaks with ANY webpack modifications
console.log('[WEBPACK DEBUG] Config name:', config.name, 'Target:', config.target)
// Skip ALL webpack modifications for edge-server
if (config.name === 'edge-server') {
console.log('[WEBPACK DEBUG] Skipping Edge Runtime - returning early')
// CRITICAL: Disable eval-based source maps in Edge Runtime to prevent CSP violations
config.devtool = false
// Add alias to prevent TypeScript files from being processed in edge runtime
config.resolve = config.resolve || {}
config.resolve.alias = {
...config.resolve.alias,
// Map TypeScript instrumentation to no-op for edge runtime
'./instrumentation-nodejs.ts': false,
'@/lib/utils/env-validator': false,
'@/lib/security/encryption-validator.server': false,
}
return config
}
// Only apply to Node.js server runtime
console.log('[WEBPACK DEBUG] Applying CommonJS config')
config.output = {
...config.output,
environment: {
...config.output?.environment,
module: false,
},
}
// Configure module resolution to prefer CommonJS when available
config.resolve.mainFields = ['main', 'module']
config.resolve.conditionNames = ['require', 'node', 'default']
// Ensure proper module type detection for .js files
config.resolve.extensionAlias = {
...config.resolve.extensionAlias,
'.js': ['.js', '.ts', '.tsx'],
}
// Configure webpack to handle node: protocol imports
// These are Node.js built-ins that should be externalized
config.externals = config.externals || []
if (Array.isArray(config.externals)) {
// Add function to externalize node: protocol imports
config.externals.push(({ request }, callback) => {
if (request && request.startsWith('node:')) {
// Externalize node: protocol imports - they're provided by Node.js runtime
return callback(null, `commonjs ${request}`)
}
callback()
})
} else if (typeof config.externals === 'object') {
// If externals is an object, add node: protocol handling
const originalExternals = config.externals
config.externals = [
originalExternals,
({ request }, callback) => {
if (request && request.startsWith('node:')) {
return callback(null, `commonjs ${request}`)
}
callback()
},
]
}
// Note: Don't override optimization.usedExports as it conflicts with Next.js cacheUnaffected
// The CommonJS/ESM compatibility is handled by output.environment.module: false above
}
// Performance budgets
if (!isServer) {
config.performance = {
...config.performance,
maxEntrypointSize: 512000, // 500 KB
maxAssetSize: 307200, // 300 KB
hints: process.env.NODE_ENV === 'production' ? 'warning' : false,
}
}
// Ensure crypto module is available for server-side code
if (!isServer) {
config.resolve.fallback = {
...config.resolve.fallback,
crypto: false,
}
}
// Conservative bundle optimization
// Strategy: Split only the largest and most stable vendor libraries
// This reduces the main vendor bundle while avoiding edge runtime conflicts
// IMPORTANT: Only apply custom splitChunks in production mode
// Development mode uses Next.js default chunking to avoid ChunkLoadError
if (!dev && !isServer) {
config.optimization = {
...config.optimization,
splitChunks: {
...config.optimization?.splitChunks,
chunks: 'all',
maxInitialRequests: 25, // Conservative limit to avoid conflicts
maxAsyncRequests: 25,
minSize: 20000, // 20 KB minimum chunk size
// NO maxSize constraint - this was causing the edge-instrumentation.js conflict
cacheGroups: {
// === CORE FRAMEWORK CHUNKS (Priority: 30-35) ===
// React core - Foundation that rarely changes, cached long-term
react: {
test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
name: 'framework-react',
priority: 35,
reuseExistingChunk: true,
enforce: true,
},
// === UI LIBRARY CHUNKS (Priority: 20) ===
// Radix UI components - 100+ KB, changes with design system updates
radix: {
name: 'ui-libs',
priority: 20,
reuseExistingChunk: true,
},
// === STRATEGIC SPLITS FOR AI & UTILITIES (Priority: 21-22) ===
// AI packages - Split from vendor chunk for better caching
ai: {
test: /[\\/]node_modules[\\/](@google\/generative-ai|openai)[\\/]/,
name: 'vendor-ai',
priority: 22,
reuseExistingChunk: true,
},
// Utilities - JWT, CSV parsing, UUID, retry logic
utilities: {
test: /[\\/]node_modules[\\/](jose|papaparse|uuid|p-retry|seek-bzip)[\\/]/,
name: 'vendor-utils',
priority: 21,
reuseExistingChunk: true,
},
// === STRATEGIC SPLITS FOR LARGEST LIBRARIES (Priority: 16-18) ===
// Supabase client - 150+ KB, changes with backend updates
supabase: {
test: /[\\/]node_modules[\\/](@supabase)[\\/]/,
name: 'vendor-supabase',
priority: 18,
reuseExistingChunk: true,
},
// Stripe - Payment processing, large library
stripe: {
test: /[\\/]node_modules[\\/](stripe|@stripe)[\\/]/,
name: 'vendor-stripe',
priority: 17,
reuseExistingChunk: true,
},
// Charts and visualization - D3, Recharts
charts: {
test: /[\\/]node_modules[\\/](recharts|d3|d3-.*)[\\/]/,
name: 'vendor-charts',
priority: 16,
reuseExistingChunk: true,
},
// === ADDITIONAL VENDOR SPLITS (Priority: 11-19) ===
// Authentication (Priority: 19)
// Note: @clerk/nextjs is externalized via serverExternalPackages, so this only affects client-side bundling
clerk: {
test: /[\\/]node_modules[\\/](@clerk)[\\/]/,
name: 'vendor-clerk',
priority: 19,
reuseExistingChunk: true,
},
// Monitoring (Priority: 15)
sentry: {
test: /[\\/]node_modules[\\/](@sentry)[\\/]/,
name: 'vendor-sentry',
priority: 15,
reuseExistingChunk: true,
enforce: true,
},
// Animations (Priority: 14)
// Split Framer Motion separately for better caching and lazy loading
// This works with LazyMotion for optimal bundle size
framerMotion: {
test: /[\\/]node_modules[\\/]framer-motion[\\/]/,
name: 'framer-motion',
priority: 14,
reuseExistingChunk: true,
enforce: true, // Ensure Framer Motion is always split
},
// Other animation libraries
animations: {
test: /[\\/]node_modules[\\/](motion-dom|@motionone)[\\/]/,
name: 'vendor-animations',
priority: 13,
reuseExistingChunk: true,
},
// Icons (Priority: 12)
icons: {
test: /[\\/]node_modules[\\/](lucide-react)[\\/]/,
name: 'vendor-icons',
priority: 12,
reuseExistingChunk: true,
},
// UI Utilities (Priority: 11)
uiUtils: {
test: /[\\/]node_modules[\\/](react-window|react-virtualized-auto-sizer|swr|@floating-ui)[\\/]/,
name: 'vendor-ui-utils',
priority: 11,
reuseExistingChunk: true,
},
// Redux (Priority: 10)
redux: {
test: /[\\/]node_modules[\\/](@reduxjs|redux|react-redux|reselect)[\\/]/,
name: 'vendor-redux',
priority: 10,
reuseExistingChunk: true,
},
// === DEFAULT VENDORS (Priority: -10) ===
// Catch-all for remaining node_modules
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true,
name: 'vendor',
},
// Default group for app code
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
// Production-only optimizations
...(config.mode === 'production'
? {
usedExports: true,
sideEffects: true,
minimize: true,
// Additional tree-shaking optimizations
providedExports: true,
concatenateModules: true,
}
: {}),
}
}
return config
},
// Compiler optimizations
compiler: {
removeConsole:
process.env.NODE_ENV === 'production'
? {
exclude: ['error', 'warn'],
}
: false,
},
// Image optimization for judge profiles and court images
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '*.supabase.co',
},
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
{
protocol: 'https',
hostname: 'courtlistener.com',
},
{
protocol: 'https',
hostname: 'www.courtlistener.com',
},
],
formats: ['image/avif', 'image/webp'],
minimumCacheTTL: 86400, // 24 hours cache for profile images
dangerouslyAllowSVG: false,
},
// Enhanced security and performance headers
async headers() {
return [
{
// Global security headers for all pages
source: '/:path*',
headers: [
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'Permissions-Policy', value: 'geolocation=(), microphone=(), camera=(), payment=(), usb=()' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
],
},
{
source: '/api/:path*',
headers: [
{
key: 'Access-Control-Allow-Origin',
value:
process.env.NODE_ENV === 'production'
? process.env.NEXT_PUBLIC_SITE_URL || '*'
: process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3005',
},
{
key: 'Access-Control-Allow-Methods',
value: 'GET,HEAD,POST,OPTIONS',
},
{
key: 'Access-Control-Allow-Headers',
value: 'Content-Type,Authorization,X-Requested-With',
},
{
key: 'X-Robots-Tag',
value: 'noindex, nofollow',
},
// Prevent MIME type sniffing attacks - forces browsers to respect declared content-type
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
// Prevent clickjacking attacks - blocks API endpoints from being embedded in iframes
{
key: 'X-Frame-Options',
value: 'DENY',
},
// Legacy XSS protection for older browsers - blocks page rendering on XSS detection
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
],
},
// Cache headers are handled by middleware.ts for proper SEO and performance
// Static assets get long-term caching
{
source: '/(.*)\\.(css|js|ico|png|jpg|jpeg|gif|svg|woff|woff2)$',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
],
},
{
source: '/analytics',
headers: [
{
key: 'Cache-Control',
value: 'no-store',
},
],
},
// CRITICAL: Prevent CDN caching for dynamic routes with query parameters
// Without this, Netlify CDN serves cached page 1 HTML for all /judges?page=N requests
{
source: '/judges',
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=0, must-revalidate, s-maxage=0',
},
{
key: 'X-Robots-Tag',
value: 'index, follow',
},
],
},
]
},
// Redirects for content consolidation
async redirects() {
return [
// Help system consolidation - redirect old paths to new unified /help
{
source: '/help-center',
destination: '/help',
permanent: true, // 301 redirect
},
{
source: '/help-center/getting-started',
destination: '/help#getting-started',
permanent: true, // 301 redirect
},
{
source: '/help-center/features',
destination: '/help#features',
permanent: true, // 301 redirect
},
{
source: '/help-center/for-attorneys',
destination: '/attorneys/resources',
permanent: true, // 301 redirect
},
{
source: '/help-center/troubleshooting',
destination: '/help#troubleshooting',
permanent: true, // 301 redirect
},
{
source: '/help-center/how-to-find-my-judge',
destination: '/help#faq-finding-judge',
permanent: true, // 301 redirect
},
{
source: '/help-center/compare-judges-in-orange-county',
destination: '/help#features',
permanent: true, // 301 redirect
},
{
source: '/help-center/what-to-expect-la-county-superior-court',
destination: '/help#faq-court-preparation',
permanent: true, // 301 redirect
},
// FAQ redirects - redirect to help center with anchors
{
source: '/faq',
destination: '/help#faq',
permanent: true, // 301 redirect
},
{
source: '/faq/how-to-find-judge',
destination: '/help#faq-finding-judge',
permanent: true, // 301 redirect
},
{
source: '/faq/judge-bias',
destination: '/help#faq-judicial-bias',
permanent: true, // 301 redirect
},
{
source: '/faq/court-preparation',
destination: '/help#faq-court-preparation',
permanent: true, // 301 redirect
},
{
source: '/faq/using-judgefinder',
destination: '/help#faq-using-judgefinder',
permanent: true, // 301 redirect
},
// Attorney section consolidation redirects
{
source: '/for-attorneys',
destination: '/attorneys/resources',
permanent: true, // 301 redirect
},
{
source: '/attorneys/preparation',
destination: '/attorneys/guide#workflow',
permanent: true, // 301 redirect
},
{
source: '/attorneys/insights',
destination: '/attorneys/guide#analytics',
permanent: true, // 301 redirect
},
{
source: '/attorneys/sponsor',
destination: '/advertise',
permanent: true, // 301 redirect
},
]
},
// Enable static optimization for better SEO
trailingSlash: false,
generateEtags: true,
poweredByHeader: false,
// Optimize for deployment
// Netlify handles output automatically via @netlify/plugin-nextjs
// DO NOT use output: 'standalone' - that's for self-hosting (Docker/VPS), not Netlify
// Build debugging and logging
onDemandEntries: {
// period (in ms) where the server will keep pages in the buffer
maxInactiveAge: 25 * 1000,
// number of pages that should be kept simultaneously without being disposed
pagesBufferLength: 2,
},
// Log build progress
logging: {
fetches: {
fullUrl: true,
},
},
}
// Sentry configuration - disable automatic instrumentation to prevent build errors with Next.js 15
const sentryWebpackPluginOptions = {
// For all available options, see:
// https://github.com/getsentry/sentry-webpack-plugin#options
// Suppresses source map uploading logs during build
silent: true,
// Disable automatic instrumentation that causes conflicts with App Router
autoInstrumentServerFunctions: false,
hideSourceMaps: true,
// Disable injecting custom error pages that conflict with Next.js 15
widenClientFileUpload: false,
}
// Export with Sentry configuration and optional bundle analyzer
// Re-enabled after fixing 503 error (was column name mismatch, not Sentry issue)
const configWithSentry = process.env.SENTRY_DSN
? withSentryConfig(nextConfig, sentryWebpackPluginOptions)
: nextConfig
module.exports = withBundleAnalyzer(configWithSentry)