javascripttypescriptcookiesdenooak

ctx.cookies.set() vs setCookies in Deno std


I'm currently working with Deno (Oak framework), and wanted to know what is the difference between using Oak's ctx.cookies (https://github.com/oakserver/oak/blob/main/cookies.ts) vs something from Deno's std lib (setCookies, getCookie, and deleteCookie from https://deno.land/std@0.120.0/http/cookie.ts).

Even though the Oak framework provides methods to work with cookies, what are the pros/cons to consider between the two? IS there ever a reason to use the std lib over oak's methods even when using the framework?


Solution

  • In short: if you're using Oak, use the methods provided by Oak unless you have a specific reason not to. (It will be evident if you ever encounter such a scenario.)


    The setCookie function from deno.land/std/http simply appends a new Set-Cookie header to an existing Headers object. You can use this with Oak:

    const cookie = {name: 'cookie_name' value: 'cookie_value'};
    setCookie(ctx.response.headers, cookie);
    

    The set method on ctx.cookies (which is an instance of the Cookies class) from deno.land/x/oak allows you to operate directly on the cookies in the current request-response context:

    await ctx.cookies.set('cookie_name', 'cookie_value');
    

    When using it, you don't need to manually pass a reference to an existing Headers object (because it's already part of the context response object). This kind of higher-level abstraction means you don't have to manage (or necessarily even think about) as many discrete parts. Oak provides additional abstractions when working with cookies, such as cryptographic signatures. The documentation covers the details.