1
votes

I recently just switched from using express with apollo server to just using apollo server since the subscriptions setup seemed more current and easier to setup. The problem I'm having now is I was saving a cookie with our refresh token for login and clearing the cookie on logout. This worked when I was using express.

     const token = context.req.cookies[process.env.REFRESH_TOKEN_NAME!];
     context.res.status(401);

Since switching from express/apollo to just apollo server I don't have access to req.cookies even when i expose the req/res context on apollo server.

I ended up switching to this (which is hacky) to get the cookie.

      const header = context.req.headers.cookie
      var cookies = header.split(/[;] */).reduce(function(result: any, pairStr: any) {
        var arr = pairStr.split('=');
        if (arr.length === 2) { result[arr[0]] = arr[1]; }
        return result;
      }, {});

This works but now I can't figure out how to delete the cookies. With express I was doing

context.res.clearCookie(process.env.REFRESH_TOKEN_NAME!);

Not sure how I can clear cookies now since res.clearCookie doesn't exist.

1

1 Answers

0
votes

Simply send back the exact same cookie to the client with an Expires attribute set to some date in the past. Note that everything about the rest of the cookie has to be exactly the same, so be sure to keep all the original cookie attributes, too.

And, here's a link to the RFC itself on this topic:

Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created.

As to how to do this, if you're using Node's http module, you can just use something like this (assuming you have a response coming from the callback passed to http.createServer):

context.response.writeHead(200, {'Set-Cookie': '<Your Cookie Here>', 'Content-Type': 'text/plain'});

This is assuming that your context has access to that http response it can write to.

For the record, you can see how Express does it here and here for clarity.