|
| 1 | +### Cookies |
| 2 | + |
| 3 | +An **HTTP cookie** is a small piece of data stored by the user's browser. Cookies were designed to be a reliable mechanism for websites to remember stateful information. When the user visits the website again, the cookie is automatically sent with the request. |
| 4 | + |
| 5 | +#### Use with Express (default) |
| 6 | + |
| 7 | +First install the required package (and its types for TypeScript users): |
| 8 | + |
| 9 | +```shell |
| 10 | +$ npm i cookie-parser |
| 11 | +$ npm i -D @types/cookie-parser |
| 12 | +``` |
| 13 | + |
| 14 | +Once the installation is complete, apply the `cookie-parser` middleware as global middleware (for example, in your `main.ts` file). |
| 15 | + |
| 16 | +```typescript |
| 17 | +import * as cookieParser from 'cookie-parser'; |
| 18 | +// somewhere in your initialization file |
| 19 | +app.use(cookieParser()); |
| 20 | +``` |
| 21 | + |
| 22 | +You can also pass several options to the `cookieParser` middleware: |
| 23 | + |
| 24 | +- `secret` a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order. |
| 25 | +- `options` an object that is passed to `cookie.parse` as the second option. See [cookie](https://www.npmjs.org/package/cookie) for more information. |
| 26 | + |
| 27 | +The middleware will parse the `Cookie` header on the request and expose the cookie data as the property `req.cookies` and, if a secret was provided, as the property `req.signedCookies`. These properties are name value pairs of the cookie name to cookie value. |
| 28 | + |
| 29 | +When secret is provided, this module will unsign and validate any signed cookie values and move those name value pairs from req.cookies into `req.signedCookies`. A signed cookie is a cookie that has a value prefixed with `s:`. Signed cookies that fail signature validation will have the value `false` instead of the tampered value. |
| 30 | + |
| 31 | +With this in place, you can now read cookies from within the route handlers, as follows: |
| 32 | + |
| 33 | +```typescript |
| 34 | +@Get() |
| 35 | +findAll(@Req() request: Request) { |
| 36 | + console.log(request.cookies); // or "request.cookies['cookieKey']" |
| 37 | + // or console.log(request.signedCookies); |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +> info **Hint** The `@Req()` decorator is imported from the `@nestjs/common`, while `Request` from the `express` package. |
| 42 | +
|
| 43 | +To attach a cookie to an outgoing response, use the `Response#cookie()` method: |
| 44 | + |
| 45 | +```typescript |
| 46 | +@Get() |
| 47 | +findAll(@Res({ passthrough: true }) response: Response) { |
| 48 | + response.cookie('key', 'value') |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +> warning **Warning** If you want to leave the response handling logic to the framework, remember to set the `passthrough` option to `true`, as shown above. Read more [here](/controllers#appendix-library-specific-approach). |
| 53 | +
|
| 54 | +> info **Hint** The `@Res()` decorator is imported from the `@nestjs/common`, while `Response` from the `express` package. |
| 55 | +
|
| 56 | +#### Use with Fastify |
| 57 | + |
| 58 | +First install the required package: |
| 59 | + |
| 60 | +```shell |
| 61 | +$ npm i fastify-cookie |
| 62 | +``` |
| 63 | + |
| 64 | +Once the installation is complete, register the `fastify-cookie` plugin: |
| 65 | + |
| 66 | +```typescript |
| 67 | +import fastifyCookie from 'fastify-cookie'; |
| 68 | + |
| 69 | +// somewhere in your initialization file |
| 70 | +const app = await NestFactory.create<NestFastifyApplication>( |
| 71 | + AppModule, |
| 72 | + new FastifyAdapter(), |
| 73 | +); |
| 74 | +app.register(fastifyCookie, { |
| 75 | + secret: 'my-secret', // for cookies signature |
| 76 | +}); |
| 77 | +``` |
| 78 | + |
| 79 | +With this in place, you can now read cookies from within the route handlers, as follows: |
| 80 | + |
| 81 | +```typescript |
| 82 | +@Get() |
| 83 | +findAll(@Req() request: FastifyRequest) { |
| 84 | + console.log(request.cookies); // or "request.cookies['cookieKey']" |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +> info **Hint** The `@Req()` decorator is imported from the `@nestjs/common`, while `FastifyRequest` from the `fastify` package. |
| 89 | +
|
| 90 | +To attach a cookie to an outgoing response, use the `FastifyReply#setCookie()` method: |
| 91 | + |
| 92 | +```typescript |
| 93 | +@Get() |
| 94 | +findAll(@Res({ passthrough: true }) response: FastifyReply) { |
| 95 | + response.setCookie('key', 'value') |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +To read more about `FastifyReply#setCookie()` method, check out this [page](https://github.com/fastify/fastify-cookie#sending). |
| 100 | + |
| 101 | +> warning **Warning** If you want to leave the response handling logic to the framework, remember to set the `passthrough` option to `true`, as shown above. Read more [here](/controllers#appendix-library-specific-approach). |
| 102 | +
|
| 103 | +> info **Hint** The `@Res()` decorator is imported from the `@nestjs/common`, while `FastifyReply` from the `fastify` package. |
| 104 | +
|
| 105 | +#### Creating a custom decorator (cross-platform) |
| 106 | + |
| 107 | +To provide a convenient, declarative way of accessing incoming cookies, we can create a [custom decorator](/custom-decorators). |
| 108 | + |
| 109 | +```typescript |
| 110 | +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; |
| 111 | + |
| 112 | +export const Cookies = createParamDecorator( |
| 113 | + (data: string, ctx: ExecutionContext) => { |
| 114 | + const request = ctx.switchToHttp().getRequest(); |
| 115 | + return data ? request.cookies?.[data] : request.cookies; |
| 116 | + }, |
| 117 | +); |
| 118 | +``` |
| 119 | + |
| 120 | +The `@Cookies()` decorator will extract all cookies, or a named cookie from the `req.cookies` object and populate the decorated parameter with that value. |
| 121 | + |
| 122 | +With this in place, we can now use the decorator in a route handler signature, as follows: |
| 123 | + |
| 124 | +```typescript |
| 125 | +@Get() |
| 126 | +findAll(@Cookies('name') name: string) {} |
| 127 | +``` |
0 commit comments