Examples

Handle Cookie

Use cookies to store data on the client.

Handling cookies with h3 is straightforward. There is three utilities to handle cookies:

  • setCookie to attach a cookie to the response.
  • getCookie to get a cookie from the request.
  • deleteCookie to clear a cookie from the response.

To set a cookie, you need to use setCookie in an event handler:

import { defineEventHandler, setCookie } from "h3";

app.use(
  defineEventHandler(async (event) => {
    setCookie(event, "name", "value", { maxAge: 60 * 60 * 24 * 7 });
  }),
);

In the options, you can configure the cookie flags:

  • maxAge to set the expiration date of the cookie in seconds.
  • expires to set the expiration date of the cookie in a Date object.
  • path to set the path of the cookie.
  • domain to set the domain of the cookie.
  • secure to set the Secure flag of the cookie.
  • httpOnly to set the HttpOnly flag of the cookie.
  • sameSite to set the SameSite flag of the cookie.
Read more in Utils.

To get a cookie, you need to use getCookie in an event handler.

import { defineEventHandler, getCookie } from "h3";

app.use(
  defineEventHandler(async (event) => {
    const name = getCookie(event, "name");

    // do something...
  }),
);

This will return the value of the cookie if it exists, or undefined otherwise.

To delete a cookie, you need to use deleteCookie in an event handler:

import { defineEventHandler, deleteCookie } from "h3";

app.use(
  defineEventHandler(async (event) => {
    deleteCookie(event, "name");
  }),
);

The utility deleteCookie is a wrapper around setCookie with the value set to "" and the maxAge set to 0.

This will erase the cookie from the client.