Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 297
东方不败 Avatar asked May 02 '19 07:05

东方不败


People also ask

How do I store session cookies?

In fact, php does store the session in a cookie - a single cookie, usually called PHPSESSID . This corresponds to a file (the filename of which is the value of the PHPSESSID cookie) on the server which is a set of key/value pairs, such as those you outline above.

Are cookies and sessions the same thing?

Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as a server. A session creates a file in a temporary directory on the server where registered session variables and their values are stored.


1 Answers

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

like image 70
SoEzPz Avatar answered Oct 05 '22 11:10

SoEzPz