LosMos
LosMos

Reputation: 149

how to get cookie in koa.js from a request

I am using koa.js as a node.js server and setting a jwt token as a cookie. It gets set correctly. When a user authenicates, the cookie is set. In response headers, I can see the set-cookie attribute

Set-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzYjZlMWUwYTFhNGMxOTQzNDgzNWVkZCIsInVzZXJuYW1lIjoibml4ZW4iLCJpYXQiOjE2NzMzODM3NDZ9.U_RNtDXVSw9p7B3GJ02abx95hCYHtKmY5oN7Hutxv_k; path=/; expires=Tue, 10 Jan 2023 20:49:06 GMT; samesite=none; httponly

Below is how I am setting the cookie

export const checkUserCredentials = async (ctx, username, password) => {
  try {
    const user = await ctx.db.collection('user').findOne({ username });
    if (!user) {
      return { status: 'error', message: 'Invalid username or password' };
    }
    if (await bcrypt.compare(password, user.password)) {
      const token = jwt.sign(
        { id: user._id, username: user.username },
        process.env.JWT_SECRET
      );
      ctx.cookies.set('jwt', token, {
        httpOnly: true,
        expires: new Date(Date.now() + 365),
        secure: process.env.NODE_ENV === 'production' ? true : false,
        sameSite: 'none',
      });
      return { status: 'ok', data: token };
    }
    return { status: 'error', message: 'Invalid username or password' };
  } catch (err) {
    logger.error(err.message);
    return { status: 'error', message: err.message };
  }
};

When I use ctx.cookies.get('jwt') // returns undefined in a different request after the user has been logged in, I get undefined. What am I doing wrong?

The request I use to get a cookie is a test endpoint which goes like below

UserRouter.get('/api/test', koaBody(), testUser);

and the testUser function

export const testUser = async (ctx) => {
  console.log(ctx.cookies.get('jwt'), ' cookie');
  ctx.body = { status: 'ok' };
};

Also, I am using fetch to send request. My function that sends the api request is below

 const testing = async (e) => {
    e.preventDefault();
    const result = await fetch('/api/test', {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((res) => res.json());
  };

I can provide more information if required.

Upvotes: 2

Views: 1407

Answers (0)

Related Questions