Cookies
Use cookies to store data on the client.
Handling cookies with H3 is straightforward. There is three utilities to handle cookies:
setCookieto attach a cookie to the response.getCookieto get a cookie from the request.deleteCookieto clear a cookie from the response.
Set a Cookie
To set a cookie, you need to use setCookie in an event handler:
import { setCookie } from "h3";
app.use(async (event) => {
setCookie(event, "name", "value", { maxAge: 60 * 60 * 24 * 7 });
return "";
});
In the options, you can configure the cookie flags:
maxAgeto set the expiration date of the cookie in seconds.expiresto set the expiration date of the cookie in aDateobject.pathto set the path of the cookie.domainto set the domain of the cookie.secureto set theSecureflag of the cookie.httpOnlyto set theHttpOnlyflag of the cookie.sameSiteto set theSameSiteflag of the cookie.
Get a Cookie
To get a cookie, you need to use getCookie in an event handler.
import { getCookie } from "h3";
app.use(async (event) => {
const name = getCookie(event, "name");
// do something...
return "";
});
This will return the value of the cookie if it exists, or undefined otherwise.
Delete a Cookie
To delete a cookie, you need to use deleteCookie in an event handler:
import { deleteCookie } from "h3";
app.use(async (event) => {
deleteCookie(event, "name");
return "";
});
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.