10

How to store, read and delete cookies and sessions in Nest.js?

Should I use this:

@nestjs/common > session

Or should I use js-cookie?

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
东方不败
  • 115
  • 1
  • 4

1 Answers1

10

Create Cookie

async myMethod(@Req() req, @Res() res) {
  res.cookie('session', myCookieData, myOptionalCookieOptions);
  ....

Read Cookie

async myMethod(@Req() req, @Res() res) {
  req.cookies['session']; // If unsigned cookie;
  req.signedCookies['session']; // If signed cookie;

Store Cookie

You can store the cookie wherever you like. However, if you are using it for auth then check out @nestjs/passport link

Delete Cookie

async myMethod(@Req() req, @Res() res) {
  res.clearCookie('session', mySameOptionsFromCreationOfCookieMustMatch);

Note: "Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge." link

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • It depends on if you are trying to read or create the cookie. Reading it would be in the response (res), creating it means sending it back to the client in the request (req). – SoEzPz Oct 12 '20 at 14:04
  • Yes, clearCookie() should have been res.clearCookie(). I have made the change, thanks. – SoEzPz Oct 12 '20 at 14:12