Global Key-Value Store.beta

Session Storage

Session Storage provides a session storage for workers at edge. It adds http Set-Cookie header to the response automatically, easy to use.

Example

import { serve } from "https://deno.land/std@0.160.0/http/server.ts";
import gokv from "https://deno.land/x/gokv@0.0.23/mod.ts";
import { checkPassword } from "./auth.ts";

serve((req) => {
  const url = new URL(req.url);
  try {
    const session = await gokv.Session<{ username: string }>(req, {
      namespace: "xxx",
    });
    switch (url.pathname) {
      case "/login":
        const form = await req.formData();
        const username = form.get("username");
        const password = form.get("password");
        if (checkPassword(username, password)) {
          // update the session store and redirect to dashboard
          return session.update({ username }, "/dash");
        }
        return new Response("Invalid username or password", { status: 400 });
      case "/logout":
        // logout and redirect to home page
        return session.end("/");
      default:
        if (session.store) {
          return new Response(`Logined as ${session.store.username}`);
        }
        return new Response("Please login");
    }
  } catch (e) {
    return new Response(e.message, { status: 500 });
  }
});

Try online: https://dash.deno.com/playground/gokv-session-example