title: How can I set a cookie along with the ResponseEntity using Java Spring
body: <p>There are three code snippets below. A cookie does not show up in the browser with the first two approaches. A cookie does show up in the browser with the last approach but I am looking for an approach that lets me send an arbitrary response object (like TestResponse), not just a file.</p>
  
  <p>Maybe another difference to note is that I'm sending an async request using the whatwg-fetch.js library for the first two snippets but hitting the route via browser refresh in the last snippet. I need the cookie to be set by the time an async request completes.</p>
  
  <p><strong>(Snippet 1)The below code snippet does not work as the cookie does not show up in the browser.</strong></p>
  
  <pre><code>@PostMapping(value="/test")
  public ResponseEntity&lt;TestResponse&gt; test(@RequestBody TestReq 
      testReq, HttpServletRequest req, HttpServletResponse res){
  
      String testMessage = testReq.getTestMessage();
  
      TestResponse testResponse = new TestResponse();
      testResponse.setTestMessage(testMessage);
  
      HttpHeaders headers = new HttpHeaders();
      headers.add("Set-Cookie", "key="+"value");
  
      ResponseEntity&lt;TestResponse&gt; testResponseEntity
          = new ResponseEntity&lt;TestResponse&gt;(testResponse, headers, HttpStatus.OK);
  
      return testResponseEntity;
  
  }
  </code></pre>
  
  <p><strong>(Snippet 2) This next code snippet also does not work as the cookie does not show up in the browser.</strong></p>
  
  <pre><code>@PostMapping(value="/test")
  public ResponseEntity&lt;TestResponse&gt; test(@RequestBody TestReq 
      testReq, HttpServletRequest req, HttpServletResponse res){
  
      String testMessage = testReq.getTestMessage();
  
      TestResponse testResponse = new TestResponse();
      testResponse.setTestMessage(testMessage);
  
      ResponseEntity&lt;TestResponse&gt; testResponseEntity
          = new ResponseEntity&lt;TestResponse&gt;(testResponse, HttpStatus.OK);
  
      Cookie c = new Cookie("key", "value");
      res.addCookie(c);
  
      return testResponseEntity;
  
  }
  </code></pre>
  
  <p><strong>(Snippet 3) The following code works. The cookie shows up in my browser when I load localhost.</strong></p>
  
  <pre><code>@GetMapping(value="/")
  public String home(HttpServletRequest req, HttpServletResponse res){
      Cookie c = new Cookie("key","value");
      res.addCookie(c);
      return "views/app.html;
  }
  </code></pre>