Skip to content

Deno server.ts not resolves non assets static files #175

@GitonioDev

Description

@GitonioDev

Hi there, there is a problem with the server.ts file it does not resolves static files that are not in the assets folder, so assets are resolved correctly but all other are just passed to the handler and that's wrong my solution is:


import { serveFile } from "@std/http/file-server";
import { join } from "@std/path/join";
import { createRequestHandler } from "react-router";

const handleRequest = createRequestHandler(
  // @ts-expect-error - build output
  await import("./build/server/index.js"),
  "production",
);

Deno.serve(async (request) => {
  const pathname = new URL(request.url).pathname;

  try {
    const filePath = join("./build/client", pathname);
    const fileInfo = await Deno.stat(filePath);

    if (fileInfo.isDirectory) {
      throw new Deno.errors.NotFound();
    }

    const response = await serveFile(request, filePath, { fileInfo });

    if (pathname.startsWith("/assets/")) {
      response.headers.set(
        "cache-control",
        "public, max-age=31536000, immutable",
      );
    } else {
      response.headers.set("cache-control", "public, max-age=600");
    }

    return response;
  } catch (error) {
    if (!(error instanceof Deno.errors.NotFound)) {
      throw error;
    }
  }

  return handleRequest(request);
});

It adds better handling of static files
And adds a ts-expect-error for the import as the server build might not exists everytime

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions