# How to set a cookie with Response Entity in Spring Boot

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 3, 2019, updated Sep 25, 2022. Topics: Spring Boot.
Canonical URL: https://attacomsian.com/blog/set-cookie-with-response-entity-in-spring-boot

> Learn how to set a cookie along with Response Entity in a Spring Boot application.

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:

```java
@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
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:

```javascript
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](https://attacomsian.com/blog/cookies-spring-boot) guide to find out more options for reading and writing cookies in Spring Boot.
