In a current project, components show information for an authenticated user, meaning this content is dynamic. As a page is cached on the first render, this means that content is no longer dynamic as it always shows the information of the authenticated user at the time of caching.

Possible Solutions

The dispatcher support authentication, however we were dealing with authentication that was not integrated into AEM.

Listing all the pages that contains this component and exclude them from caching by the dispatcher is also not the way the go because you then need an exhaustive list of pages containing this component. This also means whenever authors create a new page with this component, you also need to update the dispatcher configuration.

Finally I stumbled upon this slidedeck of the AEM Dispatcher Gems meeting by adobe. Slide 13 contains which headers on the response forbids caching.

Header Header Value
Cache-Control no-cache
Pragma no-cache
Dispatcher no-cache

An Implementation

In this case I injected the response object into my sling model, and added the header in the @PostConstructmethod, for instance like this.

public class MySlingModel {

    // other fields
    @inject
    private SlingHttpResponse response;


    @PostConstruct
    public void init() {

        // other initializations
        response.setHeader("Cache-Control", "no-cache");
    }
}

If you need to do this for multiple components, then you might considering moving this logic to a service, and inject this service for each component that requires caching to be disabled, and finally call the service method responsible for disabling the caching.