Deno logoDeno

Serving static assets

Note: to use this feature, you must link a GitHub repository to your project. URL deployments do not support static assets.

Deno Deploy supports the Deno.readFile API to read static assets from the file system. This is useful for serving static assets such as images, stylesheets, and JavaScript files. This guide demonstrates how to use this feature.

Imagine the following file structure on a GitHub repository:

├── mod.ts
└── style.css

The contents of mod.ts:

import { serve } from "https://deno.land/std@0.114.0/http/server.ts";

async function handleRequest(request: Request): Promise<Response> {
  const { pathname } = new URL(request.url);

  // This is how the server works:
  // 1. A request comes in for a specific asset.
  // 2. We read the asset from the file system.
  // 3. We send the asset back to the client.

  // Check if the request is for style.css.
  if (pathname.startsWith("/style.css")) {
    // Read the style.css file from the file system.
    const file = await Deno.readFile("./style.css");
    // Respond to the request with the style.css file.
    return new Response(file, {
      headers: {
        "content-type": "text/css",
      },
    });
  }

  return new Response(
    `<html>
      <head>
        <link rel="stylesheet" href="style.css" />
      </head>
      <body>
        <h1>Example</h1>
      </body>
    </html>`,
    {
      headers: {
        "content-type": "text/html; charset=utf-8",
      },
    },
  );
}

console.log("Listening on http://localhost:8000");
serve(handleRequest);

The path provided to the Deno.readFile API is relative to the root of the repository. You can also specify absolute paths, if they are inside Deno.cwd.