In NestJS, you can retrieve cookies from requests in several ways. One common method is to use the @Req() decorator to inject the entire request object, then access the cookies via the cookies property of the request object. Here's a specific example:
typescriptimport { Controller, Get, Req } from '@nestjs/common'; import { Request } from 'express'; // NestJS internally uses Express @Controller('example') export class ExampleController { @Get() getCookie(@Req() request: Request): string { const cookies = request.cookies; // Retrieve all cookies const myCookie = cookies['myCookieName']; // Access a specific cookie by name return `The value of myCookie is: ${myCookie}`; } }
Another method is to use the @Cookies() decorator. This is a custom decorator provided by NestJS that directly extracts cookies from the request. You can choose to retrieve all cookies or a specific one. For example:
typescriptimport { Controller, Get, Cookies } from '@nestjs/common'; @Controller('example') export class ExampleController { @Get() getCookie(@Cookies('myCookieName') myCookie: string): string { // The `myCookie` parameter directly contains the value of the cookie named 'myCookieName' return `The value of myCookie is: ${myCookie}`; } }
In this example, the @Cookies('myCookieName') decorator injects the value of the cookie named myCookieName into the myCookie parameter.
If your NestJS application does not directly handle cookies and uses third-party libraries like Passport for authentication, these libraries often provide cookie abstraction. For instance, you might set a session cookie during login and then identify users in subsequent requests through the session.
Note that to handle cookies, you may need to install and use middleware like cookie-parser in NestJS to correctly parse cookies on the request object:
bashnpm install cookie-parser
Then, configure it in your main module or middleware:
typescriptimport * as cookieParser from 'cookie-parser'; // In the configure method of the main module export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(cookieParser()) .forRoutes('*'); // Apply to all routes } }
After this, you can access cookies in your controllers as shown in the examples above.