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:
Option | Type |
---|---|
domain | string |
encode | (string) => string |
expires | Date |
httpOnly | boolean |
maxAge | number |
path | string |
sameSite | `boolean |
secure | boolean |
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: