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.
Before implementing cookies in nest.js, first is to install required packages and it's typescript definitions
$ npm i cookie-parser
$ npm i -D @types/cookie-parser
Once installation is complete, set cookie-parser middleware as global middleware in the main.ts file of the application.
In the src/main.ts file add cookie-parser
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cookieParser from 'cookie-parser';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Enable cookie parsing globally
app.use(cookieParser('your-secret-key-here'));
await app.listen(3000);
}
bootstrap();
You can pass several options to the cookieParser middleware:
- 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.
- options an object that is passed to cookie.parse as the second option. See cookie for more information.
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.
When a 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.
To issue a cookie, inject the underlying platform Response object using the @Res() decorator.
import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
@Controller('auth')
export class AuthController {
@Get('login')
setCookie(@Res({ passthrough: true }) response: Response) {
response.cookie('accessToken', 'xyz123fakeToken', {
httpOnly: true, // Prevents client-side scripts from reading the cookie
secure: true, // Ensures cookie is sent only over HTTPS
sameSite: 'strict', // Controls cross-site request behavior
maxAge: 3600000, // Expires in 1 hour (milliseconds)
});
return { message: 'Logged in and cookie issued successfully!' };
}
}
To read incoming cookies, use the standard @Req() decorator to access the parsed properties. Alternatively, you can create a custom param decorator for cleaner code.
import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('profile')
export class ProfileController {
@Get()
getProfileCookies(@Req() request: Request) {
// Read unsigned cookies
const normalCookie = request.cookies['accessToken'];
// Read signed cookies (if you provided a secret to cookieParser)
const signedCookie = request.signedCookies['accessToken'];
return { normalCookie, signedCookie };
}
}
To delete a cookie from the user's browser, match the exact configuration options used to set it (like path or domain) and call .clearCookie():
@Get('logout')
logout(@Res({ passthrough: true }) response: Response) {
response.clearCookie('accessToken', {
httpOnly: true,
secure: true,
sameSite: 'strict',
});
return { message: 'Logged out successfully!' };
}
Now, your application can decode incoming cookies and add them to the corresponding req object at req.cookies.
Top comments (0)