If you're looking for a practical example using the code snippet you provided, here is how you can implement reading and setting a cookie (as well as storing data in the context's state) using Oak. To test this code snippet, simply copy and paste it into a Deno Deploy playground or project:
import {
Application,
Context,
Middleware,
Router,
} from "https://deno.land/x/oak/mod.ts";
// Define the state structure for the server app
// It will store the last visited timestamp as a Date object
type State = {
lastVisit?: Date | undefined;
};
const cookieMiddleware: Middleware<
State,
Context<State, State>
> = async (ctx, next) => {
// Retrieve the value of the cookie, if it exists
const lastVisit = await ctx.cookies.get("last_visit");
// If the cookie exists, parse it as a Date and assign it to the context state
if (lastVisit) ctx.state.lastVisit = new Date(lastVisit);
// Update the cookie with the current timestamp
await ctx.cookies.set("last_visit", new Date().toISOString());
// Proceed with the next middleware
await next();
};
// Handle requests to the root path only
const router = new Router<State>()
.get("/", (ctx) => {
// Convert the last visit date on the state to a string, or set it to null if it doesn't exist
const lastVisit = ctx.state.lastVisit
? ctx.state.lastVisit.toISOString()
: null;
ctx.response.body = lastVisit
? `Welcome back. Your last visit was: ${lastVisit}`
: `Welcome. I haven't seen you before.`;
});
const app = new Application<State>()
.use(cookieMiddleware)
.use(router.routes())
.use(router.allowedMethods());
app.addEventListener("listen", ({ hostname, port, secure }) => {
console.log(`Listening at http${secure ? "s" : ""}://${hostname}:${port}/`);
});
await app.listen({ port: 8080 });