GuardAPI Logo
GuardAPI

Fix Improper Assets Management in Fastify

Improper Assets Management in Fastify typically occurs when developers expose sensitive directories via @fastify/static or fail to implement access controls on internal resources. This leads to information disclosure, where attackers can pull .env files, source code, or internal documentation. A hardened asset strategy requires strict path isolation, proper caching headers, and middleware-level authorization for non-public files.

The Vulnerable Pattern

const fastify = require('fastify')();
const path = require('path');

// VULNERABLE: Serving from the root directory exposes node_modules, .env, and source code fastify.register(require(‘@fastify/static’), { root: path.join(__dirname, ’./’), prefix: ‘/dist/’, });

fastify.listen({ port: 3000 });

The Secure Implementation

The fix involves three layers of defense. First, Path Isolation: the 'root' is restricted to a specific 'public' folder, preventing path traversal into sensitive project files. Second, Configuration Hardening: the 'dotfiles: deny' and 'index: false' options prevent attackers from discovering hidden configs or browsing the file system. Third, Programmatic Access Control: using a 'preHandler' hook ensures that sensitive assets aren't just 'security by obscurity' but are protected by the same authentication logic as your API routes.

const fastify = require('fastify')();
const path = require('path');

// SECURE: 1. Isolate assets to a dedicated directory // 2. Set strict security headers and caching fastify.register(require(‘@fastify/static’), { root: path.join(__dirname, ‘public’), prefix: ‘/assets/’, index: false, // Disable directory indexing list: false, // Prevent directory listing dotfiles: ‘deny’, // Explicitly deny hidden files (.env, .git) setHeaders: (res) => { res.setHeader(‘X-Content-Type-Options’, ‘nosniff’); res.setHeader(‘Cache-Control’, ‘public, max-age=31536000, immutable’); } });

// 3. Implement Auth Hook for sensitive assets fastify.addHook(‘preHandler’, async (request, reply) => { if (request.url.startsWith(‘/assets/internal/’) && !request.headers.authorization) { reply.code(403).send({ error: ‘Unauthorized Access’ }); } });

fastify.listen({ port: 3000 });

System Alert • ID: 3078
Target: Fastify API
Potential Vulnerability

Your Fastify API might be exposed to Improper Assets Management

74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.