最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to store, read and delete cookies and sessions in Nest.js - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question edited Mar 6, 2020 at 22:14 SoEzPz 15.9k8 gold badges64 silver badges66 bronze badges asked May 2, 2019 at 7:56 东方不败东方不败 1351 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

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

Updated Answer

at the moment in order to add, create, update or delete a cookie you need to install express dependency named cookie-parser to the main.ts in order to parse the cookie first and then process it in the way you want.

  1. install the cookie-parser
npm i cookie-parser
npm i -D @types/cookie-parser 
  1. add the cookie-parser as global middleware in main.ts
import * as cookieParser from 'cookie-parser';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.ts';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // somewhere in your initialization file
  app.use(cookieParser());
  await app.listen(3000);
}
bootstrap();
  1. now you are able to process the cookie

Use the Request & Response type from express

// auth.controller.ts
@Get('/logout')
  cookie(@Req() request: Request, @Res() response: Response) {
    console.log(request.cookies); // or "request.cookies['name']"

    response.cookie('key', 'value') // for setting the cookie
    
  }

there's more information for cookie configuration with Fastify and more explained in docs

发布评论

评论列表(0)

  1. 暂无评论