Features
Docs
CLI
Benchmarks
Examples

© 2024 MoroJs

Static Files

Serve static files with caching, ETags, and optimized headers for efficient asset delivery.

Basic Static File Serving

MoroJS provides built-in static file serving middleware with support for caching, ETags, and optimized headers.

Basic Static File Serving

typescript

1import { staticFiles } from '@morojs/moro';
2
3// Basic static file serving
4app.use(staticFiles({
5  root: './public',
6  maxAge: 3600000, // 1 hour
7  index: ['index.html', 'index.htm']
8}));
9
10// Files in ./public are now accessible
11// GET /styles.css -> ./public/styles.css
12// GET / -> ./public/index.html

Static File Features

  • • Automatic file serving from directory
  • • ETag support for cache validation
  • • Last-Modified headers
  • • Custom cache headers
  • • Directory index support
  • • Multiple static directories

Advanced Configuration

Advanced Static File Configuration

typescript

1import { staticFiles } from '@morojs/moro';
2
3// Advanced static file configuration
4app.use(staticFiles({
5  root: './public',
6  maxAge: 86400000, // 24 hours
7  etag: true, // Enable ETags
8  lastModified: true, // Enable Last-Modified headers
9  dotfiles: 'ignore', // 'allow' | 'deny' | 'ignore'
10  extensions: ['html', 'htm'], // Try these extensions
11  fallthrough: true, // Continue to next middleware if file not found
12  redirect: true, // Redirect to trailing slash for directories
13  setHeaders: (res, path, stat) => {
14    // Custom headers per file type
15    if (path.endsWith('.html')) {
16      res.setHeader('Cache-Control', 'no-cache');
17    } else if (path.endsWith('.css') || path.endsWith('.js')) {
18      res.setHeader('Cache-Control', 'public, max-age=31536000'); // 1 year
19    }
20  }
21}));
22
23// Multiple static directories
24app.use('/assets', staticFiles({ 
25  root: './assets',
26  maxAge: 31536000000 // 1 year
27}));
28
29app.use('/uploads', staticFiles({ 
30  root: './uploads',
31  maxAge: 0 // No cache
32}));

Best Practices

Do

  • • Use long cache times for static assets
  • • Enable ETags for cache validation
  • • Use CDN for production deployments
  • • Set appropriate cache headers
  • • Use versioned filenames for cache busting
  • • Organize files by type

Don't

  • • Serve sensitive files as static
  • • Use short cache times for assets
  • • Disable ETags unnecessarily
  • • Serve large files directly
  • • Allow directory listing
  • • Skip cache headers

Related Features