Enable Browser Caching in Spring Boot: Step-by-Step
In this article
Browser caching lets returning visitors load your Spring Boot web app faster by storing static resources (CSS, JS, images) locally. This reduces server load and improves page speed. To enable it, you configure Spring's resource handler to send Cache-Control and ETag headers. This guide covers the exact steps for both Spring Boot 2.x and 3.x.
What You'll Need
- A Spring Boot project (Maven or Gradle) with static files in
src/main/resources/static/ - Java 8 or later (for Spring Boot 2.x) or Java 17+ (for Spring Boot 3.x)
- Basic familiarity with
application.propertiesorapplication.yml
Step-by-Step
- Locate your static resources. Ensure your CSS, JavaScript, images, and other static files are under
src/main/resources/static/. Spring Boot serves them automatically at the root path (e.g.,/css/app.css). - Open your configuration file. Find
application.properties(orapplication.yml) insrc/main/resources/. - Add cache control properties. For Spring Boot 2.x and 3.x, add these lines to
application.properties:spring.web.resources.cache.cachecontrol.max-age=3600 spring.web.resources.cache.cachecontrol.cache-public=true
In YAML:spring: web: resources: cache: cachecontrol: max-age: 3600 cache-public: trueThis tells browsers to cache static resources for 1 hour (3600 seconds). Adjustmax-ageto your needs (e.g., 604800 for a week). - Enable ETag support (optional but recommended). ETags allow browsers to make conditional requests, saving bandwidth. Add:
spring.web.resources.cache.etag=true
In YAML:spring: web: resources: cache: etag: true - Configure cache for specific paths (advanced). If you want different cache durations per folder (e.g., images vs. HTML), create a
WebMvcConfigurerbean. In a class annotated with@Configuration, add:@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**") .addResourceLocations("classpath:/static/images/") .setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS).cachePublic()); registry.addResourceHandler("/css/**") .addResourceLocations("classpath:/static/css/") .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic()); } }Importorg.springframework.http.CacheControlandjava.util.concurrent.TimeUnit. - Rebuild and restart your application. Run
mvn spring-boot:runorgradle bootRunto apply changes. - Verify the headers. Open your browser's developer tools (F12), go to the Network tab, reload the page, and click on a static resource (e.g., a CSS file). Check the Response Headers for
Cache-Control: max-age=3600, publicandETagif enabled.
Common Mistakes
- Using wrong property names. In Spring Boot 2.6+, the property prefix changed from
spring.resourcestospring.web.resources. Using the old prefix silently fails. - Forgetting to set cache-public. Without
cache-public=true, some browsers/proxies may not cache resources that are not explicitly public. - Over-caching HTML pages. Static HTML files in
static/are also cached. If you update them, users may see old versions. Use a short max-age for HTML or exclude it from caching. - Not clearing browser cache while testing. After changing cache settings, hard-refresh (Ctrl+Shift+R) to bypass the old cache.
Tips
- Use versioned filenames. Append a version query string (e.g.,
app.css?v=2) or use content-based hashes in filenames. This lets you set a long max-age (e.g., 1 year) while still updating files when content changes. - Set a sensible default. For most static assets, 1 hour is safe; for images and fonts, 7 days is common. For versioned files, 365 days is fine.
- Combine with compression. Enable Gzip/Brotli in your server or Spring Boot (via server.compression.enabled=true) to further reduce transfer size.
- Test with different browsers. Chrome, Firefox, and Safari handle cache headers slightly differently; verify in at least two.
Troubleshooting
- Headers not appearing. Check that your
application.propertiesis actually loaded (look for typos). Also ensure you are not overriding the resource handler with a customWebMvcConfigurerthat doesn't set cache control. - Cache works but resources are stale. Increase the
max-age? No, the issue is likely that the browser cached an old version. Use versioned filenames or add a query string to force new requests. - ETag not working. ETag generation requires the resource handler to be set up correctly. If you use a custom handler, make sure to call
setCacheControl()and also enable ETag via.setEtag(true)on the resource handler registration. - Cache works in dev but not in production. If you're behind a proxy or CDN, they may strip or override cache headers. Check your reverse proxy configuration (e.g., Nginx, Apache) to ensure it respects
Cache-Controlfrom the backend.
Frequently Asked Questions
Does browser caching work for all static files automatically?
Yes, once you set the properties, all files served from classpath:/static/ get the cache headers. Files served by custom controllers (e.g., @RequestMapping returning a Resource) are not affected unless you add headers manually.
Can I set different cache times for different file types?
Yes, use a custom WebMvcConfigurer to register resource handlers per path pattern, as shown in Step 5.
What is the difference between cache-public and cache-private?
cache-public allows shared caches (like CDNs) to store the response. cache-private restricts caching to the user's browser only. For static assets, cache-public is usually appropriate.
Will browser caching affect API responses?
No, unless you explicitly add cache headers to API endpoints. The configuration here only applies to static resources served by the resource handler.
How do I clear the browser cache for testing?
In Chrome/Firefox, press Ctrl+Shift+R for a hard reload. For a full cache clear, open developer tools, right-click the refresh button, and select 'Empty Cache and Hard Reload'.
Does Spring Boot 3.x require a different setup?
No, the property names and configuration approach are identical in Spring Boot 3.x. Just ensure you're using Java 17+ and the correct dependency versions.