typescript
51 lines · 8 steps
A signed-cookie param decorator in NestJS
A custom NestJS parameter decorator that reads a cookie, verifies its HMAC signature in constant time, and hands back the trusted value.
Explained by
highlit
1import {
2 createParamDecorator,
3 ExecutionContext,
4 UnauthorizedException,
5} from '@nestjs/common';
6import { Request } from 'express';
7import { createHmac, timingSafeEqual } from 'crypto';
8
9function verifySignedValue(signed: string, secret: string): string {
10 const lastDot = signed.lastIndexOf('.');
11 if (lastDot === -1) {
12 throw new UnauthorizedException('Malformed signed cookie');
13 }
14
15 const value = signed.slice(0, lastDot);
16 const signature = signed.slice(lastDot + 1);
17
18 const expected = createHmac('sha256', secret)
19 .update(value)
20 .digest('base64url');
21
22 const provided = Buffer.from(signature);
23 const digest = Buffer.from(expected);
24
25 if (
26 provided.length !== digest.length ||
27 !timingSafeEqual(provided, digest)
28 ) {
29 throw new UnauthorizedException('Invalid cookie signature');
30 }
31
32 return value;
33}
34
35export const SignedCookie = createParamDecorator(
36 (cookieName: string, ctx: ExecutionContext): string => {
37 const request = ctx.switchToHttp().getRequest<Request>();
38 const raw = request.cookies?.[cookieName];
39
40 if (typeof raw !== 'string' || raw.length === 0) {
41 throw new UnauthorizedException(`Missing cookie: ${cookieName}`);
42 }
43
44 const secret = process.env.COOKIE_SECRET;
45 if (!secret) {
46 throw new Error('COOKIE_SECRET is not configured');
47 }
48
49 return verifySignedValue(raw, secret);
50 },
51);
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Signing a value with HMAC lets you trust data that round-trips through an untrusted client like a cookie.
- 2Signature comparisons must use a constant-time check so attackers can't learn the digest byte by byte.
- 3Custom parameter decorators pull verification logic out of controllers, so handlers receive already-trusted values.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-signed-cookie-param-decorator-in-nestjs-explained-typescript-168d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.