Jersey Set Cookie in REST API Response: How-To
In this article
Setting a cookie in a Jersey REST API response is a straightforward task once you know the right JAX-RS annotations and response types. This recipe shows you how to attach a `Set-Cookie` header to your HTTP response using Jersey's `NewCookie` class, which handles cookie attributes like expiry, path, and security flags automatically. It works with both JAX-RS 2.x and Jersey 2.x, and it's perfect for session tokens, user preferences, or any client-side state you need to persist.
Ingredients
- Jersey 2.x (or 3.x with Jakarta EE 9+) – 1 project dependency
- JAX-RS `Response` class – from `javax.ws.rs.core` (or `jakarta.ws.rs.core`)
- JAX-RS `NewCookie` class – from the same package
- Cookie name and value – e.g., `sessionId` and `abc123`
- Optional: cookie domain, path, max age (in seconds), secure flag, HTTP-only flag
- Java IDE or text editor – any
- Maven or Gradle – for dependency management
Instructions
- Add Jersey dependencies to your project. If using Maven, include `jersey-container-servlet-core` and `jersey-hk2` (or the equivalent for your setup) in your `pom.xml`. For Jersey 3.x, use the `jakarta.*` namespace.
- Create a resource class. Annotate it with `@Path("/api")` and `@Produces(MediaType.APPLICATION_JSON)`.
- Write a method that returns a `Response` object. For example, a login endpoint: `@POST @Path("/login")`.
- Build a `NewCookie` instance. Use the constructor: `new NewCookie("sessionId", "abc123", "/", null, "comment", 3600, false)`. The parameters are: name, value, path, domain, comment, maxAge (seconds), and secure flag. Set `maxAge` to `-1` for a session cookie (deleted when browser closes).
- Attach the cookie to the response. Use `Response.ok(yourJsonEntity).cookie(newCookie).build()`. The `.cookie()` method accepts one or more `NewCookie` objects. If you have multiple cookies, pass them as separate arguments.
- Return the response. Your method now returns a `Response` with the `Set-Cookie` header automatically added by Jersey.
- Test the endpoint. Use a REST client like Postman or curl. Check the response headers for `Set-Cookie: sessionId=abc123; Path=/; Max-Age=3600` (or similar).
Tips
- Use `NewCookie` instead of manually setting the header. While you could do `response.header("Set-Cookie", "name=value")`, `NewCookie` handles URL encoding, expiry formatting, and other attributes correctly. It also integrates with Jersey's response builder.
- Set the `HttpOnly` flag. To prevent JavaScript access (important for security), use the constructor with a `boolean httpOnly` parameter: `new NewCookie(name, value, path, domain, comment, maxAge, secure, httpOnly)`. In Jersey 2.x, this is available since version 2.22.
- Be careful with `maxAge`. A value of `0` deletes the cookie immediately. A negative value (like `-1`) means a session cookie that expires when the browser closes. Positive values are in seconds. Common choices: 3600 (1 hour), 86400 (1 day), 604800 (1 week).
- Cookie size limits. Browsers typically limit cookies to 4KB per cookie and 20 cookies per domain. Keep your cookie values small – use a token or ID, not large data.
Serving Suggestions
This recipe works best for authentication endpoints (login, OAuth token refresh), user preference endpoints (theme, language), or any API that needs to maintain client state. Pair it with a JSON response body containing user info or a success message. For example, after login, return `{"status":"success"}` plus the session cookie.
Variations
- Multiple cookies: Call `.cookie(cookie1, cookie2)` to set several cookies in one response.
- Cookie with domain: Pass a domain string (e.g., `.example.com`) to make the cookie available across subdomains.
- Secure flag: Set `secure=true` to only send the cookie over HTTPS. Do this in production.
- Using `Response` with a status code: Instead of `Response.ok()`, use `Response.status(Response.Status.CREATED).cookie(...).build()` for 201 responses.
Storage and Reheating
Cookies are stored client-side, not server-side. The server doesn't need to persist them. The `maxAge` attribute controls how long the browser keeps the cookie. For a session cookie (maxAge=-1), it lasts until the browser closes. For persistent cookies, the browser stores them until the expiry time. There's no 'reheating' – each request includes the cookie automatically if the path and domain match. If you need to invalidate a cookie, set a new cookie with the same name and `maxAge=0` to delete it.
Frequently Asked Questions
How do I read a cookie in a Jersey request?
Use `@CookieParam("sessionId") String sessionId` as a method parameter, or inject `HttpHeaders` and call `getCookies()`. Jersey automatically parses the `Cookie` header.
Can I set a cookie with a custom header name?
No, cookies must use the `Set-Cookie` header. But you can have multiple `Set-Cookie` headers (one per cookie) – Jersey's `.cookie()` method handles this.
What's the difference between `NewCookie` and `Cookie`?
`Cookie` is used to send a cookie from client to server (in requests). `NewCookie` is used to send a cookie from server to client (in responses). They are in the same package but serve different purposes.
Does Jersey automatically URL-encode cookie values?
Yes, Jersey encodes the cookie value when building the header. But it's safer to use values without special characters (like alphanumeric tokens) to avoid encoding issues.
Why is my cookie not being set in the browser?
Check the path and domain. If your API is at `/api`, and you set path to `/`, the cookie is sent to all paths. Also ensure the `SameSite` attribute is not blocking it – Jersey doesn't set `SameSite` by default, so you may need to add it manually via `.header("Set-Cookie", ...)` if needed.
Can I set a cookie in a response that returns a file or redirect?
Yes, the same `.cookie()` method works with any `Response` builder, including `Response.status(302).location(...).cookie(...)`. Just make sure to build the response correctly.