Cookie Editor Utility
Parse/edit/generate Web Cookie strings. For more information on Cookies, see the Overview section. For code examples, see the Examples section.
Overview
Web cookies, often simply called "cookies," are small pieces of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to allow the server to retain state for the user that is persisted over time. They enable websites to keep track of stateful information (like items added to a shopping cart) or to record user browsing activity (such as logging in, clicking particular buttons, recording which pages were visited in the past, or user preferences).
Creation
- Server-Side: When you visit a website, the server can send a 
Set-Cookie header along with the HTTP response. This instructs the browser to store the cookie with the specified name and value. For example:Set-Cookie: sessionId=12345; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/
 - Client-Side: JavaScript running on a webpage can also create cookies. For instance, using the 
document.cookie property:document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
 
Storage
Cookies are stored locally on the user's device. Each browser will manage cookies a little differently, but generally, they are stored in a location specific to the particular browser on the user's hard drive. Cookies have attributes that determine their lifespan:
- Session Cookies: These are temporary and are deleted when the browser is closed. They do not have the "expires" attribute.
 - Persistent Cookies: These have an expiration date specified and will persist on the user'sdevice until that date.
 
Apart from expiration, cookies also contain other attributes like:
- Domain: Specifies which website the cookie belongs to.
 - Path: Determines the URL path the cookie is available to.
 - Secure: Indicates that the cookie should only be sent over HTTPS.
 - HttpOnly: Indicates that the cookie should not be accessible via JavaScript.
 
Transmission
After a cookie is set for a domain, every subsequent HTTP request made by the browser to that domain will include the cookie in the HTTP headers until the cookie expires or is deleted. This is how the server recognizes returning users or sessions.
For example, if a cookie has been set with the name "sessionId" and value "12345", the browser will automatically include it in the request headers for each request to the domain:
GET /somepage.html HTTP/1.1
Host: www.example.com
Cookie: sessionId=12345
If there are multiple cookies for the same site, they are transmitted as a single Cookie header in the HTTP request, with each key-value pair separated by a semicolon and space. For instance, if a site has set a"sessionId" cookie and a "username" cookie, the header might look something like this:
Cookie: sessionId=12345; username=JohnDoe
Summary
Complex websites or frameworks typically have complex cookies which can be difficult to parse and understand by the human eye. The Cookie Editor tool helps with the task by allowing users to paste in an entire cookie header value and parses it into an easy to understand table format. To understand how to interact with cookies in code, take a look at some of our Examples.
Examples
Java Servlet Cookie Read
@WebFilter(urlPatterns = "/*")
public class CookieAuthenticationFilter implements Filter {
    private AuthService authService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.authService = new AuthService(/* initialize AuthService here */);
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (httpRequest.getRequestURI().equals("/auth")) {
            chain.doFilter(request, response);
            return;
        }   
        
        // Find the Auth cookie
        String authToken = null;
        Cookie[] cookies = httpRequest.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("Authorization".equals(cookie.getName())) {
                    authToken = cookie.getValue();
                    break;
                }
            }
        }
        
        if (authToken != null) {
            // Validate and continue
            Authentication auth = authService.validateToken(authToken);
            if (auth != null) {
                // Continue chain, possibly set auth object in request context somewhere
                chain.doFilter(request, response);
                return;
            }
        }
        
        // Invalid token
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not Authorized");
    }
    
    @Override
    public void destroy() {
        // Cleanup resources (if any)
    }
}
HTTP Filter component that validates a token from a Cookie
Java Spring Cookie Read
@Component
@Order(Ordered.HIGHEST_PRECEDENCE);
public class CookieAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private AuthService authService;
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // Don't attempt to authorize if authenticating
        return request.getRequestURI().equals("/auth");
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String authToken = null;
    
        // Find the Auth cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("Authorization".equals(cookie.getName())) {
                    authToken = cookie.getValue();
                    break;
                }
            }
        }
        
        if (authToken != null) {
            // Validate and continue
            Authentication auth = authService.validateToken(authToken);
            if (auth != null) {
                // Set for spring security
                SecurityContextHolder.getContext().setAuthentication(auth);
                filterChain.doFilter(request, response);
                return;
            }
        }
        
        // Invalid token
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not Authorized");
    }
}
HTTP Filter component that validates a token from a Cookie
Java Servlet Cookie Write
@WebServlet("/auth")
public class AuthServlet extends HttpServlet {
    private AuthService authService;
    
    /* ... constructor and initialization ... */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Read request parameters
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String redirectPath = request.getParameter("redirect");
        if (redirectPath == null) {
            redirectPath = '/';
        }
        
        // Authorization request
        String authToken = authService.authenticate(username, password);
        if (authToken != null) {
            // Authorized
            response.setStatus(HttpServletResponse.SC_OK);
            // Create and add the cookie to the response
            Cookie authCookie = new Cookie("Authorization", authToken);
            authCookie.setPath("/");
            authCookie.setHttpOnly(true);
            authCookie.setSecure(true);
            response.addCookie(authCookie);
            
            // Redirect to original path
            response.sendRedirect(redirectURL);
        } else {
            // Not authorized
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Username/Password");
        }
    }
}
Authorization servlet that sets token as cookie upon success
Java Spring Cookie Write
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class AuthController {
    @Autowired
    private AuthService authService;
    @PostMapping("/auth")
    public ResponseEntity authenticate(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam(value = "redirect", required = false) String redirectPath) {
        
        String authToken = authService.authenticate(username, password);
        HttpHeaders headers = new HttpHeaders();
        if (authToken != null) {
            // Authorized, create and add the cookie to the response
            headers.add("Set-Cookie", "Authorization=" + authToken + "; Path=/; HttpOnly; Secure");
            headers.setLocation(redirectPath);
            return new ResponseEntity<>(headers, HttpStatus.FOUND);
        } else {
            // Not Authorized 
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Not Authorized");
        }
    }
}
Authorization controller that sets token as cookie upon success
Typescript Document Cookie Read
type Cookies = { readonly [key: string]: string };
function readCookies(): Cookies {
  const cookies: { [key: string]: string } = {};
  // Cookie is in format key1=value1;key2=value2;...
  const cookieKeyValues = document.cookie.split(';');
  for (const cookie of cookieKeyValues) {
    const [key, value] = cookie.split('=');
    // keys/values should be uri encoded, so decode when reading
    cookies[decodeURIComponent(key)] = decodeURIComponent(value);
  }
  return cookies;
}
Parses all cookies on the document into a key/value object
Typescript js-cookie Read/Write
import * as Cookies from "js-cookie";
interface Cookie {
  readonly name: string;
  readonly value: string;
  readonly expiration?: Date;
  readonly path?: string;
  readonly domain?: string;
  readonly secure?: boolean;
}
const cookies = Cookies
    // Add default attributes
    .withAttributes({path: '/', domain: '.mydomain.com', secure: true, expiration: 7})
    // Add converters to encode/decode values automatically
    .withConverter({
      read: (value, name) => {
        return decodeURIComponent(value);
      }
      write: (value, name) => {
        return encodeURIComponent(value);
      }
    });
// Export functions to wrap cookie access library to allow for swapping of library used
export type Cookies = { readonly [key: string]: string };
export function readCookie(name: string) {
  return cookies.get(name);
}
export function readCookies(): Cookies {
  return cookies.get();
}
export function writeCookie(cookie: Cookie) {
  // extract, key/value/expiration and remaining attrs
  const { name, value, expiration, ...attrs } = cookie;
  cookies.set(name, value, {
    expires,
    ...attrs
  });
}
export function clearCookie(name: string) {
  cookies.remove(name);
}
Exposes functions to read/write cookies using the js-cookie library internally
Typescript Document Cookie Write
interface Cookie {
  readonly key: string;
  readonly value: string;
  readonly expiration?: Date;
  readonly path?: string;
  readonly domain?: string;
  readonly secure?: boolean;
}
function writeCookie(cookie: Cookie) {
  // Encode key/value required for cookies
  let cookieString = `${encodeURIComponent(cookie.key)}=${encodeURIComponent(
  cookie.value,
)}`;
  if (cookie.expiration) {
    cookieString += '; expires=' + cookie.expiration.toUTCString();
  }
  if (cookie.path) {
    cookieString += '; path=' + cookie.path;
  }
  if (cookie.domain) {
    cookieString += '; domain=' + cookie.domain;
  }
  if (cookie.secure) {
    cookieString += '; secure';
  }
  // Setting the cookie on the document cookie stores a new cookie or overwrites one of same key
  document.cookie = cookieString;
}
Takes an object representation of a cookie and stores it to the document
Typescript js-cookie Read/Write
import * as Cookies from "js-cookie";
interface Cookie {
  readonly name: string;
  readonly value: string;
  readonly expiration?: Date;
  readonly path?: string;
  readonly domain?: string;
  readonly secure?: boolean;
}
const cookies = Cookies
    // Add default attributes
    .withAttributes({path: '/', domain: '.mydomain.com', secure: true, expiration: 7})
    // Add converters to encode/decode values automatically
    .withConverter({
      read: (value, name) => {
        return decodeURIComponent(value);
      }
      write: (value, name) => {
        return encodeURIComponent(value);
      }
    });
// Export functions to wrap cookie access library to allow for swapping of library used
export type Cookies = { readonly [key: string]: string };
export function readCookie(name: string) {
  return cookies.get(name);
}
export function readCookies(): Cookies {
  return cookies.get();
}
export function writeCookie(cookie: Cookie) {
  // extract, key/value/expiration and remaining attrs
  const { name, value, expiration, ...attrs } = cookie;
  cookies.set(name, value, {
    expires,
    ...attrs
  });
}
export function clearCookie(name: string) {
  cookies.remove(name);
}
Exposes functions to read/write cookies using the js-cookie library internally
import express from 'express';
import cookieParser from 'cookie-parser';
const app = express();
app.use(cookieParser());
app.get('/some-endpoint', (req, res) => {
  const cookieVal = req.cookies['some_cookie'];
  
  if (!cookieVal) {
    // Send a 400 Bad Request response if the cookie is not set
    return res.status(400).json({ error: 'some_cookie cookie is not set' });
  } else {
    return res.status(200).json({ value: cookieVal });
  }
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
Adds an api endpoint to the express.js app that reads a cookie value
This code requires the installation of cookie-parser in order to expose access to server-side cookies to the express.js app.
import express from 'express';
const app = express();
// POST to /some-endpoint writes cookie
app.post('/some-endpoint', (req, res) => {
  const cookieVal = req.body['some_cookie'];
  
  if (!cookieVal) {
    // Send a 400 Bad Request response if the cookie is not set
    return res.status(400).json({ error: 'some_cookie is not set on request' });
  } else {
    // write cookie and expire cookie 7 days from now
    res.cookie('some_cookie', cookieVal, {expires: new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000)});
    return res.status(200);
  }
});
// DELETE to /some-endpoint clears cookie
app.delete('/some-endpoint', (req, res) => {
  res.clearCookie('some_cookie');
  return res.status(200);
});
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
Adds an api endpoint to the express.js app that writes a cookie value
Choose from the options above to view an example.