### Configure AdonisJS Static Package Source: https://context7.com/adonisjs/static/llms.txt Automated configuration function for installing the @adonisjs/static package. It publishes configuration stubs, registers middleware, and updates the AdonisJS RC file. ```typescript // Run via AdonisJS CLI // node ace configure @adonisjs/static // The configure function performs these operations: // 1. Creates config/static.ts from stub template // 2. Registers middleware in start/kernel.ts // 3. Adds provider to adonisrc.ts // 4. Registers public/** as meta files // Generated config/static.ts: import { defineConfig } from '@adonisjs/static' const staticServerConfig = defineConfig({ enabled: true, etag: true, lastModified: true, dotFiles: 'ignore', }) export default staticServerConfig // Updated adonisrc.ts includes: // providers: [..., () => import('@adonisjs/static/static_provider')], // metaFiles: [{ pattern: 'public/**', reloadServer: false }] ``` -------------------------------- ### Implement Static File Serving with StaticMiddleware Source: https://context7.com/adonisjs/static/llms.txt The `StaticMiddleware` class handles static file serving by wrapping the `serve-static` package. It integrates with AdonisJS's HTTP context for proper header propagation and response streaming. Use it within an HTTP server to serve files from a specified public path, with a fallback callback for unmatched requests. ```typescript import { join } from 'node:path' import { createServer } from 'node:http' import { defineConfig } from '@adonisjs/static' import StaticMiddleware from '@adonisjs/static/static_middleware' import { RequestFactory, ResponseFactory, HttpContextFactory } from '@adonisjs/core/factories/http' // Create middleware instance const publicPath = join(process.cwd(), 'public') const config = defineConfig({ maxAge: 86400000, // 1 day in milliseconds etag: true, dotFiles: 'ignore', }) const staticMiddleware = new StaticMiddleware(publicPath, config) // Use in HTTP server const server = createServer(async (req, res) => { const request = new RequestFactory().merge({ req, res }).create() const response = new ResponseFactory().merge({ req, res }).create() const ctx = new HttpContextFactory().merge({ request, response }).create() // Set custom headers before serving ctx.response.header('X-Powered-By', 'AdonisJS') await staticMiddleware.handle(ctx, async () => { // Called when no static file matches - handle as normal route ctx.response.status(404).send('Not Found') ctx.response.finish() }) }) server.listen(3000) // GET /style.css -> Serves ./public/style.css with headers // GET /images/logo.png -> Serves ./public/images/logo.png // GET /nonexistent -> Returns 404 via next() callback ``` -------------------------------- ### Configure Static Assets with defineConfig Source: https://context7.com/adonisjs/static/llms.txt Use `defineConfig` to create a static assets configuration object. It merges user options with defaults, allowing customization of caching, security, and headers. Supports various options like `enabled`, `dotFiles`, `maxAge`, `immutable`, `acceptRanges`, `cacheControl`, and a custom `headers` callback. ```typescript import { defineConfig } from '@adonisjs/static' // Basic configuration with defaults const basicConfig = defineConfig({}) // Result: { enabled: true, dotFiles: 'ignore', etag: true, lastModified: true } // Full configuration with all options const fullConfig = defineConfig({ enabled: true, etag: true, lastModified: true, dotFiles: 'deny', // 'ignore' | 'allow' | 'deny' maxAge: '1d', // Cache duration: number (ms) or string ('1d', '2h', '30m') immutable: true, // Add immutable directive to Cache-Control acceptRanges: true, // Enable partial content requests (HTTP 206) cacheControl: true, // Enable Cache-Control header headers: (path, stats) => ({ 'X-Content-Length': stats.size.toString(), 'X-File-Path': path, 'X-Last-Modified': stats.mtime.toISOString(), }), }) export default fullConfig ``` -------------------------------- ### Configure Dotfiles Handling in Static Middleware Source: https://context7.com/adonisjs/static/llms.txt Configure how the middleware handles requests for dotfiles. Options are 'ignore' (404), 'allow' (serve normally), or 'deny' (403 Forbidden). ```typescript import { join } from 'node:path' import { defineConfig } from '@adonisjs/static' import StaticMiddleware from '@adonisjs/static/static_middleware' // Ignore dotfiles (default) - returns 404 for /.env, /.gitignore const ignoreConfig = defineConfig({ dotFiles: 'ignore' }) // Allow dotfiles - serves /.well-known/*, /.htaccess const allowConfig = defineConfig({ dotFiles: 'allow' }) // Use case: Serving Apple Pay domain verification files // GET /.well-known/apple-developer-merchantid-domain-association -> 200 OK // Deny dotfiles - returns 403 Forbidden const denyConfig = defineConfig({ dotFiles: 'deny' }) // GET /.env -> 403 Forbidden // Example: Allow .well-known directory for domain verification const middleware = new StaticMiddleware( join(process.cwd(), 'public'), defineConfig({ dotFiles: 'allow' }) ) // File structure: // public/ // .well-known/ // apple-developer-merchantid-domain-association // acme-challenge/ // token123 // style.css // Requests: // GET /style.css -> 200 OK // GET /.well-known/apple-developer-merchantid-domain-association -> 200 OK // GET /.well-known/acme-challenge/token123 -> 200 OK ``` -------------------------------- ### Register StaticProvider in AdonisJS Source: https://context7.com/adonisjs/static/llms.txt The `StaticProvider` integrates the `StaticMiddleware` into the AdonisJS IoC container. It reads configuration from `config/static.ts` and binds the middleware using the application's public path. Register the provider in `adonisrc.ts` and the middleware in `start/kernel.ts`. ```typescript // adonisrc.ts - Register the provider import { defineConfig } from '@adonisjs/core/app' export default defineConfig({ providers: [ () => import('@adonisjs/core/providers/app_provider'), () => import('@adonisjs/core/providers/http_provider'), () => import('@adonisjs/static/static_provider'), // Add static provider ], }) // config/static.ts - Define configuration import { defineConfig } from '@adonisjs/static' const staticServerConfig = defineConfig({ enabled: true, etag: true, lastModified: true, dotFiles: 'ignore', }) export default staticServerConfig // start/kernel.ts - Register middleware import router from '@adonisjs/core/services/router' router.use([ () => import('@adonisjs/static/static_middleware'), // Add as server middleware ]) // The provider automatically: // 1. Resolves app.publicPath() (typically './public') // 2. Reads config from 'config/static.ts' // 3. Creates StaticMiddleware singleton in container ``` -------------------------------- ### AssetsConfig Type for Static Middleware Source: https://context7.com/adonisjs/static/llms.txt Defines the TypeScript interface for all configuration options of the static middleware. Use this for type-safe configuration objects. ```typescript import type { AssetsConfig } from '@adonisjs/static/types' import type { Stats } from 'node:fs' // Type-safe configuration const config: AssetsConfig = { enabled: true, acceptRanges: true, // Enable HTTP 206 partial content cacheControl: true, // Enable Cache-Control header dotFiles: 'deny', // Reject dotfile requests with 403 etag: true, // Generate ETag headers lastModified: true, // Include Last-Modified header maxAge: '7d', // Cache for 7 days immutable: false, // Don't mark as immutable headers: (path: string, stats: Stats) => { const headers: Record = {} // Add security headers for specific file types if (path.endsWith('.js')) { headers['Content-Type'] = 'application/javascript; charset=utf-8' } if (path.endsWith('.css')) { headers['Content-Type'] = 'text/css; charset=utf-8' } // Add custom metadata headers['X-File-Size'] = stats.size.toString() headers['X-Served-At'] = new Date().toISOString() return headers }, } export default config ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.