Spring Boot update the HTTP Headers of the static assets

Updated:

One of my applications runs in Azure Cloud using an App Service.

The App Service is easy to deploy (via GitHub) and monitor, but it's very limited in the configuration's options.

The application using Azure is public and the SEO is very important for this WebApp. After running Lighthouse and other tools to verify the most common errors and bad practices a couple of problems were connected directly to the deployment in Azure.

Update the HTTP Headers of the static assets

A recommendation from Google and SEO Tools is to add some cache information to the HTTP Headers to improve the loading performance of a page during future visits.

One of these options is to use Cache-Control on static assets. Usually, static assets don't change frequently and we can tell the browser to store them for e.g. a week.

We have a lot of options to add this header: proxy server (rewrite), application server, application.

Azure doesn't give us access to the server configuration and recommends rewriting the HTTP requests using their Azure Application Gateway.

We want to avoid additional layers and costs, for this reason we stick with our Spring Application features.

Spring has the possibility to integrate a Filter that updates every HTTP Response adding our Cache-Control value.

This solution is perfect for pages handled by Spring, our static resources (css, javascript etc.) are handled directly by the Embedded Tomcat provided by Spring.

Spring solved for us the problem with a property that we can use in our Application.properties:

spring.web.resources.cache.cachecontrol.max-age (from 2.6.0, in previous versions: spring.resources.cache.cachecontrol.max-age)

Example for 604800 seconds (1 week): spring.web.resources.cache.cachecontrol.max-age: 604800

This property adds the Cache-Control Header to our static assets automatically when they are sent to the client.

spring boot cache control

Extra: HTTP/2.0 configuration in Azure

The server was serving pages in HTTP/1.1 and not in HTTP/2.0, this was an issue according to Google Lighthouse.

By default, Azure uses HTTP/1.1 for App Service.

to use HTTP/2.0 you have to go into the 'Configuration' of your App Service and modify the HTTP Version from 1.1 to 2.0.

You can see the option in the following image:

configure azure for http/2.0


You could be interested in

Angular: Local proxy server to improve frontend development

Mix local and remote REST answers to speed up frontend dev
2019-11-08
Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).