惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
H
Help Net Security
量子位
The Cloudflare Blog
博客园 - Franky
博客园 - 聂微东
博客园 - 司徒正美
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
罗磊的独立博客
GbyAI
GbyAI
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Implementing Cookies with Nest.js
Daniel Kuboi · 2026-06-03 · via DEV Community
Cover image for Implementing Cookies with Nest.js

Daniel Kuboi

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

Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

You can pass several options to the cookieParser middleware:

  1. 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.
  2. 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!' };
  }
}

Enter fullscreen mode Exit fullscreen mode

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 };
  }
}

Enter fullscreen mode Exit fullscreen mode

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!' };
}

Enter fullscreen mode Exit fullscreen mode

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