Search code examples
cookiesdenooak

Not able to set cookie in browser with Deno Oak


I am trying to set up Authentication with Deno, Oak and JWT.

Objective:

  1. Send cookie with jwt token in the response.
  2. Set cookie in the browser
  3. Use the cookie for subsequent requests.

Route: Cookie being set

export const getUsers = async ({ response, cookies }) => {
    const users = await userCollection.find().toArray();

    await cookies.set("token", "1234567890", {
        sameSite: "lax",
    });
    response.body = users;
};

handling the Cors issue

app.use(
    oakCors({
        credentials: true,
        origin: /^.+localhost:(3000|4200|8080)$/,
    })
);

Cookie is being recieved but I am not able to see this cookie in APplication --> Cookies

Response headers has the cookie but the same is not set in Application --> Cookies.

Please help me understand this issue.


Solution

  • using ctx.cookies.set is how you set a cookie in Oak, have in mind that by default it's httpOnly. Your browser might not show it in that case or you're looking in the wrong place.

    From the screenshot we can see that Oak is setting the cookie correctly in the response headers:

    token=1234567890; path=/; samesite=lax; httponly
    

    To check that the cookie is set correctly, just add:

    console.log(await ctx.cookies.get('token'));
    

    And you'll see that in subsequent requests will log 1234567890 correctly.


    Since you're mentioning CORS I suspect that you're looking the cookie to be present in the wrong domain, you should be looking for the cookie in:

    • localhost:8000 (server setting the cookie)

    And not in your front end domain:port

    So, if you issue the request from: http://localhost:3000 to http://localhost:8000, when you're in :3000 there will be no cookie present in Application > Cookies > http://localhost:3000, but it'll be in Application > Cookies > http://localhost:8000