Elffuss BraidHub

kikocis/continue public

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