Skip to content

Commit 36ceadc

Browse files
committed
Remove custom fallback handling for index.html, it is no longer necessary
1 parent 8be7633 commit 36ceadc

File tree

3 files changed

+27
-73
lines changed

3 files changed

+27
-73
lines changed

lib/fastify-static.ts

Lines changed: 6 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,18 @@
1-
import { FastifyInstance } from "fastify"
21
import fastifyStatic from "@fastify/static"
3-
import globby from "globby"
2+
import { FastifyInstance } from "fastify"
43
import path from "path"
54

6-
import { Config, StaticFallbacks } from "./types"
7-
8-
//
9-
// Unfortunately I couldn't make fastify-static add a fallback to /path/index.html when /path is requested.
10-
// Therefore this collects those fallbacks once on startup.
11-
//
12-
function collectFallbacks(staticDir: string) {
13-
const files = globby.sync("", { cwd: staticDir, onlyFiles: true })
14-
15-
const fallbacks = files.reduce((result, filename) => {
16-
if (!filename.includes("/")) {
17-
return result
18-
}
19-
if (!filename.endsWith(".html") && !filename.endsWith(".htm")) {
20-
return result
21-
}
22-
23-
const directory = path.dirname(filename)
24-
const url = "/" + directory
25-
26-
if (result[url]) {
27-
return result
28-
}
29-
30-
if (!result[directory]) {
31-
const fallbackDir = path.resolve(staticDir, directory)
32-
result["/" + directory] = fallbackDir
33-
}
34-
35-
return result
36-
}, {} as StaticFallbacks)
37-
38-
return fallbacks
39-
}
5+
import { Config } from "./types"
406

417
//
428
// https://github.com/fastify/fastify-static#fastify-static
439
//
4410
export function registerServeStatic(server: FastifyInstance, config: Config) {
45-
const fallbacks = collectFallbacks(config.staticDir)
46-
47-
server.setNotFoundHandler(async (req, res) => {
48-
const fallbackDir = fallbacks[req.url]
49-
if (fallbackDir) {
50-
res.sendFile("index.html", fallbackDir)
51-
} else {
52-
res.sendFile("index.html", config.staticDir)
53-
}
54-
})
55-
5611
server.register(fastifyStatic, {
5712
root: path.resolve(config.staticDir),
58-
extensions: ["html", "htm"],
13+
})
14+
15+
server.setNotFoundHandler(function (request, reply) {
16+
reply.sendFile("index.html")
5917
})
6018
}

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@
3131
"@fastify/static": "^6.11.2",
3232
"axios": "^1.5.0",
3333
"fastify": "^4.23.2",
34-
"globby": "^11.1.0",
3534
"nanoid": "^3.3.6",
3635
"ow": "^0.26.0"
3736
},

pnpm-lock.yaml

Lines changed: 21 additions & 24 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)