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

The file is missing the required fields in the Firestore document

I've been facing a challenge while attempting to update specific fields within a firebase document. Even though the cloud function triggers and performs an upload on the document, the values of the fields I am trying to update never seem to get upload ...

Utilizing a syntax highlighter in combination with tsx React markdown allows for cleaner

I'm currently looking at the React Markdown library on Github and attempting to incorporate SyntaxHighlighter into my markdown code snippets. When I try to implement the example code within a function used for rendering posts, I encounter the error de ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

Using a single Material Autocomplete input to handle two values within Angular

Looking to implement a search feature using Material's autocomplete that can filter by either user name or user ID. The current implementation is partially functional in this Stackblitz. When selecting a user name from the autocomplete options with a ...

How to process response in React using Typescript and Axios?

What is the proper way to set the result of a function in a State variable? const [car, setCars] = useState<ICars[]>([]); useEffect(() =>{ const data = fetchCars(params.cartyp); //The return type of this function is: Promise<AxiosRespo ...

Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included. After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using onl ...

What is the best way to asynchronously refresh Angular 2 (or 4) PrimeNg Charts?

Issue: How can PrimeNg Charts be updated asynchronously? Situation: I have a dropdown menu that should trigger a chart refresh based on the user's selection. I believed I had the solution figured out, understanding Angular change detection and reali ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

An error occurs when trying to use AWS.Comprehend as a constructor in the aws JavaScript SDK

I'm attempting to utilize the Amazon Comprehend API using the AWS JavaScript SDK. However, I keep encountering Uncaught (in promise): TypeError: undefined is not a constructor (evaluating 'new AWS.Comprehend... ' What am I doing incorr ...

Determining the return type based on the parameter type

Here is an example of my function: const safeIdCastToNumber = (id: string | null | undefined) => isNil(id) ? id : Number(id) When calling safeIdCastToNumber, I can use an id parameter with a type union string | null | undefined, as well as one with a t ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

The input elements fail to register the passed-in value until they are clicked on

I am experiencing an issue with my form element that contains a few input fields. Two of these inputs are set to readOnly and have values passed in from a calendar element. Even though the input elements contain valid dates, they still display an error mes ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

Identifying unique properties with specific keys in a Typescript object

Can a specific type be used with one property when using the key in of type? Playground. type ManyProps = 'name' | 'age' | 'height' type MyObj = {[key in ManyProps]: number, name?: string} ...

The error message "The type 'MouseEvent' is non-generic in TypeScript" popped up on the screen

Having created a custom button component, I encountered an issue when trying to handle the onClick event from outside the component. I specified the parameter type for the onClickCallback as MouseEvent<HTMLButtonElement, MouseEvent>, which is typical ...

If a task is currently ongoing, be sure to subscribe to it; otherwise, restart it

If I have a long-running observable called longObservable, which emits a new string once after 5 seconds and then completes. longObservable(): Subject<string> { return timer(5000).pipe{ map(() => randomString()) } } Other pages c ...

Angular 7 is throwing an error message that reads: "Module not found: 'AppModule'"

When running ng build, an error occurs without providing any specific details like the file name. This project is an ASP.NET Core app with Angular 7. c:\Users\siva\Myapp\ClientApp>ng build Date: 2019-08-08T13:22:52.205Z Hash: 3cf960 ...

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...