Issue with setting context.cookies in Deno oak v10.5.1 not resolved

When I try to set cookies in oak, the cookies property of the context doesn't seem to update and always returns undefined. This happens even when following the example provided in their documentation.

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 you before.`)
        }
    } catch (error) {
        console.error(error)
    }
})

Could it be that I'm not accessing the cookies correctly?

Answer №1

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 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to add mp3 files to a Vue/TypeScript application, a "Module not found" error is triggered

I am encountering an error while trying to import .mp3 files into my Vue/Typescript app. Upon running 'npm serve', I am presented with the following message: ERROR in /Users/***/***/application/src/components/Sampler.vue(80,16): 80:16 Cannot fin ...

What is the best way to save a Map for future use in different components?

Let's say I define an enum like this: export enum SomeEnum { SomeLongName = 1, AnotherName = 2 } Within my display components, I'm utilizing an enum map to translate the enum values into strings for presentation on the web app: enumMap = new Map ...

I want to know the best way to send latitude and longitude coordinates from an external source in order to generate a

Looking for advice on customizing a working code that uses leaflet angular to place markers with predefined latitudes and longitudes. I want to be able to customize this by passing latitudes and longitudes when the addmarker button is pr ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

What could be the reason for the react hook form failing to capture the data upon submission?

I am struggling to access the props' value after clicking the button, as it keeps returning undefined. My goal is to display the years of service and profession details based on the user's selection. return ( <form onSubmit={handleSubmit(o ...

No output when using Typescript 2.0

Recently, I've been working on a project in VS 2015 update 3 and just integrated Typescript 2.0. Initially, I encountered a lot of errors and had to go through a trial and error process to resolve them. Now, all the errors have been fixed but I' ...

Store Angular 17 control flow in a variable for easy access and manipulation

Many of us are familiar with the trick of "storing the conditional variable in a variable" using *ngIf="assertType(item) as renamedItem" to assign a type to a variable. This technique has always been quite useful for me, as shown in this example: <ng-t ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...

Data retrieval from DynamoDB DocumentClient does not occur following a put operation

I am currently working on testing a lambda function using the serverless framework in conjunction with the sls offline command. The purpose of this lambda is to connect to my local DynamoDB, which has been initialized with a docker-compose image, and inser ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

Establishing a server in Node.js alongside an Angular 2 frontend by harnessing the power of Typescript

I'm looking to deploy my web application on IBM Bluemix with Angular 2 using Typescript for the frontend and Node.js for the backend. Can you advise me on how to configure the server, connect it to the frontend, and specify which transpiler I should u ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

The power of Typescript shines in its ability to ensure type safety when working with conditional

I am struggling with typing a simple function in Typescript that takes a union type and a boolean as parameters. Here is the code snippet: type A = 'a' | 'A'; function f(a: A, b: boolean): string { if (b) { switch (a) { ...

Limiting the height of a grid item in MaterialUI to be no taller than another grid item

How can I create a grid with 4 items where the fourth item is taller than the others, determining the overall height of the grid? Is it possible to limit the height of the fourth item (h4) to match the height of the first item (h1) so that h4 = Grid height ...