Elffuss BraidHub

kikocis/continue public

e31fcddb0dec 路 20.3 KiBRawPermalink
1---
2title: "Netlify Performance Optimization Cookbook"
3description: "Optimize web performance with A/B testing, automated monitoring, and data-driven improvements using Netlify MCP and Continue."
4sidebarTitle: "Using Netlify MCP for Performance Optimization"
5---
6
7<Card title="Ship Faster Code, Not Slower Sites" icon="gauge-high">
8 Use AI to automatically monitor performance metrics, run A/B tests between
9 branches, and get actionable optimization suggestions based on real user data
10 from Netlify Analytics
11</Card>
12
13<Info>
14 **Did You Know?** Netlify is more than just static hosting! It offers:
15 - [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches
16 - [Analytics](https://docs.netlify.com/analytics/get-started/) with Core Web Vitals tracking
17 - [Edge Functions](https://docs.netlify.com/edge-functions/overview/) for personalization at the edge
18 - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) ecosystem with 100+ integrations
19 - [Forms](https://docs.netlify.com/forms/setup/) with built-in spam protection
20 - [Identity](https://docs.netlify.com/visitor-access/identity/) for user authentication
21 - [Large Media](https://docs.netlify.com/large-media/overview/) for Git LFS support
22
23This guide shows you how to leverage these features through natural language with Continue CLI!
24
25</Info>
26
27## What You'll Learn
28
29This cookbook teaches you to:
30
31- Run [A/B tests](https://docs.netlify.com/site-deploys/split-testing/) between branches to measure performance impact
32- Monitor [Core Web Vitals](https://docs.netlify.com/analytics/get-started/#core-web-vitals) and build performance metrics
33- Automatically block deploys that degrade performance using [Deploy Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts)
34- Optimize build times with [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) and bundle sizes with AI assistance
35
36## Prerequisites
37
38- GitHub repository with a web project
39- [Netlify account](https://netlify.com) (free tier works)
40- Node.js 22+ installed (required for Netlify)
41- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`)
42- [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) configured
43- [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) (recommended)
44
45## Quick Setup
46
47<Steps>
48 <Step title="Install Continue CLI">
49 ```bash
50 npm i -g @continuedev/cli
51 ```
52 </Step>
53
54<Step title="Configure Netlify MCP">
55 1. Install Netlify CLI: `npm i -g netlify-cli` 2. Authenticate with Netlify:
56 `netlify login` 3. Visit [Netlify MCP on Continue
57 Hub](https://hub.continue.dev/netlify/netlify-mcp) 4. Follow the configuration
58 instructions for your editor
59</Step>
60
61 <Step title="Add Development Rules">
62 Install the [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) bundle for best practices:
63
64 1. Visit the bundle page on Continue Hub
65 2. Click **"Install Rules"**
66 3. Rules automatically apply to your agent
67
68 </Step>
69
70 <Step title="Verify Setup">
71 Test the connection with cn CLI:
72
73 ```bash
74 cn
75 # Then in TUI mode:
76 "Check my Netlify auth and list sites"
77 ```
78
79 </Step>
80</Steps>
81
82<Info>
83 The Netlify Development Rules bundle includes guardrails for: - Proper
84 `.gitignore` configuration - Function structure and placement - Edge function
85 constraints - Local development best practices
86</Info>
87
88## Performance Optimization Steps
89
90### Step 1: Baseline Performance Metrics
91
92Establish your current performance baseline using cn CLI:
93
94```bash
95# Start cn in TUI mode
96cn
97
98# Then ask:
99"Show my site's Core Web Vitals and build times"
100```
101
102<Tip>
103 **Test in Plan Mode First**: Before making performance optimizations that
104 might affect your site, test your prompts in plan mode (see the [Plan Mode
105 Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This
106 shows you what the agent will do without executing it. For example: `"Set up
107 A/B testing between main and feature branch with performance monitoring"`
108</Tip>
109
110<Info>
111
112 Netlify automatically tracks:
113 - **Build Performance**: Compile times, cache
114 hits
115 - **Runtime Performance**: Core Web Vitals, Time to Interactive
116 - **Resource Usage**: Bandwidth, function execution times
117
118</Info>
119
120### Step 2: A/B Test Branch Performance
121
122Compare performance between branches:
123
124```bash
125# In cn TUI mode:
126"Set up A/B test between main and feature branch on Netlify:
127- Split traffic 50/50 between branches
128- Track Core Web Vitals for each variant
129- Monitor conversion metrics and bounce rate
130- Enable analytics to measure performance impact
131- Configure cookie-based visitor persistence
132- Set test duration for 1000 unique visitors
133- Auto-conclude test when statistical significance reached
134Report winner based on performance + conversion metrics"
135```
136
137<Info>
138 **Enhanced Analytics**: Combine Netlify's A/B testing with PostHog session
139 recordings to understand not just which variant performs better, but why users
140 behave differently. See our [PostHog session analysis
141 guide](/guides/posthog-github-continuous-ai) to set up session tracking and
142 create a complete continuous AI analytics workflow.
143</Info>
144
145### Step 3: Advanced Build Optimization with Netlify
146
147Leverage Netlify's powerful build features to dramatically reduce build times:
148
149```bash
150# In cn TUI mode:
151"Optimize my Netlify build performance using these features:
152
1531. Enable Netlify Cache Plugin for dependency caching
154 - Configure @netlify/plugin-cache for node_modules
155 - Set up custom cache directories for .next/cache or .nuxt
156 - Enable Gatsby's incremental builds if applicable
157
1582. Set up Build Plugins from Netlify's ecosystem:
159 - Install @netlify/plugin-lighthouse for performance monitoring
160 - Add netlify-plugin-checklinks to prevent broken links
161 - Configure netlify-plugin-submit-sitemap for SEO
162
1633. Implement Conditional Builds:
164 - Skip builds when only docs change (ignore: /docs/**)
165 - Use build.ignore script for custom logic
166 - Set up monorepo-specific build triggers
167
1684. Configure concurrent builds for monorepos
169 - Set base directory per package
170 - Use pnpm workspaces or yarn workspaces
171
172Show me the netlify.toml configuration and explain each optimization"
173```
174
175<Info>
176 **Netlify Build Features You're Getting**:
177 - [Build Caching](https://docs.netlify.com/configure-builds/build-caching/) - Persist dependencies between builds
178 - [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) - Extend build process with 100+ plugins
179 - [Conditional Builds](https://docs.netlify.com/configure-builds/ignore-builds/) - Skip unnecessary builds
180 - [Monorepo Support](https://docs.netlify.com/configure-builds/monorepos/) - Optimize multi-package repos
181
182These features can reduce build times by 50-70% for most projects!
183
184</Info>
185
186<Tip>
187 **Discover more optimization prompts!** The Netlify community has documented dozens of build optimization strategies in their [Support Guide: How can I optimize my Netlify build time](https://answers.netlify.com/t/support-guide-how-can-i-optimize-my-netlify-build-time/3907).
188
189 Use this guide as inspiration for cn CLI prompts not covered in this cookbook, such as:
190 - `"Configure my builds to skip Dependabot PRs automatically"`
191 - `"Set up custom ignore patterns for documentation-only changes"`
192 - `"Optimize my Contentful webhooks to prevent duplicate builds"`
193 - `"Show me how to use build hooks instead of automatic git triggers"`
194 - `"Help me choose between Astro and Hugo based on build performance"`
195
196 The community guide contains real-world scenarios that you can turn into AI-assisted solutions - just describe what you want to achieve and let cn CLI handle the implementation!
197</Tip>
198
199### Step 4: Bundle Analysis with Netlify's Built-in Tools
200
201Use Netlify's bundle analyzer and optimization features:
202
203```bash
204# In cn TUI mode:
205"Analyze and optimize my bundle using Netlify's tools:
206
2071. Enable Netlify Bundle Analyzer:
208 - Add @netlify/plugin-bundle-analyzer to plugins
209 - Configure size thresholds in netlify.toml
210 - Generate visual bundle reports
211
2122. Set up Asset Optimization:
213 - Enable automatic JS minification
214 - Configure CSS optimization
215 - Turn on HTML minification
216 - Set up image processing pipeline
217
2183. Implement Smart Code Splitting:
219 - Analyze current chunks with the bundle analyzer
220 - Identify components over 50KB for splitting
221 - Configure webpack/vite for optimal chunking
222 - Set up route-based code splitting
223
2244. Configure Netlify's CDN for optimal delivery:
225 - Set cache headers for static assets
226 - Enable Brotli compression
227 - Configure edge caching rules
228
229Generate a full report with before/after bundle sizes"
230```
231
232<Card title="Netlify's Performance Arsenal" icon="rocket">
233
234 **Features Available Through Netlify MCP**:
235 - [Bundle
236 Analyzer](https://docs.netlify.com/configure-builds/build-plugins/bundle-analyzer/): Visualize your JavaScript bundles
237 - [Asset
238 Optimization](https://docs.netlify.com/configure-builds/post-processing/):
239 Automatic minification and compression
240 - [Edge
241 Network](https://docs.netlify.com/platform/edge-network/): Global CDN with
242 smart caching
243 - [Deploy
244 Previews](https://docs.netlify.com/site-deploys/deploy-previews/): Test
245 optimizations before production
246
247</Card>
248
249### Step 5: Image Optimization
250
251Optimize images for better performance:
252
253```bash
254# In cn TUI mode:
255"Set up Cloudinary image optimization for my Netlify site:
256- Install @cloudinary/netlify-plugin via MCP
257- Auto-convert images to WebP with fallbacks
258- Generate responsive sizes (320w, 640w, 1024w, 1920w)
259- Add lazy loading for all images
260- Configure blur-up placeholders
261- Update netlify.toml with Cloudinary settings
262Target: Reduce image payload by 60-80% and improve LCP"
263```
264
265## Continuous Performance Monitoring
266
267### Step 6: Performance Budget Enforcement with Lighthouse CI
268
269Set and enforce performance budgets with automated testing:
270
271```bash
272# In cn TUI mode:
273"Set up Lighthouse CI with performance budgets for my Netlify site:
274
275Requirements:
276- LCP must be < 2.5 seconds
277- JavaScript bundle must be < 200KB
278- Total size < 500KB
279- Performance score >= 90
280
281Setup needed:
2821. Install @lhci/cli and @netlify/plugin-lighthouse
2832. Create lighthouserc.js with these budget assertions
2843. Configure netlify.toml to run checks on all deploys
2854. Add GitHub status checks to block PRs that exceed budgets
2865. Create performance dashboard at /lighthouse-reports
287
288Please configure the complete Lighthouse CI setup with these budgets."
289```
290
291<Tip>
292 This comprehensive setup will automatically test every deploy preview and
293 production deployment, blocking any changes that violate your performance
294 budgets.
295</Tip>
296
297### Step 7: Real User Monitoring with Netlify Analytics
298
299Leverage Netlify's built-in analytics and integrate advanced RUM solutions:
300
301```bash
302# In cn TUI mode:
303"Set up comprehensive Real User Monitoring for my Netlify site:
304
3051. Configure Netlify Analytics Pro (requires Pro account):
306 - Set up server-side analytics (no JS required)
307 - Track Core Web Vitals (LCP, FID, CLS, INP)
308 - Monitor top pages by performance score
309 - Create custom performance alerts
310 - Configure weekly performance reports
311
3122. Integrate Web Vitals tracking:
313 - Install web-vitals library for detailed metrics
314 - Send metrics to Netlify Functions endpoint
315 - Store performance data in Netlify Blobs
316 - Create performance dashboard at /metrics
317
3183. Set up Performance Alerts:
319 - Alert when P75 LCP > 3 seconds
320 - Notify if CLS increases by 20%
321 - Monitor JavaScript error rates
322 - Track 404s and broken resources
323 - Send alerts to Slack via Netlify Functions
324
3254. Configure Geographic Performance Monitoring:
326 - Use Netlify Edge Functions to track region-specific metrics
327 - Identify slow regions with Edge geo data
328 - Compare performance across CDN nodes
329 - Optimize edge caching for slow regions
330
3315. Create Custom Performance Dashboard:
332 - Build dashboard page using Netlify Functions
333 - Display real-time Core Web Vitals
334 - Show performance trends over time
335 - Include browser and device breakdowns
336
337Show me the complete implementation with all code and configurations"
338```
339
340<Warning>
341 **Note**: Netlify Analytics Pro requires a paid Netlify Pro account ($19/month
342 per site). The prompt above assumes you have this plan. For free tier users,
343 focus on steps 2-5 which use Netlify Functions and Edge Functions to build
344 custom analytics.
345</Warning>
346
347<Info>
348 **Netlify Analytics Advantages**:
349 - [Server-side Analytics](https://docs.netlify.com/analytics/get-started/) - No client-side JavaScript needed
350 - [Core Web Vitals](https://docs.netlify.com/analytics/core-web-vitals/) - Automatic tracking of Google's metrics
351 - [Custom Metrics](https://docs.netlify.com/functions/logs/) - Track any metric via Functions
352 - [Edge Insights](https://docs.netlify.com/edge-functions/overview/#geolocation) - Geographic performance data
353 - [No Cookie Banner Required](https://docs.netlify.com/analytics/get-started/#privacy) - GDPR compliant by default
354
355Unlike Google Analytics, Netlify Analytics:
356
357- Doesn't slow down your site (server-side)
358- Captures 100% of traffic (no ad blockers)
359- Respects user privacy (no cookies)
360- Shows bot traffic separately
361</Info>
362
363<Tip>
364
365 **Pro Tip**
366 Combine Netlify Analytics with Edge Functions to create a
367 powerful RUM solution that:
368 - Tracks performance by user segment
369 - A/B tests
370 performance optimizations
371 - Personalizes content based on connection speed
372 - Automatically serves lighter assets to slow connections
373
374</Tip>
375
376## Automated Performance Checks
377
378### GitHub Actions Performance Guard
379
380Block PRs that degrade performance:
381
382```yaml
383name: Performance Check
384
385on:
386 pull_request:
387
388jobs:
389 performance:
390 runs-on: ubuntu-latest
391 steps:
392 - uses: actions/checkout@v4
393 - uses: actions/setup-node@v4
394 with:
395 node-version: "22"
396
397 - name: Deploy and Test Performance
398 id: perf
399 env:
400 NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
401 NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
402 run: |
403 npx @continuedev/cli@latest << 'EOF'
404 Deploy PR preview and run Lighthouse.
405 Compare scores with main branch.
406 Output JSON with score deltas.
407 EOF > performance.json
408
409 - name: Comment Performance Results
410 uses: actions/github-script@v7
411 with:
412 script: |
413 const fs = require('fs');
414 const perf = JSON.parse(fs.readFileSync('performance.json'));
415
416 const emoji = perf.score_delta < -10 ? '馃敶' :
417 perf.score_delta < 0 ? '馃煛' : '馃煝';
418
419 const comment = `## ${emoji} Performance Impact
420
421 | Metric | Main | PR | Delta |
422 |--------|------|----|---------|
423 | Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} |
424 | LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s |
425 | Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB |
426
427 ${perf.score_delta < -10 ? '鈿狅笍 **This PR significantly degrades performance. Please optimize before merging.**' : ''}
428
429 [View Full Report](${perf.report_url})`;
430
431 github.rest.issues.createComment({
432 issue_number: context.issue.number,
433 owner: context.repo.owner,
434 repo: context.repo.repo,
435 body: comment
436 });
437
438 // Fail check if performance degrades significantly
439 if (perf.score_delta < -10) {
440 core.setFailed('Performance degraded by more than 10 points');
441 }
442```
443
444<Warning>
445 This workflow will: - **Block merge** if performance score drops >10 points -
446 **Warn** on any performance regression - **Celebrate** improvements with green
447 indicators
448</Warning>
449
450## Performance Testing Locally
451
452### Step 8: Local Performance Testing
453
454Test performance before deploying:
455
456```bash
457# In cn TUI mode:
458"Run production build and measure bundle sizes"
459```
460
461### Step 9: Pre-commit Performance Checks
462
463Prevent performance regressions before they happen:
464
465```bash
466# In cn TUI mode:
467"Add pre-commit hooks for bundle size limits"
468```
469
470## Performance Troubleshooting
471
472### Debug Performance Issues
473
474Identify and fix performance bottlenecks:
475
476```bash
477# In cn TUI mode:
478"Why did my performance score drop?"
479```
480
481### Performance Issue Quick Fixes
482
483| Issue | Quick Fix Command (in cn TUI) |
484| ------------- | --------------------------------- |
485| Slow LCP | `"Preload critical resources"` |
486| High CLS | `"Add size attributes to images"` |
487| Large bundles | `"Implement code splitting"` |
488| Slow builds | `"Enable build caching"` |
489| Poor caching | `"Configure cache headers"` |
490
491## What You've Accomplished
492
493<Card title="Performance-First Development" icon="gauge-high">
494
495 You've built an AI-powered performance optimization system that:
496 - Automatically monitors Core Web Vitals
497 - Runs A/B tests between branches
498 - Blocks deployments that degrade performance
499 - Provides actionable optimization
500 suggestions
501
502</Card>
503
504## Discover Netlify's Hidden Performance Gems
505
506Features many developers don't know Netlify offers:
507
508<CardGroup cols={2}>
509 <Card title="Edge Functions" icon="bolt">
510
511 **[Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)**
512 - Run code at the edge, closer to users
513 - Transform responses on-the-fly
514 - A/B test at the edge level
515 - Personalize content without client-side JS
516
517 </Card>
518
519<Card title="Netlify Graph" icon="diagram-project">
520
521 **[Netlify Graph](https://docs.netlify.com/graph/overview/)**
522 - Unified GraphQL gateway for all your APIs
523 - Automatic TypeScript generation
524 - Built-in authentication handling
525 - Zero client-side API keys needed
526
527</Card>
528
529<Card title="On-Demand Builders" icon="hammer">
530 **[On-Demand
531 Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)** -
532 Generate pages only when requested - Cache dynamically generated content -
533 Perfect for large sites (10k+ pages) - Reduce build times dramatically
534</Card>
535
536 <Card title="Netlify Functions" icon="function">
537 **[Background Functions](https://docs.netlify.com/functions/background-functions/)**
538 - Run tasks up to 15 minutes
539 - Process webhooks asynchronously
540 - Handle heavy computations
541 - No timeout worries
542 </Card>
543</CardGroup>
544
545```bash
546# Try these advanced features in cn TUI mode:
547"Show me how to use Netlify Edge Functions for geo-based personalization"
548"Set up On-Demand Builders for my blog with 5000 posts"
549"Configure Background Functions for image processing"
550```
551
552## Performance Best Practices
553
554The Netlify Performance Rules enforce:
555
556<CardGroup cols={3}>
557 <Card title="Build Optimization" icon="hammer">
558 - Dependency caching enabled
559 - Parallel builds when possible
560 - Incremental compilation
561 - Smart cache invalidation
562 </Card>
563
564 <Card title="Runtime Performance" icon="bolt">
565 - Automatic image optimization
566 - Efficient resource hints (preload, prefetch)
567 - Optimal cache headers
568 - CDN configuration
569 </Card>
570
571 <Card title="Monitoring Standards" icon="chart-line">
572 - Performance budgets enforced
573 - Core Web Vitals tracking
574 - Real user monitoring
575 - Automated alerts
576 </Card>
577</CardGroup>
578
579## Advanced Performance Strategies
580
581### Progressive Enhancement
582
583```bash
584# In cn TUI mode:
585"Implement progressive enhancement with basic HTML first"
586```
587
588### Multi-variant Testing
589
590```bash
591# In cn TUI mode:
592"Test 3 bundle strategies and auto-select winner"
593```
594
595### Predictive Prefetching
596
597```bash
598# In cn TUI mode:
599"Analyze navigation patterns and prefetch next pages"
600```
601
602## Next Steps
603
604- Install [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) from Continue Hub
605- Set up [Performance Monitoring](https://docs.netlify.com/analytics/get-started/)
606- Configure [A/B Testing](https://docs.netlify.com/split-testing/overview/)
607- Join the [Continue Discord](https://discord.gg/continue) for support
608
609## Resources
610
611- [Netlify MCP on Continue Hub](https://hub.continue.dev/netlify/netlify-mcp)
612- [Core Web Vitals Guide](https://web.dev/vitals/)
613- [Netlify Analytics Documentation](https://docs.netlify.com/analytics/)
614- [Continue Performance Guides](https://docs.continue.dev/guides)