0
0
Spring Bootframework~5 mins

Custom response headers in Spring Boot

Choose your learning style9 modes available
Introduction

Custom response headers let you add extra information to what your server sends back. This helps clients understand or handle the response better.

You want to tell the client about the type of content or version of your API.
You need to send security info like CORS policies or tokens.
You want to pass metadata like request IDs or timing info for debugging.
You want to control caching behavior for the client.
You want to add custom flags or messages for the client to read.
Syntax
Spring Boot
return ResponseEntity.ok()
    .header("Header-Name", "Header-Value")
    .body(responseBody);
Use ResponseEntity to build responses with custom headers easily.
You can add multiple headers by chaining .header() calls.
Examples
Adds a custom header named X-Custom-Header with value MyValue to the response.
Spring Boot
return ResponseEntity.ok()
    .header("X-Custom-Header", "MyValue")
    .body("Hello World");
Creates headers separately and adds them to the response.
Spring Boot
HttpHeaders headers = new HttpHeaders();
headers.add("X-Rate-Limit", "1000");
return ResponseEntity.ok()
    .headers(headers)
    .body("Data");
Sets a cache control header to tell clients not to cache the response.
Spring Boot
@GetMapping("/example")
public ResponseEntity<String> example() {
    return ResponseEntity.ok()
        .header("Cache-Control", "no-cache")
        .body("Cached data");
}
Sample Program

This Spring Boot controller has one endpoint /greet. It sends back a greeting message with a custom header X-Greeting set to HelloUser.

Spring Boot
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HeaderController {

    @GetMapping("/greet")
    public ResponseEntity<String> greet() {
        return ResponseEntity.ok()
            .header("X-Greeting", "HelloUser")
            .body("Welcome to our service!");
    }
}
OutputSuccess
Important Notes

Custom headers should use names that start with 'X-' or be clearly unique to avoid conflicts.

Headers are case-insensitive but it's good to keep consistent casing for readability.

Use ResponseEntity to control headers, status, and body together cleanly.

Summary

Custom response headers add extra info to server replies.

Use ResponseEntity in Spring Boot to add headers easily.

Headers help clients handle responses better and add metadata.