Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/3.config/0.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,10 @@ The `dir` option is where your files live on your file system; the `baseURL` opt

### `compressPublicAssets`

- Default: `{ gzip: false, brotli: false }`{lang=ts}
- Default: `{ gzip: false, brotli: false, zstd: false }`{lang=ts}

If enabled, Nitro will generate a pre-compressed (gzip and/or brotli) version of supported types of public assets and prerendered routes
larger than 1024 bytes into the public directory. The best compression level is used. Using this option you can support zero overhead asset compression without using a CDN.
If enabled, Nitro will generate a pre-compressed (gzip, brotli, and/or zstd) version of supported types of public assets and prerendered routes
larger than 1024 bytes into the public directory. Default compression levels are used. Using this option you can support zero overhead asset compression without using a CDN.

List of compressible MIME types:

Expand Down
4 changes: 3 additions & 1 deletion src/build/virtual/public-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default function publicAssets(nitro: Nitro) {
const { errors } = await runParallel(
new Set(files),
async (id) => {
let mimeType = mime.getType(id.replace(/\.(gz|br)$/, "")) || "text/plain";
let mimeType = mime.getType(id.replace(/\.(gz|br|zst)$/, "")) || "text/plain";
if (mimeType.startsWith("text")) {
mimeType += "; charset=utf-8";
}
Expand All @@ -54,6 +54,8 @@ export default function publicAssets(nitro: Nitro) {
encoding = "gzip";
} else if (id.endsWith(".br")) {
encoding = "br";
} else if (id.endsWith(".zst")) {
encoding = "zstd";
}

assets[assetId] = {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/internal/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getAsset, isPublicAssetURL, readAsset } from "#nitro/virtual/public-ass

const METHODS = new Set(["HEAD", "GET"] as HTTPMethod[]);

const EncodingMap = { gzip: ".gz", br: ".br" } as const;
const EncodingMap = { gzip: ".gz", br: ".br", zstd: ".zst" } as const;

export default defineHandler((event) => {
if (event.req.method && !METHODS.has(event.req.method as HTTPMethod)) {
Expand Down
1 change: 1 addition & 0 deletions src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ export interface PublicAssetDir {
export interface CompressOptions {
gzip?: boolean;
brotli?: boolean;
zstd?: boolean;
}

// Server assets
Expand Down
42 changes: 32 additions & 10 deletions src/utils/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,38 @@ import mime from "mime";
import type { Nitro } from "nitro/types";
import { resolve } from "pathe";

const EncodingMap = { gzip: ".gz", br: ".br", zstd: ".zst" } as const;

export async function compressPublicAssets(nitro: Nitro) {
const publicFiles = await glob("**", {
cwd: nitro.options.output.publicDir,
absolute: false,
dot: true,
ignore: ["**/*.gz", "**/*.br"],
ignore: ["**/*.gz", "**/*.br", "**/*.zst"],
});

await Promise.all(
publicFiles.map(async (fileName) => {
const compressPublicAssets = nitro.options.compressPublicAssets;
if (compressPublicAssets === false) {
return;
}

const {
gzip = false,
brotli = false,
zstd = false,
} = compressPublicAssets === true
? { gzip: true, brotli: true, zstd: true }
: compressPublicAssets;
const zstdSupported = zlib.zstdCompress !== undefined;
const filePath = resolve(nitro.options.output.publicDir, fileName);

if (existsSync(filePath + ".gz") || existsSync(filePath + ".br")) {
if (
(gzip && existsSync(filePath + EncodingMap.gzip)) ||
(brotli && existsSync(filePath + EncodingMap.br)) ||
(zstd && zstdSupported && existsSync(filePath + EncodingMap.zstd))
) {
return;
}

Expand All @@ -33,32 +52,35 @@ export async function compressPublicAssets(nitro: Nitro) {
return;
}

const { gzip, brotli } = nitro.options.compressPublicAssets || ({} as any);

const encodings = [gzip !== false && "gzip", brotli !== false && "br"].filter(Boolean);
const encodings = [
gzip && ("gzip" as const),
brotli && ("br" as const),
zstd && zstdSupported && ("zstd" as const),
].filter((v): v is keyof typeof EncodingMap => v !== false);

await Promise.all(
encodings.map(async (encoding) => {
const suffix = "." + (encoding === "gzip" ? "gz" : "br");
const suffix = EncodingMap[encoding];
const compressedPath = filePath + suffix;
if (existsSync(compressedPath)) {
return;
}
const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION };
const brotliOptions = {
[zlib.constants.BROTLI_PARAM_MODE]: isTextMime(mimeType)
? zlib.constants.BROTLI_MODE_TEXT
: zlib.constants.BROTLI_MODE_GENERIC,
[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_DEFAULT_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length,
};
const compressedBuff: Buffer = await new Promise((resolve, reject) => {
const cb = (error: Error | null, result: Buffer) =>
error ? reject(error) : resolve(result);
if (encoding === "gzip") {
zlib.gzip(fileContents, gzipOptions, cb);
} else {
zlib.gzip(fileContents, cb);
} else if (encoding === "br") {
zlib.brotliCompress(fileContents, brotliOptions, cb);
} else if (zstdSupported) {
zlib.zstdCompress(fileContents, cb);
}
});
await fsp.writeFile(compressedPath, compressedBuff);
Expand Down
4 changes: 4 additions & 0 deletions test/presets/cloudflare-pages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe.skipIf(isWindows)("nitro:preset:cloudflare-pages", async () => {
"/_openapi.json",
"/_openapi.json.br",
"/_openapi.json.gz",
"/_openapi.json.zst",
"/_scalar",
"/_swagger",
"/favicon.ico",
Expand All @@ -54,12 +55,15 @@ describe.skipIf(isWindows)("nitro:preset:cloudflare-pages", async () => {
"/prerender-custom",
"/_scalar/index.html.br",
"/_scalar/index.html.gz",
"/_scalar/index.html.zst",
"/_swagger/index.html.br",
"/_swagger/index.html.gz",
"/_swagger/index.html.zst",
"/api/hello",
"/api/hey",
"/prerender/index.html.br",
"/prerender/index.html.gz",
"/prerender/index.html.zst",
"/api/param/foo.json",
"/api/param/hidden",
"/api/param/prerender1",
Expand Down
Loading