tracking for shynet analytics when Javascript is disabled Optimize SvelteKit performance with brotli compression — Hugo Sum
Hugo Sum

Optimize SvelteKit performance with brotli compression

In my post of building Docker image for static SvelteKit application with nginx, I have covered almost everything, except serving brotli compressed assets. brotli generally compress files better than traditional gzip.

Today I want to share how to optimize SvelteKit’s performance with brotli compression, and serve those pre-compressed assets with nginx.

Enable pre-compression in SvelteKit

As we are building a static site, we can compress all our assets with brotli during the build time. To enable pre-compression, you need to set precompress: true in your adapter.

svelte.config.js
import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  kit: {
    adapter: adapter({
      precompress: true
    }),
  },
};

export default config;

Enable brotli support in nginx

By default, nginx does not support brotli compression, and it won’t serve pre-compressed brotli assets as well. To enable that, you have to install ngx_brotli module.

Luckily there is a Docker image with ngx_brotli pre-installed. We are going to modify our Docker image that build SvelteKit with static adapter and serve with nginx, and use that image.

Dockerfile
# omitted for brevity
FROM base AS prerelease
COPY --from=install /temp/dev/node_modules node_modules
COPY . .

ENV NODE_ENV=production
RUN npm run build

# the nginx Docker image with brotli modules installed
FROM KiweeEu/nginx-brotli AS release
COPY --from=prerelease --chown=nginx:nginx /usr/src/app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]

And finally we just need to allow nginx to serve brotli compressed content, by modifying nginx.conf.

nginx.conf
# load the ngx_brotli module
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;

server {
    # some usual nginx config
    listen 8080;
    listen [::]:8080;
    root /usr/share/nginx/html;
    server_name _;
    try_files $uri $uri.html $uri/ =404;

    brotli_static on; # allow serving brotli compressed files 
}

Hugo Sum

A Hongkonger living in the UK. The only thing I know is there is so much I don't know.

Enjoy reading my blog?

Subscribe to a monthly newsletter and join my adventure on software development.

© 2025 Hugo Sum. All Rights Reserved.