Cookies

You can use @routex/cookies for cookies.

Install

yarn add @routex/cookies
# or
npm add @routex/cookies

Usage

Setup your app:

const { Routex, TextBody } = require("routex");
const cookies = require("@routex/cookies");
const port = process.env.PORT || 3000;
const app = new Routex();
app.use(cookies());
app.get("/", (ctx) => {
const name = ctx.cookies.get("name");
if (!name) {
ctx.cookies.set("name", "john");
}
return new TextBody("Set name cookie");
});
app.listen(port).then(() => console.log(`Listening on ${port}`));

Get

You can use ctx.cookies.get(cookie) or ctx.cookies.all to get cookies:

app.get("/a", (ctx) => {
const name = ctx.cookies.get("name");
});
app.get("/b", (ctx) => {
const { name } = ctx.cookies.all;
});

Set

You can use ctx.cookies.set(cookie, value) set cookies:

app.get("/", (ctx) => {
ctx.cookies.set("name", "john");
});

You may also pass options (see link for more details) as a third parameters:

OptionType
domainstring
encode(string) => string
expiresDate
httpOnlyboolean
maxAgenumber
pathstring
sameSite`boolean
secureboolean

Remove

You can use ctx.cookies.remove(cookie) remove cookies:

app.get("/remove", (ctx) => {
ctx.cookies.remove("name");
});

Options

You may also pass options to the cookies() middleware:

  • parse:

    OptionType
    decode(string) => string
  • serialize:

    OptionType
    domainstring
    encode(string) => string
    expiresDate
    httpOnlyboolean
    maxAgenumber
    pathstring
    sameSite`boolean
    secureboolean