Content Delivery
CDN Integration
Integrate with CDN providers like CloudFront and Cloudflare for efficient asset delivery and cache management.
Basic CDN Integration
MoroJS provides built-in CDN integration middleware with support for CloudFront and Cloudflare.
CloudFront Integrationtypescript
1import { middleware } from '@morojs/moro';
2
3// CloudFront integration
4app.use(middleware.cdn({
5 provider: 'cloudfront',
6 config: {
7 distributionId: 'E1234567890ABC',
8 region: 'us-east-1',
9 accessKeyId: process.env.AWS_ACCESS_KEY_ID,
10 secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
11 },
12 pathPrefix: '/assets',
13 invalidateOnChange: true
14}));
15
16// Purge cache
17app.post('/api/deploy', async (req, res) => {
18 await req.cdn.purge(['/assets/*']);
19 return { success: true };
20});Cloudflare Integrationtypescript
1import { middleware } from '@morojs/moro';
2
3// Cloudflare integration
4app.use(middleware.cdn({
5 provider: 'cloudflare',
6 config: {
7 zoneId: process.env.CLOUDFLARE_ZONE_ID,
8 apiKey: process.env.CLOUDFLARE_API_KEY,
9 email: process.env.CLOUDFLARE_EMAIL
10 }
11}));
12
13// Purge cache
14app.post('/api/deploy', async (req, res) => {
15 await req.cdn.purge(['/assets/*', '/css/*', '/js/*']);
16 return { success: true };
17});CDN Features
- Support for CloudFront and Cloudflare
- Automatic cache invalidation
- Manual cache purging
- Path prefix configuration
- Asset URL generation
- Cache management
Best Practices
Do
- Use CDN for static assets
- Purge cache on deployments
- Use versioned filenames
- Configure appropriate TTLs
- Monitor CDN performance
- Use path prefixes for organization
Don't
- Cache dynamic content
- Skip cache invalidation
- Use CDN for sensitive data
- Ignore CDN errors
- Set very short TTLs
- Purge entire cache unnecessarily