How to set a cookie with Response Entity in Spring Boot

A web cookie is a small piece of data stored by the server in the user's browser to track user behavior, facilitate session management, and more. The cookie is sent to the client browser while returning the response for an HTTP request.

Here is an example that shows how to set a cookie while sending back ResponseEntity as a response for a RESTful web service:

@GetMapping("/login")
@ResponseBody
public ResponseEntity<?> login(@RequestBody String credentials, HttpServletResponse response) {

    // create a cookie
    Cookie cookie = new Cookie("platform","mobile");

    // expires in 7 days
    cookie.setMaxAge(7 * 24 * 60 * 60);

    // optional properties
    cookie.setSecure(true);
    cookie.setHttpOnly(true);
    cookie.setPath("/");

    // add cookie to response
    response.addCookie(cookie);

    // TODO: add your login logic here
    String jwtToken = "NOT_AVAILABLE";

    // return response entity
    return new ResponseEntity<>(jwtToken, HttpStatus.OK);
}

The above code uses HttpServletResponse to add a cookie to the response. Here are what the response headers look like:

HTTP/1.1 200
Set-Cookie: platform=mobile; Max-Age=604800; Expires=Sat, 10-Aug-2019 12:14:41 GMT; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 13
Date: Sat, 03 Aug 2019 12:14:41 GMT

Another way is to add the cookie as a raw Set-Cookie header while building the ResponseEntity object:

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","platform=mobile; Max-Age=604800; Path=/; Secure; HttpOnly");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();

Read how to use cookies in Spring Boot guide to find out more options for reading and writing cookies in Spring Boot.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.