Cookies

Harpia provides a straightforward API to read, create, and delete cookies natively attached to the Request and Response objects.

Reading Cookies

You can read cookies sent by the client using the req.cookies object.

app.get("/welcome", (req, res) => {
  // Get a specific cookie by name
  const theme = req.cookies.get("theme");
  
  if (theme) {
    res.send(`Your preferred theme is ${theme}`);
  } else {
    res.send("Welcome! You have no theme preference.");
  }
});

To get all parsed cookies as a JavaScript object:

const allCookies = req.cookies.getAll();
console.log(allCookies); // { theme: "dark", session_id: "..." }

Setting Cookies

To send cookies back to the client, use the res.cookies.set() method.

app.post("/settings/theme", async (req, res) => {
  const body = await req.json();
  
  // Set a cookie named "theme"
  res.cookies.set("theme", body.theme, {
    maxAge: 31536000, // 1 year in seconds
    httpOnly: true,
    sameSite: "Lax"
  });
  
  res.send("Theme updated");
});

The third parameter of set and delete accepts an options object to configure the cookie’s behavior:

  • domain (string): Specifies the hosts to which the cookie will be sent.
  • path (string): Specifies the URL path that must exist in the requested URL for the browser to send the Cookie header.
  • maxAge (number): Indicates the number of seconds until the cookie expires.
  • expires (Date): Sets a specific expiration date.
  • httpOnly (boolean): If true, the cookie cannot be accessed through client-side scripts (e.g., document.cookie). This mitigates XSS attacks.
  • secure (boolean): If true, the cookie is only sent to the server when a request is made with the https: scheme.
  • sameSite ("Strict" | "Lax" | "None"): Controls whether the cookie is sent with cross-site requests.

Deleting Cookies

To remove a cookie from the client’s browser, use res.cookies.delete().

app.post("/logout", (req, res) => {
  // Deletes the cookie by setting its expiration date to the past
  res.cookies.delete("session_id", {
    path: "/" // Make sure the path and domain match the ones used when setting it
  });
  
  res.send("Logged out");
});

Scope Matching

When deleting a cookie, you must provide the exact same path and domain options that were used when the cookie was originally set. Otherwise, the browser might not delete it.