Skip to content
当前有符合你浏览器所设置语言的版本,是否前往zh-CN版本的网站?
There is a version suitable for your browser's language settings. Would you like to go to the zh-CN language of the site?
HomeDocument

Static

H1

Sometimes we hope that the frontend and backend can be deployed together. This way, under one domain name, we can provide webpage access while offering services.

This feature currently supports Bun. For other runtimes, feel free to submit a PR to make Milkio compatible.

Installation

Terminal window
bun i milkio-static

Then use it:

/milkio.ts
import { createMilkioApp } from "milkio";
import { milkioStatic } from "milkio-static";
export const milkio = createMilkioApp({
middlewares: () => [
milkioStatic()
],
});

Create a /public directory, now, all assets under this directory will be served by the static service. Write a greeting webpage!

/public/index.html
<!DOCTYPE html>
<html>
<body>Hello World!</body>
</html>

Visit http://localhost:9000/, and you’ll see this webpage.

Page Not Found

When the page is not found, the static service will return a 404 status code and display your /public/404.html.

If this file does not exist, then the default JSON result will be displayed.

Configuration

You can edit the default values of the static service by passing in parameters.

milkioStatic({
assets: 'static', // Default: 'public'
index: 'main.html', // Default: 'index.html'
notFound: 'not-found.html', // Default: '404.html'
headers: { 'X-Foo': 'bar' } // Default: {}
})

Caching

Setting a good caching strategy can effectively reduce the load on your website.

By default, for statically accessed assets, they will be cached for 30 minutes by adding the Cache-Control header. If you want to change this duration, you can do it like this:

milkioStatic({
headers: { 'Cache-Control': 'public, max-age=3600' }
})

Of course, a more effective way is to use CDN services to cache your static resources. For example, Cloudflare.