NukeBase

Serving Static Files

Serve files from a local directory using app.serveStatic. This is typically the very next thing you'll register after addDomain — it powers your frontend, assets, and any other files the browser needs. Registers both GET and HEAD handlers automatically:

Basic static file serving
// Serve everything in ../public at the root
nukebase.app.serveStatic("/*", path.join(__dirname, "../public"));

// Serve a private directory (no auth callback = open access)
nukebase.app.serveStatic("/assets/*", path.join(__dirname, "assets"));
Parameter order: The serveStatic auth callback receives (res, req)res first, then req. This matches the underlying uWebSockets convention and is the opposite of Express.

Signature

app.serveStatic(routePattern, rootDir, auth?)

  • routePattern - URL pattern with trailing /* (e.g., "/*", "/admin/*"). The matched portion before /* is treated as the mount point and stripped before resolving against rootDir.
  • rootDir - Absolute path to the directory to serve from. Use path.join(__dirname, "...").
  • auth (optional) - Async callback returning a boolean. If provided, runs before any file is served. Return true to allow, false to respond with 401.

Auth Callback

The auth callback receives (res, req) — same convention as postWithBody:

Static files with authentication
// Only logged-in users can access /private/*
nukebase.app.serveStatic("/private/*", path.join(__dirname, "../private"),
  async (res, req) => {
    return Boolean(req.uid);
  }
);

// Admins only
nukebase.app.serveStatic("/admin/*", path.join(__dirname, "../admin"),
  async (res, req) => {
    return req.claims?.role === "admin";
  }
);

The req object passed to the auth callback contains the auth fields populated by checkAuth (uid, username, claims, cookies, urlParams, referer, userAgent, ip, url) plus host and method. Identity fields are present only when the user is authenticated. Returning a falsy value sends a 401 response automatically.

Behavior Details

  • Index files: Requests ending in / automatically serve index.html from that directory.
  • Path traversal protection: Any URL that resolves outside rootDir (e.g., via ../) returns 403 Forbidden.
  • Missing files: Return 404 Not Found.
  • Streaming: Files are streamed in 16KB chunks rather than buffered into memory — safe for large files.
  • Content-Type: Set automatically from the file extension via the mime package; falls back to application/octet-stream for unknown types.
  • Image caching: Files with image/* content types receive Cache-Control: public, max-age=31536000 (1 year). Other file types are served without cache headers.