abcdef38
abcdef3816mo ago

In Deno, what is the best way to simply host static websites?

What is the best way to simply host static/cached files? Without having to do a read file call every request. And would this work with Deno Deploy?
10 Replies
abcdef38
abcdef38OP16mo ago
Also how much can I optimise
Deno.serve((_req) => {
return new Response("Hello, World!");
})
Deno.serve((_req) => {
return new Response("Hello, World!");
})
, I want the highest possible requests/second.
abcdef38
abcdef38OP16mo ago
Thanks, but that is not really what I'm looking for. It doesn't do caching or anything like that. I'm better off implementing a system myself maybe. But what about getting the highest number of requests/second locally? Bun.serve can do 2x-3x the amount of requests/second, which can't be right.
abcdef38
abcdef38OP16mo ago
Homebrew Formulae
wrk
Homebrew’s package index
ioB
ioB16mo ago
it does do caching
abcdef38
abcdef38OP16mo ago
How?
import { serveDir, serveFile } from "https://deno.land/std@0.194.0/http/file_server.ts";
Deno.serve((req: Request) => {
const pathname = new URL(req.url).pathname;

if (pathname === "/simple_file") {
return serveFile(req, "./path/to/file.txt");
}

if (pathname.startsWith("/static")) {
return serveDir(req, {
fsRoot: "public",
urlRoot: "static",
});
}

return new Response("404: Not Found", {
status: 404,
});
});
import { serveDir, serveFile } from "https://deno.land/std@0.194.0/http/file_server.ts";
Deno.serve((req: Request) => {
const pathname = new URL(req.url).pathname;

if (pathname === "/simple_file") {
return serveFile(req, "./path/to/file.txt");
}

if (pathname.startsWith("/static")) {
return serveDir(req, {
fsRoot: "public",
urlRoot: "static",
});
}

return new Response("404: Not Found", {
status: 404,
});
});
ioB
ioB16mo ago
It sets the appropriate headers automatically to ensure that a browser will not download the same file twice Behind the scenes, serveDir and the CLI that https://deno.land/std/http/file_server.ts provides does the same thing, so you can't go wrong either way.
abcdef38
abcdef38OP16mo ago
That is not really the same thing, but okay. That's just status code 304.
ioB
ioB16mo ago
It's more complicated than that unfortunately. serveDir supports a bunch of caching headers, including https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
ETag - HTTP | MDN
The ETag (or entity tag) HTTP response header is an identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content was not changed. Additionally, etags help to prevent simultaneous updates of a resource from overwriting each othe...
abcdef38
abcdef38OP16mo ago
Oh, okay. But status 304 works. Well, I only know of it because I accidentally used it and all my code changes did nothing. It took me a while to realise this.

Did you find this page helpful?