0

When attempting to set cookies in oak, the cookies property of the context is never changed and the value is always returned undefined even when using the example in their docs.

app.use(async ctx => {
    try {
        const lastVisit = await ctx.cookies.get('lastVisit')
        console.log(lastVisit)
        await ctx.cookies.set('lastVisit', new Date().toISOString())
        if (lastVisit) {
            console.log(`Welcome back. You were last here at ${lastVisit}.`)
        } else {
            console.log(`Welcome, I haven't seen your before.`)
        }
    } catch (error) {
        console.error(error)
    }
})

Am I not accessing the cookies the correct way?

Ray Kochenderfer
  • 333
  • 1
  • 6
  • 15

1 Answers1

0

Here's an example based on the code you shared which shows how to read and set a cookie (and also store data in the context's state) using Oak. You can simply copy + paste into a playground or project on Deno Deploy to try it:

import {
  Application,
  type Context,
  type Middleware,
  Router,
} from "https://deno.land/x/oak@v10.5.1/mod.ts";

// The shape of the state for this server app
// It can hold the last visited timestamp as a Date object
type State = {
  lastVisit?: Date | undefined;
};

const cookieMiddleWare: Middleware<
  State,
  Context<State, State>
> = async (ctx, next) => {
  // Get cookie value (if it exists)
  const lastVisit = await ctx.cookies.get("last_visit");
  // If it does, parse as a Date and set 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());
  // Continue with next middleware
  await next();
};

// Handle visits to the root path only
const router = new Router<State>()
  .get("/", (ctx) => {
    // If the last visit date is on the state, stringify it
    // else set it to null
    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 });

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • This works when I hit the API directly using something like VSCode Rest but when I try the API through my frontend, using solidjs on chrome, it does not save the cookie.My CORS is setup like this ```ts app.use( oakCors({ origin: Deno.env.get('CORS_ORIGIN') || '*', allowedHeaders: ['Content-Type', 'Authorization', 'Accept'], }) ) ``` Do you know why this doesn't work ? I've also tried setting sameSite to false in the cookie options and it still does not work. – Ray Kochenderfer May 03 '22 at 03:29
  • @RayKochenderfer If you’re trying to debug another issue with your app configuration, that would be a separate question and you are welcome to [ask a new question](https://stackoverflow.com/questions/ask). – jsejcksn May 03 '22 at 10:07
  • I created a new question here https://stackoverflow.com/questions/72098907/deno-cookie-not-being-saved-in-browser – Ray Kochenderfer May 03 '22 at 12:17