NestJS - Cookies

Nikos Oikonomou
2 min readJan 27, 2024

In this section, we’ll introduce cookies management to our NestJS application.

This section is part of a larger guide. You can follow it from the beginning or just complete the only prerequisite step (getting started).

At this point, you should have a fully operational NestJS project to follow the upcoming steps.

NestJS Web Apps don’t handle cookies by default so we’ll need to install and enable the cookie-parser package. It provides an express middleware that can parse Request’s cookies and add them to req.cookies.

Let’s start by installing the cookie-parser package and its types:

npm i cookie-parser
npm i -D @types/cookie-parser

Now we can create a basic NestJS module to apply the new middleware:

We can now install the new module in our application and create a test endpoint that returns the provided cookies:

You can test the new endpoint by running the application and sending a new HTTP request:

npm run start:dev
curl -H 'cookie: awesome=cookie' localhost:3000/cookies
# expected output: {"awesome":"cookie"}

Or by running e2e tests:

npm run test:e2e

Now that we have a fully operational example, we can focus on implementing the available settings from the cookies-parser package. To do so we’ll introduce a new NestJS config and use it at the cookie’s configure method.

The application can also define Cookie Secrets that can be used to decode signed cookies. Just set COOKIES_SECRET environment variable and it will be used by the cookie parser middleware. You can pass single or multiple values separated by commas (e.g. COOKIES_SECRET=secret-a , COOKIES_SECRET=secret-a,secret-b,secret-c ).

Now, your application can decode incoming cookies and add them to the corresponding req object at req.cookies.

Note: To use import cookieParser from 'cookie-parser'; instead of import * as cookieParser from 'cookie-parser';, you must enable esModuleInterop.

Disclaimer: There are various ways to enable cookie parser (e.g. using app.use(cookieParser())), but in this guide, we try to always use the module structure (check the best practices section for more details).

--

--