DEV Community

John Winston
John Winston

Posted on

Optimize SvelteKit performance with brotli compression

In my post of building Docker image for static SvelteKit application with nginx, I have covered almost everything, with the exception of 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 supported in nginx.

Enable precompression in SvelteKit

As we are building a static site, we can compress all our assets during the build time. To enable precompression, 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 = {
  // omitted for brevity
  kit: {
    adapter: adapter({
      // omitted for brevity,
      precompress: true
    }),
  },
};

export default config;
Enter fullscreen mode Exit fullscreen mode

Enable brotli support in nginx

By default nginx does not support brotli compression. To enable that, you have to install ngx_brotli module.

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

# 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

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;"]
Enter fullscreen mode Exit fullscreen mode

And finally we just need to allow nginx to serve brotli compressed content, by modifying 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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)