Skip to content

Commit

Permalink
Add Vary header for Hx-Requests
Browse files Browse the repository at this point in the history
The HTMX docs recommend doing this to avoid issues with caches
returning partial results.
  • Loading branch information
dsyer committed Apr 10, 2024
1 parent 4d790c1 commit 86ed3a5
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.lang.reflect.Method;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

Expand All @@ -23,11 +24,16 @@ public boolean preHandle(HttpServletRequest request,
Method method = ((HandlerMethod) handler).getMethod();
setHxTrigger(response, method);
setHxRefresh(response, method);
setVary(response, method);
}

return true;
}

private void setVary(HttpServletResponse response, Method method) {
response.addHeader(HttpHeaders.VARY, HtmxRequestHeader.HX_REQUEST.getValue());
}

private void setHxTrigger(HttpServletResponse response, Method method) {
HxTrigger methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, HxTrigger.class);
if (methodAnnotation != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.collection.IsIterableContainingInRelativeOrder.containsInRelativeOrder;

@WebMvcTest(TestController.class)
@WithMockUser
Expand Down Expand Up @@ -59,6 +60,13 @@ public void testAnnotationCompositionWithAliasFor() throws Exception {
.andExpect(header().string("HX-Trigger", "updateTrigger"));
}

@Test
public void testVary() throws Exception {
mockMvc.perform(get("/hx-vary"))
.andExpect(status().isOk())
.andExpect(header().stringValues("Vary", containsInRelativeOrder("HX-Request")));
}

@Test
public void testHxRefresh() throws Exception {
mockMvc.perform(get("/hx-refresh"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,10 @@ public String hxRefresh() {
return "";
}

@GetMapping("/hx-vary")
@ResponseBody
public String hxVary() {
return "";
}

}

0 comments on commit 86ed3a5

Please sign in to comment.