unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability

Home Page:https://h3.unjs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[QUESTION] Static Asset Catch All

go4cas opened this issue · comments

Describe the change

I am using this example (from the docs) to serve static assets (mainly .hmtl files):

import { createApp, defineEventHandler, serveStatic } from "h3";
import { stat, readFile } from "node:fs/promises";
import { join } from "pathe";

export const app = createApp();

const publicDir = "public";

app.use(
  defineEventHandler((event) => {
    return serveStatic(event, {
      getContents: (id) => readFile(join(publicDir, id)),
      getMeta: async (id) => {
        const stats = await stat(join(publicDir, id)).catch(() => {});

        if (!stats || !stats.isFile()) {
          return;
        }

        return {
          size: stats.size,
          mtime: stats.mtimeMs,
        };
      },
    });
  }),
);

This works well. However, I would like a catch all for routes that do not exist, to redirect to index.html. How would I go about that?

URLs

No response

Additional information

  • Would you be willing to help?

@go4cas This is a minimal implementation

import { createApp, defineEventHandler, serveStatic } from "h3";
import { readFile, stat } from "node:fs/promises";
import { join } from "pathe";

export const app = createApp();

const publicDir = "public";

app.use(
  defineEventHandler(async (event) => {
    const result = await serveStatic(event, {
      fallthrough: true,
      getContents: (id) => readFile(join(publicDir, id)),
      getMeta: async (id) => {
        const stats = await stat(join(publicDir, id)).catch(() => {});

        if (!stats || !stats.isFile()) {
          return;
        }

        return {
          size: stats.size,
          mtime: stats.mtimeMs,
        };
      },
    });

    if (result === false) {
      return readFile(join(publicDir, "index.html"), "utf8");
    }
  }),
);