DEV Community

Cover image for How to build an e-commerce backend in Node.js with NestJS: carts, checkout and the last item in stock
Kamil Mysliwiec for NestJS

Posted on Originally published at docs.nestjs.com

How to build an e-commerce backend in Node.js with NestJS: carts, checkout and the last item in stock

sk for an e-commerce backend and you get products, carts and orders, and most of it is CRUD that any framework handles. Then one day a product with one unit left goes on sale, and two customers both get a confirmation email.

That second part is what decides whether a shop backend is any good, and it lives in a handful of places: where prices are stored, what an order remembers about them, and the few statements that take stock out of the warehouse. Get those right and the CRUD around them is routine. Get them wrong and the bug shows up only under load, on the day you sell the most.

This post builds the whole backend with NestJS 12, PostgreSQL and Drizzle: a catalog that staff manage, a cart per customer, a checkout that can't oversell, cancelling and shipping, a curl session, tests that race real requests against a real database, and a production checklist. Every file is here, including the sign-in side it starts from. The docs version of this article, kept up to date, is Build an e-commerce backend in Node.js.

What the API does

When it's done, the API:

  • Lets anyone browse and search the catalog, and only staff create and edit products. Permissions come from @nestjs/authorization, which refuses any route that doesn't say who may call it.
  • Keeps a cart for every customer, priced at today's prices, and marks the lines that can't be bought right now.
  • Checks out in one database transaction: it takes the cart, takes the stock and records the prices, or it changes nothing at all.
  • Lets customers cancel orders that haven't shipped, which puts the stock back, and lets staff ship them.
  • Proves, in a test against PostgreSQL, that ten customers racing for the last unit produce exactly one order.

The routes, by the section that adds them:

  • Sign-in and health, from the JWT API: POST /auth/sign-up, POST /auth/token, POST /auth/token/refresh, POST /auth/token/revoke, GET /me, GET /health/live, GET /health/ready.
  • The catalog: GET /products, GET /products/:id, POST /products, PATCH /products/:id.
  • The cart: GET /cart, PUT /cart/items/:productId, DELETE /cart/items/:productId.
  • Checkout and orders: POST /orders, GET /orders, GET /orders/:id.
  • Cancelling and shipping: POST /orders/:id/cancel, POST /orders/:id/ship.

The tested app uses @nestjs/core 12.5.1, @nestjs/authentication 0.1.6, @nestjs/authorization 0.1.4, @nestjs/drizzle 0.0.2, drizzle-orm and drizzle-kit 1.0.0-rc.5, pg 8.23.1, Zod 4.6.7 and Vitest 5.1.1. You'll also need Docker, for PostgreSQL.

Set up the project from the JWT API

A shop needs accounts, and accounts aren't what this post is about. So the starting point is the API from the docs tutorial Build a REST API with JWT authentication: sign-up and sign-in with short-lived access tokens and rotating refresh tokens from @nestjs/authentication, request validation with Zod, data in PostgreSQL through Drizzle, rate limits, an OpenAPI document and health checks. That tutorial explains each of those; here they're just the base we build on.

Create the project and install everything this post uses. It's the JWT API's package list, plus @nestjs/authorization:

$ npm i -g @nestjs/cli
$ nest new shop-api --minimal
$ cd shop-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/authorization @nestjs/throttler @nestjs/swagger @nestjs/terminus
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite
Enter fullscreen mode Exit fullscreen mode

The --minimal flag gives you a one-file project, which the files below replace. The Express adapter goes because the app runs on the Node adapter, which puts Nest directly on node:http.

From the JWT API, the app takes src/config.ts, src/main.ts, drizzle.config.ts, vitest.config.e2e.ts, everything under src/auth/, src/users/ and src/health/, and test/refresh-token.store.e2e-spec.ts. None of them is specific to a shop, so rather than interrupt the walkthrough with them, they're all listed in full in the appendix at the end, already renamed for the shop: the realm in JwtAuth is shop, and the OpenAPI document is titled "Shop API". What doesn't come along is the JWT API's notes module and its drizzle/ folder: the shop's first migration is generated from its own schema, in the next section.

The tests get a script in the scripts of package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
Enter fullscreen mode Exit fullscreen mode

The shop gets a PostgreSQL database of its own. With Docker:

$ docker run -d --name shop-db -e POSTGRES_PASSWORD=shop -e POSTGRES_DB=shop -p 5432:5432 postgres:17
Enter fullscreen mode Exit fullscreen mode

Its URL goes in .env at the project root, next to the secret that signs the access tokens:

DATABASE_URL=postgres://postgres:shop@localhost:5432/shop
# Generate with: openssl rand -base64 32
JWT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Give users a role: customer or staff

Customers and staff sign in the same way, through the same routes. What tells them apart is a role on the user:

// src/users/user.ts
export type Role = 'customer' | 'staff';

export interface User {
  id: string;
  email: string;
  role: Role;
  createdAt: Date;
}
Enter fullscreen mode Exit fullscreen mode

UsersRepository selects the role together with the other columns. It's a one-line change to the columns it returns (the whole file is in the appendix):

// src/users/users.repository.ts
// ...
const columns = { id: users.id, email: users.email, role: users.role, createdAt: users.createdAt };
Enter fullscreen mode Exit fullscreen mode

Note what's not happening: the role isn't put in the access token. JwtAuth.validate() loads the user from the database on every request, so when you promote someone to staff, or demote them, it applies from their next request. With the role baked into the token, a demoted staff member would keep their powers until the token expired.

Design the database schema for an e-commerce backend

Here's the whole schema, in one file. The users and refresh_tokens tables are the JWT API's, with the new role column on users; products, cart items, orders and order items are the shop:

// src/database/schema.ts
import { sql } from 'drizzle-orm';
import { boolean, check, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  role: text('role', { enum: ['customer', 'staff'] }).notNull().default('customer'),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const products = pgTable(
  'products',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    name: text('name').notNull(),
    description: text('description').notNull(),
    // Money in integer cents: no floating-point rounding.
    price: integer('price').notNull(),
    stock: integer('stock').notNull(),
    active: boolean('active').notNull().default(true),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [
    check('products_price_positive', sql`${table.price} > 0`),
    // The last line of defense against overselling.
    check('products_stock_not_negative', sql`${table.stock} >= 0`),
  ],
);

export const cartItems = pgTable(
  'cart_items',
  {
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    productId: uuid('product_id')
      .notNull()
      .references(() => products.id, { onDelete: 'cascade' }),
    quantity: integer('quantity').notNull(),
  },
  (table) => [primaryKey({ columns: [table.userId, table.productId] })],
);

export const orders = pgTable(
  'orders',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id),
    status: text('status', { enum: ['placed', 'shipped', 'cancelled'] }).notNull(),
    total: integer('total').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [index('orders_user_id_created_at_idx').on(table.userId, table.createdAt)],
);

// What was bought, at the price it was bought at: later price changes don't rewrite past orders.
export const orderItems = pgTable(
  'order_items',
  {
    orderId: uuid('order_id')
      .notNull()
      .references(() => orders.id, { onDelete: 'cascade' }),
    productId: uuid('product_id')
      .notNull()
      .references(() => products.id),
    name: text('name').notNull(),
    unitPrice: integer('unit_price').notNull(),
    quantity: integer('quantity').notNull(),
  },
  (table) => [primaryKey({ columns: [table.orderId, table.productId] })],
);

// What @nestjs/authentication keeps for refresh tokens, stored by their SHA-256.
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // A family is revoked when any of its tokens is.
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type Product = typeof products.$inferSelect;
export type Order = typeof orders.$inferSelect;
export type OrderItem = typeof orderItems.$inferSelect;
Enter fullscreen mode Exit fullscreen mode

Most of the bugs a shop can have are decided by a few lines of that file:

  • Prices are integers, in cents. 19.99 has no exact floating-point representation, and a total of many of them drifts. 1999 doesn't. Every price and total in this API is a whole number of cents, and a CHECK keeps prices above zero.
  • An order item copies the product's name and price. When staff change a price or rename a product, past orders keep what the customer actually paid for. An order that joined the product table for its price would rewrite history every time the catalog changed.
  • The cart is a table, keyed by user and product. Setting a line's quantity is a single upsert, and the same product can't appear twice in one cart.
  • Products are deactivated, never deleted. Order items keep referring to them. That's why there's an active flag and no DELETE /products/:id.
  • stock can't go below zero. That's the products_stock_not_negative constraint. The checkout below never tries to take more than there is, but if a later change gets that wrong, PostgreSQL refuses the write instead of storing a negative stock. It's the last line of defense, not the first.

Generate and apply the migration

Drizzle Kit generates the SQL from the schema and applies it (the Migrations chapter has the details):

$ npx drizzle-kit generate --name=shop
$ npx drizzle-kit migrate
Enter fullscreen mode Exit fullscreen mode

The first command writes a folder like drizzle/20261119202159_shop/ with a migration.sql in it. The part of it worth reading is the products table, where the two CHECK constraints end up in the database itself:

CREATE TABLE "products" (
    "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    "name" text NOT NULL,
    "description" text NOT NULL,
    "price" integer NOT NULL,
    "stock" integer NOT NULL,
    "active" boolean DEFAULT true NOT NULL,
    "created_at" timestamp with time zone DEFAULT now() NOT NULL,
    CONSTRAINT "products_price_positive" CHECK ("price" > 0),
    CONSTRAINT "products_stock_not_negative" CHECK ("stock" >= 0)
);
Enter fullscreen mode Exit fullscreen mode

From here on, those rules hold no matter which code writes to the table, whether it's this API, a script someone runs in production, or a future admin tool.

Let staff manage the catalog with @nestjs/authorization

Anyone may read the catalog; only staff may change it. @nestjs/authorization expresses rules like that as policies: classes whose methods answer "may this user do this?".

The root module

Here's the root module as it ends up, with all of the shop's feature modules (the imports of files we haven't written yet will resolve as we go). Register AuthorizationModule right after AuthenticationModule: both install a global guard, and the authorization guard needs the user that the authentication guard sets:

// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { DrizzleModule } from '@nestjs/drizzle';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { CartModule } from './cart/cart.module.js';
import { HealthModule } from './health/health.module.js';
import { OrdersModule } from './orders/orders.module.js';
import { ProductsModule } from './products/products.module.js';
import { UsersModule } from './users/users.module.js';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'shop-api',
          audience: 'shop-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    // After AuthenticationModule: its guard reads the user that authentication sets.
    AuthorizationModule.forRoot(),
    ThrottlerModule.forRoot([
      // Per IP address, on every route.
      { name: 'default', ttl: minutes(1), limit: 100 },
      // Per email and IP address, wherever the request body names an account.
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ProductsModule,
    CartModule,
    OrdersModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

The rest is the JWT API's: configuration validated at startup, the database, access tokens that live 15 minutes, refresh tokens that rotate and last 30 days each and 90 days at most from the sign-in, a rate limit per IP address on every route and a stricter one per account wherever the request body names an email, and Zod validation on every route through StandardSchemaValidationPipe.

Deny by default

The authorization guard denies by default. A route runs only if it declares who may call it, in one of three ways: @Can() checks a policy, @Can.Anyone() lets through any caller that authentication accepted, and @Public() counts as @Can.Anyone(). A route whose declaration someone forgot is closed, not open, and the module logs every such route at startup, so you find out from the log rather than from an incident.

The JWT API's routes under /auth and /health are @Public() already. GET /me is for any signed-in user, so it gets @Can.Anyone():

// src/users/me.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from './user.js';

@Can.Anyone()
@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: User) {
    return user;
  }
}
Enter fullscreen mode Exit fullscreen mode

A policy for the catalog

The catalog's policy has one ability, managing products. Its user parameter accepts null, which stands for a guest, so the guard can call it on any route, signed in or not:

// src/products/product.policy.ts
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';

@Policy()
export class ProductPolicy {
  // `null` is a guest.
  manage(user: User | null) {
    return user?.role === 'staff';
  }
}
Enter fullscreen mode Exit fullscreen mode

Validate prices in cents with Zod

The request schemas. Prices are validated as whole numbers of cents, so a client that sends 19.99 gets a 400 instead of a rounding question:

// src/products/products.schemas.ts
import { z } from 'zod';

const name = z.string().trim().min(1).max(200);
const description = z.string().max(5_000);
// In cents: 1999 is 19.99.
const price = z.number().int().positive().max(10_000_000);
const stock = z.number().int().min(0);

export const createProductSchema = z.object({ name, description: description.default(''), price, stock });
export type CreateProductDto = z.infer<typeof createProductSchema>;

export const updateProductSchema = z.object({ name, description, price, stock, active: z.boolean() }).partial();
export type UpdateProductDto = z.infer<typeof updateProductSchema>;

export const listProductsQuerySchema = z.object({
  q: z.string().trim().min(1).max(100).optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  offset: z.coerce.number().int().min(0).default(0),
});
export type ListProductsQuery = z.infer<typeof listProductsQuerySchema>;
Enter fullscreen mode Exit fullscreen mode

The update schema is written out rather than derived from the create schema with partial(), for the same reason as in the JWT API: partial() would keep the default('') on description, and every update that didn't mention the description would quietly clear it.

The products service

The service lists active products, with an optional search by name, and reads, creates and updates them:

// src/products/products.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, ilike } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { products, type Product } from '../database/schema.js';
import type { CreateProductDto, ListProductsQuery, UpdateProductDto } from './products.schemas.js';

@Injectable()
export class ProductsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  findAll({ q, limit, offset }: ListProductsQuery): Promise<Product[]> {
    return this.db
      .select()
      .from(products)
      .where(and(eq(products.active, true), q ? ilike(products.name, `%${escapeLike(q)}%`) : undefined))
      .orderBy(asc(products.name), asc(products.id))
      .limit(limit)
      .offset(offset);
  }

  async findOne(id: string): Promise<Product> {
    const [product] = await this.db
      .select()
      .from(products)
      .where(and(eq(products.id, id), eq(products.active, true)));
    return product ?? notFound();
  }

  async create(dto: CreateProductDto): Promise<Product> {
    const [product] = await this.db.insert(products).values(dto).returning();
    return product;
  }

  async update(id: string, dto: UpdateProductDto): Promise<Product> {
    const [product] = await this.db.update(products).set(dto).where(eq(products.id, id)).returning();
    return product ?? notFound();
  }
}

function notFound(): never {
  throw new NotFoundException('Product not found');
}

/** `%` and `_` in the search are literal characters, not wildcards. */
const escapeLike = (value: string) => value.replace(/[\\%_]/g, (char) => `\\${char}`);
Enter fullscreen mode Exit fullscreen mode

The search goes through Drizzle's ilike(), which sends the pattern as a query parameter, so it can't inject SQL. What it would still do, unescaped, is treat % and _ as wildcards: a search for 100% would match every product. escapeLike() makes them literal characters. The list is ordered by name and then by id, so products with the same name come back in a stable order from one page to the next.

The products controller

The read routes are @Public(). The write routes check the policy before the handler runs, and the answer depends on who's asking: a guest gets a 401, which says "sign in", and a signed-in customer gets a 403, which says signing in won't help:

// src/products/products.controller.ts
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { ApiSecurity } from '@nestjs/swagger';
import { z } from 'zod';
import { ProductPolicy } from './product.policy.js';
import {
  createProductSchema,
  listProductsQuerySchema,
  updateProductSchema,
  type CreateProductDto,
  type ListProductsQuery,
  type UpdateProductDto,
} from './products.schemas.js';
import { ProductsService } from './products.service.js';

const productId = { schema: z.uuid() };

@Controller('products')
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Public()
  @ApiSecurity({})
  @Get()
  findAll(@Query({ schema: listProductsQuerySchema }) query: ListProductsQuery) {
    return this.productsService.findAll(query);
  }

  @Public()
  @ApiSecurity({})
  @Get(':id')
  findOne(@Param('id', productId) id: string) {
    return this.productsService.findOne(id);
  }

  @Can(ProductPolicy, 'manage')
  @Post()
  create(@Body({ schema: createProductSchema }) dto: CreateProductDto) {
    return this.productsService.create(dto);
  }

  @Can(ProductPolicy, 'manage')
  @Patch(':id')
  update(@Param('id', productId) id: string, @Body({ schema: updateProductSchema }) dto: UpdateProductDto) {
    return this.productsService.update(id, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

@ApiSecurity({}) marks the public routes in the OpenAPI document as needing no token (the document requires the bearer token everywhere else). And @Can() is type-checked against the policy: @Can(ProductPolicy, 'mange') doesn't compile.

The policy is registered as a provider of its module, which is where the authorization module finds it:

// src/products/products.module.ts
import { Module } from '@nestjs/common';
import { ProductPolicy } from './product.policy.js';
import { ProductsController } from './products.controller.js';
import { ProductsService } from './products.service.js';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService, ProductPolicy],
})
export class ProductsModule {}
Enter fullscreen mode Exit fullscreen mode

Promote the first staff member

Sign-up creates customers, and no route makes someone staff. Promote the first staff member in the database; from then on, an admin screen of your own can do it:

$ docker exec shop-db psql -U postgres -d shop -c "UPDATE users SET role = 'staff' WHERE email = 'sam@example.com'"
Enter fullscreen mode Exit fullscreen mode

Keep a shopping cart that doesn't reserve stock

A cart line is a product and a quantity. The one request schema is the quantity:

// src/cart/cart.schemas.ts
import { z } from 'zod';

export const setQuantitySchema = z.object({
  quantity: z.number().int().min(1).max(100),
});
export type SetQuantityDto = z.infer<typeof setQuantitySchema>;
Enter fullscreen mode Exit fullscreen mode

The service reads the cart joined to the products, at today's prices, and sets a line with an upsert on the table's primary key. That makes the PUT idempotent: sending the same request twice leaves the same cart:

// src/cart/cart.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { cartItems, products } from '../database/schema.js';

export interface CartLine {
  productId: string;
  name: string;
  unitPrice: number;
  quantity: number;
  /** Whether checkout can take this line right now. */
  available: boolean;
}

export interface Cart {
  items: CartLine[];
  /** In cents, at today's prices. */
  total: number;
}

@Injectable()
export class CartService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  async get(userId: string): Promise<Cart> {
    const rows = await this.db
      .select({
        productId: cartItems.productId,
        name: products.name,
        unitPrice: products.price,
        quantity: cartItems.quantity,
        active: products.active,
        stock: products.stock,
      })
      .from(cartItems)
      .innerJoin(products, eq(products.id, cartItems.productId))
      .where(eq(cartItems.userId, userId))
      .orderBy(asc(products.name));
    const items = rows.map(({ active, stock, ...line }) => ({ ...line, available: active && stock >= line.quantity }));
    const total = items.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0);
    return { items, total };
  }

  async setQuantity(userId: string, productId: string, quantity: number): Promise<Cart> {
    const [product] = await this.db
      .select({ id: products.id })
      .from(products)
      .where(and(eq(products.id, productId), eq(products.active, true)));
    if (!product) {
      throw new NotFoundException('Product not found');
    }
    // Stock isn't reserved here: checkout checks it, in the same statement that takes it.
    await this.db
      .insert(cartItems)
      .values({ userId, productId, quantity })
      .onConflictDoUpdate({ target: [cartItems.userId, cartItems.productId], set: { quantity } });
    return this.get(userId);
  }

  async remove(userId: string, productId: string): Promise<Cart> {
    await this.db.delete(cartItems).where(and(eq(cartItems.userId, userId), eq(cartItems.productId, productId)));
    return this.get(userId);
  }
}
Enter fullscreen mode Exit fullscreen mode

The comment in setQuantity() is the design decision of this section. The cart doesn't reserve stock. If adding to the cart held units, abandoned carts would hold the inventory, and one person filling a cart with 100 of something would take it off sale for everyone. Instead, GET /cart computes available for each line, from whether the product is still active and has enough stock right now, and the client can show it. The stock is taken at checkout, and only there.

The same goes for prices: the cart is priced at today's prices, and the order at the prices of the moment of checkout. Neither trusts a price the client sends, because the client never sends one.

Every signed-in user has a cart, so the controller declares @Can.Anyone() once, at the class level. There's no cart id in the routes: each query is scoped to the user from the token, so nobody can address someone else's cart:

// src/cart/cart.controller.ts
import { Body, Controller, Delete, Get, Param, Put } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { setQuantitySchema, type SetQuantityDto } from './cart.schemas.js';
import { CartService } from './cart.service.js';

const productId = { schema: z.uuid() };

// Every signed-in customer has a cart, and only sees their own.
@Can.Anyone()
@Controller('cart')
export class CartController {
  constructor(private readonly cartService: CartService) {}

  @Get()
  get(@CurrentUser('id') userId: string) {
    return this.cartService.get(userId);
  }

  @Put('items/:productId')
  setQuantity(
    @CurrentUser('id') userId: string,
    @Param('productId', productId) id: string,
    @Body({ schema: setQuantitySchema }) { quantity }: SetQuantityDto,
  ) {
    return this.cartService.setQuantity(userId, id, quantity);
  }

  @Delete('items/:productId')
  remove(@CurrentUser('id') userId: string, @Param('productId', productId) id: string) {
    return this.cartService.remove(userId, id);
  }
}
Enter fullscreen mode Exit fullscreen mode

The cart module registers the controller and the service:

// src/cart/cart.module.ts
import { Module } from '@nestjs/common';
import { CartController } from './cart.controller.js';
import { CartService } from './cart.service.js';

@Module({
  controllers: [CartController],
  providers: [CartService],
})
export class CartModule {}
Enter fullscreen mode Exit fullscreen mode

Checkout: the version that oversells

Checkout is where an e-commerce backend usually goes wrong. Here's the shape of the checkout most people write first: read the product, check the stock in JavaScript, write the new stock.

const [product] = await tx.select().from(products).where(eq(products.id, productId));
if (!product || product.stock < quantity) {
  throw new ConflictException('Not enough stock');
}
await tx.update(products).set({ stock: product.stock - quantity }).where(eq(products.id, productId));
Enter fullscreen mode Exit fullscreen mode

It's in a transaction, so it looks safe. It isn't. PostgreSQL's default isolation level is READ COMMITTED, and a plain SELECT takes no lock: two checkouts that run at the same moment both read a stock of 1, both pass the check, and both write 0. Two orders, one keyboard. The transaction doesn't help, because nothing in it stops the second checkout from reading the row before the first one writes it.

I didn't want to argue this from theory, so the tests at the end of this post include one: ten customers, each with the last unit in their cart, all checking out at once through a connection pool. With a read, a check in JavaScript and a write in place of the conditional UPDATE below, several of the ten got an order in every run.

Checkout: the version that doesn't (prevent overselling in PostgreSQL)

The fix is to make the check and the write the same statement. The checkout takes everything it needs with conditional statements, inside one transaction:

// src/orders/orders.service.ts
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, desc, eq, gte, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { cartItems, orderItems, orders, products, type Order, type OrderItem } from '../database/schema.js';

export type OrderWithItems = Order & { items: Omit<OrderItem, 'orderId'>[] };

@Injectable()
export class OrdersService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** Turns the user's cart into an order, or throws without changing anything. */
  checkout(userId: string): Promise<OrderWithItems> {
    return this.db.transaction(async (tx) => {
      // Taking the cart is the first statement. A second checkout of the same
      // cart waits for this transaction, then finds it empty.
      const taken = await tx.delete(cartItems).where(eq(cartItems.userId, userId)).returning();
      if (taken.length === 0) {
        throw new ConflictException('Your cart is empty');
      }
      // Lock products in one order across all checkouts, so two of them never deadlock.
      taken.sort((a, b) => a.productId.localeCompare(b.productId));

      const items: Omit<OrderItem, 'orderId'>[] = [];
      for (const { productId, quantity } of taken) {
        // Checks and takes the stock in one statement: no read-then-write window.
        const [product] = await tx
          .update(products)
          .set({ stock: sql`${products.stock} - ${quantity}` })
          .where(and(eq(products.id, productId), eq(products.active, true), gte(products.stock, quantity)))
          .returning({ name: products.name, price: products.price });
        if (!product) {
          // Rolls back the whole transaction: the cart and the other products are untouched.
          throw new ConflictException(`Not enough stock for product ${productId}`);
        }
        items.push({ productId, name: product.name, unitPrice: product.price, quantity });
      }

      const total = items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0);
      const [order] = await tx.insert(orders).values({ userId, status: 'placed', total }).returning();
      await tx.insert(orderItems).values(items.map((item) => ({ ...item, orderId: order.id })));
      return { ...order, items };
    });
  }

  // findMine(), findOne(), cancel() and ship() follow in the next section.
}
Enter fullscreen mode Exit fullscreen mode

The comment at the end of the class stands in for four more methods, which come in the next section. Here's what the checkout gets right, and why:

  • The stock is checked and taken by one UPDATE. Its WHERE clause requires enough stock. PostgreSQL locks the row while it updates it, so a second checkout's UPDATE waits for the first transaction to finish, then re-evaluates its WHERE clause against the stock the first one left. With 0 left, it updates no row, returns nothing, and the checkout throws. There's no window between the check and the write for another request to slip into.
  • Throwing rolls everything back. Drizzle's transaction() rolls back when its callback throws (see Transactions), so a checkout that fails on its third product leaves the first two products' stock and the whole cart exactly as they were. Nest turns the ConflictException into a 409.
  • The cart is taken first, with DELETE ... RETURNING. That's what makes a double-clicked checkout safe. If the same customer submits the checkout twice, the second request's DELETE waits on the first transaction's locks on the same rows, and once the first commits, it finds an empty cart and answers 409. One click, one order, without an idempotency key to manage. (The payment is a different matter; see the production checklist.)
  • Every checkout locks products in the same order. Two carts with the same two products, processed in opposite orders, would each lock one row and wait for the other's, and PostgreSQL would abort one of them as a deadlock. Sorting by product id means that can't happen.
  • The prices come from the UPDATE's RETURNING, so the order records the price at the moment the stock was taken, not whatever the cart showed earlier, and certainly not anything the client sent.
  • Every query goes through tx. A query on the injected this.db inside the callback would run on another connection from the pool, outside the transaction, and wouldn't be rolled back with it.

Cancel and ship orders without a race

An order moves from placed to either cancelled, by its customer, or shipped, by staff. Both moves are conditional updates on the current status. So when a customer cancels at the very moment a staff member ships, exactly one of them wins and the other gets a 409, instead of an order that's both shipped and cancelled, with its stock back on the shelf. Cancelling also puts the stock back, in the same transaction as the status change.

Here's the rest of OrdersService. These methods replace the comment at the end of the class above:

// src/orders/orders.service.ts
  findMine(userId: string): Promise<Order[]> {
    return this.db.select().from(orders).where(eq(orders.userId, userId)).orderBy(desc(orders.createdAt)).limit(100);
  }

  async findOne(userId: string, id: string): Promise<OrderWithItems> {
    const [order] = await this.db
      .select()
      .from(orders)
      .where(and(eq(orders.id, id), eq(orders.userId, userId)));
    if (!order) {
      throw new NotFoundException('Order not found');
    }
    return { ...order, items: await this.items(this.db, order.id) };
  }

  /** The owner cancels an order that hasn't shipped, and its stock goes back. */
  cancel(userId: string, id: string): Promise<Order> {
    return this.db.transaction(async (tx) => {
      // Conditional: of a cancel and a ship racing for the same order, one wins.
      const [order] = await tx
        .update(orders)
        .set({ status: 'cancelled' })
        .where(and(eq(orders.id, id), eq(orders.userId, userId), eq(orders.status, 'placed')))
        .returning();
      if (!order) {
        return this.refuse(tx, id, userId);
      }
      for (const { productId, quantity } of await this.items(tx, order.id)) {
        await tx
          .update(products)
          .set({ stock: sql`${products.stock} + ${quantity}` })
          .where(eq(products.id, productId));
      }
      return order;
    });
  }

  /** Staff mark a placed order as shipped. */
  async ship(id: string): Promise<Order> {
    const [order] = await this.db
      .update(orders)
      .set({ status: 'shipped' })
      .where(and(eq(orders.id, id), eq(orders.status, 'placed')))
      .returning();
    return order ?? this.refuse(this.db, id);
  }

  private items(db: Pick<NodePgDatabase, 'select'>, orderId: string) {
    return db
      .select({
        productId: orderItems.productId,
        name: orderItems.name,
        unitPrice: orderItems.unitPrice,
        quantity: orderItems.quantity,
      })
      .from(orderItems)
      .where(eq(orderItems.orderId, orderId))
      .orderBy(asc(orderItems.name));
  }

  /** Why a conditional update changed nothing: 404 if the order isn't there (or isn't theirs), 409 otherwise. */
  private async refuse(db: Pick<NodePgDatabase, 'select'>, id: string, userId?: string): Promise<never> {
    const [order] = await db
      .select({ status: orders.status })
      .from(orders)
      .where(and(eq(orders.id, id), userId ? eq(orders.userId, userId) : undefined));
    if (!order) {
      throw new NotFoundException('Order not found');
    }
    throw new ConflictException(`Order is already ${order.status}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

When a conditional update changes nothing, refuse() works out why: a 404 if the order isn't there, or isn't the caller's, and a 409 naming its status otherwise. Another customer's order is a 404, the same answer as an order that doesn't exist, so the API doesn't confirm which order ids are real. items() takes the database to read from as a parameter, so cancel() can read the order's items through its transaction.

Shipping is for staff, so it needs a second policy:

// src/orders/order.policy.ts
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';

@Policy()
export class OrderPolicy {
  ship(user: User | null) {
    return user?.role === 'staff';
  }
}
Enter fullscreen mode Exit fullscreen mode

The controller checks that policy on the ship route. The other routes are for any signed-in customer, and their queries are scoped to that customer:

// src/orders/orders.controller.ts
import { Controller, Get, HttpCode, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { OrderPolicy } from './order.policy.js';
import { OrdersService } from './orders.service.js';

const orderId = { schema: z.uuid() };

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  // Checkout: the cart becomes an order.
  @Can.Anyone()
  @Post()
  checkout(@CurrentUser('id') userId: string) {
    return this.ordersService.checkout(userId);
  }

  @Can.Anyone()
  @Get()
  findMine(@CurrentUser('id') userId: string) {
    return this.ordersService.findMine(userId);
  }

  @Can.Anyone()
  @Get(':id')
  findOne(@CurrentUser('id') userId: string, @Param('id', orderId) id: string) {
    return this.ordersService.findOne(userId, id);
  }

  @Can.Anyone()
  @Post(':id/cancel')
  @HttpCode(200)
  cancel(@CurrentUser('id') userId: string, @Param('id', orderId) id: string) {
    return this.ordersService.cancel(userId, id);
  }

  @Can(OrderPolicy, 'ship')
  @Post(':id/ship')
  @HttpCode(200)
  ship(@Param('id', orderId) id: string) {
    return this.ordersService.ship(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

POST /orders creates an order, so it answers 201, the default for a POST. Cancelling and shipping change an order that exists, so they answer 200, with @HttpCode(200).

The orders module registers both:

// src/orders/orders.module.ts
import { Module } from '@nestjs/common';
import { OrderPolicy } from './order.policy.js';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';

@Module({
  controllers: [OrdersController],
  providers: [OrdersService, OrderPolicy],
})
export class OrdersModule {}
Enter fullscreen mode Exit fullscreen mode

Try it

Start the application:

$ npm run start:dev
Enter fullscreen mode Exit fullscreen mode

Sign up a customer and a staff member, and promote the staff member with the UPDATE from the catalog section. Their tokens keep working after the promotion, since the role is read on every request. Tokens and response bodies are shortened here and below:

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ SAM="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
Enter fullscreen mode Exit fullscreen mode

Only staff add products. A customer gets a 403, staff get the product, and a price with a decimal point is a 400:

$ curl localhost:3000/products -H "$ADA" --json '{"name":"Mechanical keyboard","price":12900,"stock":5}'
{"message":"Forbidden","statusCode":403}
$ curl localhost:3000/products -H "$SAM" --json '{"name":"Mechanical keyboard","description":"Hot-swappable switches","price":12900,"stock":5}'
{"id":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","description":"Hot-swappable switches","price":12900,"stock":5,"active":true,"createdAt":"2026-11-19T20:04:12.673Z"}
$ curl localhost:3000/products -H "$SAM" --json '{"name":"Wrist rest","price":19.99,"stock":1}'
{"message":["price: Invalid input: expected int, received number"],"error":"Bad Request","statusCode":400}
Enter fullscreen mode Exit fullscreen mode

Fill the cart and check out. Off screen, staff added a wrist rest the same way, at 1999 cents, and Ada put one in her cart with a second PUT, which is why the order has two lines. The second checkout finds the cart already gone:

$ curl -X PUT localhost:3000/cart/items/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$ADA" --json '{"quantity":2}'
{"items":[{"productId":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","unitPrice":12900,"quantity":2,"available":true}],"total":25800}
$ curl -X POST localhost:3000/orders -H "$ADA"
{"id":"02ebc117-957f-4566-a2bb-e343afb01854","userId":"ed17ba4e-4d43-4aa4-9116-c6eda67ec2a7","status":"placed","total":27799,"createdAt":"2026-11-19T20:04:25.979Z","items":[{"productId":"afffc03b-...","name":"Mechanical keyboard","unitPrice":12900,"quantity":2},{"productId":"dc51c8f1-...","name":"Wrist rest","unitPrice":1999,"quantity":1}]}
$ curl -X POST localhost:3000/orders -H "$ADA"
{"message":"Your cart is empty","error":"Conflict","statusCode":409}
Enter fullscreen mode Exit fullscreen mode

Three keyboards are left. A cart that asks for four can't be checked out, and keeps its line, now marked unavailable:

$ curl -X PUT localhost:3000/cart/items/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$ADA" --json '{"quantity":4}'
$ curl -X POST localhost:3000/orders -H "$ADA"
{"message":"Not enough stock for product afffc03b-9142-4761-be96-84e6da07f8d4","error":"Conflict","statusCode":409}
$ curl localhost:3000/cart -H "$ADA"
{"items":[{"productId":"afffc03b-9142-4761-be96-84e6da07f8d4","name":"Mechanical keyboard","unitPrice":12900,"quantity":4,"available":false}],"total":51600}
Enter fullscreen mode Exit fullscreen mode

Staff raise the keyboard's price. The order keeps the price it was placed at. Cancelling it puts its stock back, and it can be cancelled only once:

$ curl -X PATCH localhost:3000/products/afffc03b-9142-4761-be96-84e6da07f8d4 -H "$SAM" --json '{"price":14900}'
$ curl localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854 -H "$ADA"
{"id":"02ebc117-...","status":"placed","total":27799,...,"items":[{"productId":"afffc03b-...","name":"Mechanical keyboard","unitPrice":12900,"quantity":2},...]}
$ curl -X POST localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854/cancel -H "$ADA"
{"id":"02ebc117-957f-4566-a2bb-e343afb01854","userId":"ed17ba4e-4d43-4aa4-9116-c6eda67ec2a7","status":"cancelled","total":27799,"createdAt":"2026-11-19T20:04:25.979Z"}
$ curl -X POST localhost:3000/orders/02ebc117-957f-4566-a2bb-e343afb01854/cancel -H "$ADA"
{"message":"Order is already cancelled","error":"Conflict","statusCode":409}
Enter fullscreen mode Exit fullscreen mode

Beyond that session: a customer who tries to ship an order gets a 403, staff who try to ship a cancelled order get a 409, and another customer asking for the order gets a 404.

Test the checkout race conditions against a real PostgreSQL

Everything that matters most in this app is about concurrency, and that rules out the usual shortcut. An in-process database like PGlite has a single connection, where requests never truly race. These tests run against a real PostgreSQL server, through a connection pool with up to 20 connections, and they send requests that run at the same time with app.inject(), which the Node adapter provides, so nothing listens on a port.

With Nest, that's a small change to an ordinary end-to-end test: boot the real AppModule, override the Drizzle provider with the pooled test database, and override PasswordHasher with a cheaper scrypt cost, since the default takes 128 MiB and a few hundred milliseconds per hash. The tests truncate the tables, so they get a database of their own:

// test/checkout.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { products, users } from '../src/database/schema.js';
import type { Role } from '../src/users/user.js';

// A real PostgreSQL with a pool, so concurrent checkouts really race.
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('Shop API (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  let app: NestNodeApplication;

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, products, refresh_tokens CASCADE`);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // scrypt at the default cost takes 128 MiB and a few hundred ms per hash.
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await app.init();
  });

  afterAll(() => app.close()); // closes the pool too

  let clients = 0;

  /** Signs a user up, and returns the headers that authenticate as them. */
  async function signUp(email: string, role: Role = 'customer') {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      // Each user signs up from an address of their own, as they would in
      // production: sign-up is rate-limited per IP address.
      remoteAddress: `10.0.0.${++clients}`,
    });
    await db.update(users).set({ role }).where(eq(users.email, email));
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  async function createProduct(stock: number) {
    const res = await app.inject({
      method: 'POST',
      url: '/products',
      headers: await signUp(`staff-${crypto.randomUUID()}@example.com`, 'staff'),
      payload: { name: 'Limited edition keycaps', price: 9900, stock },
    });
    expect(res.statusCode).toBe(201);
    return res.json<{ id: string }>().id;
  }

  it('lets only staff edit the catalog', async () => {
    const payload = { name: 'Desk mat', price: 2500, stock: 10 };
    const customer = await signUp('customer@example.com');
    expect((await app.inject({ method: 'POST', url: '/products', payload })).statusCode).toBe(401);
    expect((await app.inject({ method: 'POST', url: '/products', headers: customer, payload })).statusCode).toBe(403);
  });

  it('sells the last unit exactly once', async () => {
    const productId = await createProduct(1);
    const buyers = await Promise.all(Array.from({ length: 10 }, (_, i) => signUp(`buyer${i}@example.com`)));
    for (const headers of buyers) {
      await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 1 } });
    }

    const results = await Promise.all(buyers.map((headers) => app.inject({ method: 'POST', url: '/orders', headers })));

    expect(results.map((res) => res.statusCode).sort()).toEqual([201, ...Array(9).fill(409)]);
    const [{ stock }] = await db.select({ stock: products.stock }).from(products).where(eq(products.id, productId));
    expect(stock).toBe(0);
  });

  it('places one order when the same cart is checked out twice at once', async () => {
    const productId = await createProduct(10);
    const headers = await signUp('double-click@example.com');
    await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 2 } });

    const results = await Promise.all([1, 2].map(() => app.inject({ method: 'POST', url: '/orders', headers })));

    expect(results.map((res) => res.statusCode).sort()).toEqual([201, 409]);
    const orders = await app.inject({ method: 'GET', url: '/orders', headers });
    expect(orders.json()).toHaveLength(1);
  });

  it('puts the stock back when an order is cancelled', async () => {
    const productId = await createProduct(3);
    const headers = await signUp('cancel@example.com');
    await app.inject({ method: 'PUT', url: `/cart/items/${productId}`, headers, payload: { quantity: 3 } });
    const order = (await app.inject({ method: 'POST', url: '/orders', headers })).json<{ id: string }>();

    const cancelled = await app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers });
    expect(cancelled.json()).toMatchObject({ status: 'cancelled' });
    const product = await app.inject({ method: 'GET', url: `/products/${productId}` });
    expect(product.json()).toMatchObject({ stock: 3 });
    expect((await app.inject({ method: 'POST', url: `/orders/${order.id}/cancel`, headers })).statusCode).toBe(409);
  });
});
Enter fullscreen mode Exit fullscreen mode

Four tests, each about one guarantee:

  • Only staff edit the catalog: a guest gets a 401 and a customer a 403.
  • The last unit sells exactly once: ten buyers, one unit, all ten checkouts fired with Promise.all. One 201, nine 409s, and the stock ends at 0.
  • A double-submitted cart places one order: the same cart checked out twice at once gives one 201, one 409, and one order in GET /orders.
  • Cancelling puts the stock back: three units ordered, the order cancelled, the stock is 3 again, and a second cancel is a 409.

Each user signs up from an address of their own, through remoteAddress, because sign-up is rate-limited per IP address, as it would be in production. Sign-up allows ten per hour from one address (the @Throttle() on signUp(), in the appendix), and the suite signs up more users than that.

Create the test database once, then run the suite:

$ docker exec shop-db psql -U postgres -c "CREATE DATABASE shop_test"
$ TEST_DATABASE_URL=postgres://postgres:shop@localhost:5432/shop_test npm run test:e2e

 Test Files  1 passed (1)
      Tests  4 passed (4)
Enter fullscreen mode Exit fullscreen mode

A test that has only ever passed doesn't prove much, so make this one fail. Replace the stock UPDATE in checkout() with a read, a check in JavaScript and a write, like the version that oversells above, and "sells the last unit exactly once" fails: several of the ten customers get an order.

That output is from a run with only the checkout file. The refresh-token store test from the JWT API (in the appendix) applies here unchanged, and with it in test/ as well, Vitest picks up both files. They truncate tables of the same database, so run them one after the other:

$ npm run test:e2e -- --no-file-parallelism
Enter fullscreen mode Exit fullscreen mode

Production checklist for an e-commerce backend

Everything on the JWT API's production checklist applies: NODE_ENV=production, the signing secret in a secret store, migrations as a release step, CORS origins, JSON logs, shared throttler storage once there's more than one instance, trustProxy behind a load balancer, and the health probes. For the shop in particular:

  • Size the connection pool for checkout. Each checkout holds a connection for the length of its transaction, and checkouts of a popular product queue on its row lock. Keep the transaction short: nothing in checkout() waits on anything but the database, and it should stay that way. Call a payment provider before or after the transaction, never inside it.
  • Take payment with an idempotency key. A checkout is safe to retry, because the cart is gone after the first one. A payment isn't: a retried charge charges twice. The provider's API takes a key; send the order's id. To make your own payment endpoint safe to retry, see Idempotency keys.
  • Never trust a price from the client. The order's prices come from the products table at the moment of checkout, so a client that sends a price or a total is ignored by construction. Keep it that way when you add discounts.
  • Keep deactivating products instead of deleting them. Order items refer to them.
  • Watch checkout in production. Lock waits on a popular product show up as slow checkouts, not as errors. NestJS Observe records every request with a trace of its spans, SQL statements included, and p95 latency per route, so a checkout that slows down during a sale is visible before customers complain.
  • Give staff accounts a second factor. A staff token can rewrite the catalog's prices. See Add two-factor authentication, and require it on staff routes with @Authenticate().

What's next

Why Nest for this

The interesting code in this post is SQL, and it would be the same SQL in any framework. What Nest adds is everything around it, decided once: validation from schemas that also type the handlers and produce the OpenAPI document, authentication that's on for every route unless you opt out, authorization that denies routes that don't declare a rule, and a test module that swaps the database for a pooled test one in one line. In a shop backend that grows (payments, emails, an admin, more people working on it), those defaults are what keep the next route as safe as the first.

What's left below is the sign-in side's code, for copying. Its reasoning is in Build a REST API with JWT authentication in Node.js.

Appendix: the files from the JWT API

These are the JWT API's files as the shop uses them, already adapted: the role in UsersRepository, @Can.Anyone() on MeController (shown earlier), the shop realm and the "Shop API" title. The reasoning behind them is in the JWT tutorial's Sign users in with JWTs and the sections after it; here they're just the code.

Configuration, entry point and tooling

The environment schema, which ConfigModule checks at startup, so a missing secret or a malformed URL stops the app before it serves a request:

// src/config.ts
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // Signs the access tokens: at least 32 bytes.
  JWT_SECRET: z.string().min(32),
  // The browser origins allowed to call the API, comma-separated. None by default.
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
Enter fullscreen mode Exit fullscreen mode

The entry point runs on the Node adapter, writes JSON logs in production with passwords and tokens masked, sets security headers and CORS, enables shutdown hooks, and serves the OpenAPI document at /docs, with the bearer token required document-wide:

// src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  logger: new ConsoleLogger({
    // One JSON object per line in production; readable text in development.
    json: production,
    // Masks these properties wherever they appear in a logged object.
    redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
  }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

const document = new DocumentBuilder()
  .setTitle('Shop API')
  .setVersion('1.0')
  .addBearerAuth()
  .addSecurityRequirements('bearer')
  .build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));

await app.listen(config.get('PORT', { infer: true }));
Enter fullscreen mode Exit fullscreen mode

Drizzle Kit reads the schema and writes migrations to drizzle/:

// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/database/schema.ts',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});
Enter fullscreen mode Exit fullscreen mode

The Vitest configuration for the end-to-end tests sets the two required variables, so the configuration check passes; the tests replace the database connection themselves:

// vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Users

The repository, with the role in its columns. Only User objects leave it; password hashes stay inside:

// src/users/users.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.js';

const columns = { id: users.id, email: users.email, role: users.role, createdAt: users.createdAt };

/** Only `User` objects leave this class: password hashes stay inside. */
@Injectable()
export class UsersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** The new user, or `null` when the email is taken. */
  async create(email: string, passwordHash: string): Promise<User | null> {
    // One statement: two sign-ups with the same email can't both succeed.
    const [user] = await this.db
      .insert(users)
      .values({ email: normalize(email), passwordHash })
      .onConflictDoNothing({ target: users.email })
      .returning(columns);
    return user ?? null;
  }

  async findById(id: string): Promise<User | null> {
    const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
    return user ?? null;
  }

  /** For password sign-in only. */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
    const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
    if (!row) {
      return null;
    }
    const { passwordHash, ...user } = row;
    return { user, passwordHash };
  }

  async updatePasswordHash(id: string, passwordHash: string): Promise<void> {
    await this.db.update(users).set({ passwordHash }).where(eq(users.id, id));
  }
}

const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
Enter fullscreen mode Exit fullscreen mode

The users module exports the repository for the auth module, and holds the MeController from the catalog section:

// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';

@Module({
  controllers: [MeController],
  providers: [UsersRepository],
  exports: [UsersRepository],
})
export class UsersModule {}
Enter fullscreen mode Exit fullscreen mode

Authentication

The account email that the throttler's per-account limit keys on, normalized the same way as the repository's emails:

// src/auth/account-email.ts
/** The address the request body names, trimmed, lowercased and in Unicode NFC, or `''`. */
export function accountEmail(req: { body?: { email?: unknown } }): string {
  const email = req.body?.email;
  return typeof email === 'string' ? email.trim().normalize('NFC').toLowerCase() : '';
}
Enter fullscreen mode Exit fullscreen mode

This declaration tells @nestjs/authentication which type the signed-in user has, so @CurrentUser() is typed as the shop's User, role included:

// src/auth/auth-types.ts
import type { User } from '../users/user.js';

declare module '@nestjs/authentication' {
  interface AuthenticationTypes {
    user: User;
  }
}
Enter fullscreen mode Exit fullscreen mode

The request schemas for sign-up, sign-in and refresh tokens:

// src/auth/auth.schemas.ts
import { z } from 'zod';

export const signUpSchema = z.object({
  email: z.email(),
  password: z.string().min(12).max(128),
});
export type SignUpDto = z.infer<typeof signUpSchema>;

// No minimum here: a password set under an older rule still signs in.
export const signInSchema = z.object({
  email: z.email(),
  password: z.string().max(128),
});
export type SignInDto = z.infer<typeof signInSchema>;

export const refreshTokenSchema = z.object({
  refreshToken: z.string().min(1),
});
export type RefreshTokenDto = z.infer<typeof refreshTokenSchema>;
Enter fullscreen mode Exit fullscreen mode

CredentialsService registers users and checks passwords, at the same cost whether or not the email has an account:

// src/auth/credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class CredentialsService {
  constructor(
    private readonly usersRepository: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}

  async register(email: string, password: string): Promise<User> {
    const user = await this.usersRepository.create(email, await this.passwordHasher.hash(password));
    if (!user) {
      throw new ConflictException('Email already registered');
    }
    return user;
  }

  /** The user, or `null` when the email or the password is wrong. */
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // With no account, verify() checks a dummy hash, so the response
    // time doesn't reveal which emails are registered.
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found) {
      return null;
    }
    if (this.passwordHasher.needsRehash(found.passwordHash)) {
      await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
    }
    return found.user;
  }
}
Enter fullscreen mode Exit fullscreen mode

The refresh-token store keeps the package's tokens in the refresh_tokens table, so every instance of the API shares them. Spending a token is one conditional UPDATE, the same idea as the checkout's:

// src/auth/drizzle-refresh-token.store.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationStorage, type RefreshTokenRecord, type RefreshTokenStore } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, isNull, lte } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { refreshTokens } from '../database/schema.js';

/** Refresh tokens in PostgreSQL, shared by every instance of the API. */
@Injectable()
export class DrizzleRefreshTokenStore implements RefreshTokenStore {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    storage: AuthenticationStorage,
  ) {
    storage.registerSource({ refreshTokens: this });
  }

  async getRefreshToken(id: string): Promise<RefreshTokenRecord | undefined> {
    const [row] = await this.db.select().from(refreshTokens).where(eq(refreshTokens.id, id));
    if (!row) {
      return undefined;
    }
    const { revoked: _, usedAt, claims, ...token } = row;
    return { ...token, usedAt: usedAt ?? undefined, claims: claims ?? undefined };
  }

  async saveRefreshToken(record: RefreshTokenRecord): Promise<void> {
    await this.db.insert(refreshTokens).values(record);
    // Families past their absolute lifetime can go.
    await this.db.delete(refreshTokens).where(lte(refreshTokens.familyExpiresAt, record.createdAt));
  }

  async markRefreshTokenUsed(id: string, at: Date): Promise<boolean> {
    // Conditional: of two refreshes with the same token, one updates the row.
    const updated = await this.db
      .update(refreshTokens)
      .set({ usedAt: at })
      .where(and(eq(refreshTokens.id, id), isNull(refreshTokens.usedAt)))
      .returning({ id: refreshTokens.id });
    return updated.length === 1;
  }

  async revokeRefreshTokenFamily(familyId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.familyId, familyId));
  }

  async isRefreshTokenFamilyRevoked(familyId: string): Promise<boolean> {
    const revoked = await this.db
      .select({ id: refreshTokens.id })
      .from(refreshTokens)
      .where(and(eq(refreshTokens.familyId, familyId), eq(refreshTokens.revoked, true)))
      .limit(1);
    return revoked.length > 0;
  }

  async revokeUserRefreshTokens(userId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.userId, userId));
  }
}
Enter fullscreen mode Exit fullscreen mode

JwtAuth turns a verified access token into a user by loading it on every request, which is what makes a role change apply at once:

// src/auth/jwt-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly usersRepository: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    // The key, issuer and audience come from the `accessToken` options.
    super({ realm: 'shop' });
    registry.registerProvider(this);
  }

  // Called once the signature, `exp`, `iss` and `aud` checked out.
  // Returning null (the user was deleted) rejects the token.
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
Enter fullscreen mode Exit fullscreen mode

The auth controller signs users up and in, and refreshes and revokes tokens, with rate limits of its own:

// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
import {
  refreshTokenSchema,
  signInSchema,
  signUpSchema,
  type RefreshTokenDto,
  type SignInDto,
  type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';

@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly tokenService: TokenService,
  ) {}

  @SkipThrottle({ account: true })
  @Throttle({ default: { limit: 10, ttl: hours(1) } })
  @Post('sign-up')
  async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
    const user = await this.credentialsService.register(body.email, body.password);
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  @Throttle({
    default: { limit: 30, ttl: minutes(15) },
    account: { limit: 5, ttl: minutes(15) },
  })
  @Post('token')
  @HttpCode(200)
  async token(@Body({ schema: signInSchema }) body: SignInDto) {
    const user = await this.credentialsService.verify(body.email, body.password);
    if (!user) {
      throw new UnauthorizedException('Invalid email or password');
    }
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  // An unknown, expired or reused refresh token gets a 401.
  @Post('token/refresh')
  @HttpCode(200)
  refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    return this.tokenService.refresh(body.refreshToken);
  }

  // Signs this device out. Unknown tokens get the same answer, as in RFC 7009.
  @Post('token/revoke')
  @HttpCode(204)
  async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    await this.tokenService.revoke(body.refreshToken);
  }
}
Enter fullscreen mode Exit fullscreen mode

The auth module ties them together:

// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';

@Module({
  imports: [UsersModule],
  controllers: [AuthController],
  providers: [JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}
Enter fullscreen mode Exit fullscreen mode

Health checks

The readiness check runs select 1 against the database, with a one-second timeout:

// src/health/database.health.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { HealthIndicatorService } from '@nestjs/terminus';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

@Injectable()
export class DatabaseHealthIndicator {
  constructor(
    private readonly healthIndicatorService: HealthIndicatorService,
    @InjectDrizzle() private readonly db: NodePgDatabase,
  ) {}

  isHealthy(key: string) {
    return this.healthIndicatorService
      .check(key)
      .attempt(async () => {
        await this.db.execute(sql`select 1`);
      })
      .withTimeout('1s');
  }
}
Enter fullscreen mode Exit fullscreen mode

The health controller is public and skips rate limiting. live checks nothing but the process, and ready checks the database:

// src/health/health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { SkipThrottle } from '@nestjs/throttler';
import { DatabaseHealthIndicator } from './database.health.js';

@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly database: DatabaseHealthIndicator,
  ) {}

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([() => this.database.isHealthy('database')]);
  }
}
Enter fullscreen mode Exit fullscreen mode

And its module:

// src/health/health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { DatabaseHealthIndicator } from './database.health.js';
import { HealthController } from './health.controller.js';

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
  providers: [DatabaseHealthIndicator],
})
export class HealthModule {}
Enter fullscreen mode Exit fullscreen mode

The refresh-token store test

The second test file runs the contract suite that @nestjs/authentication ships against the store, on a real pool, with concurrent calls:

// test/refresh-token.store.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { AuthenticationStorage } from '@nestjs/authentication';
import { authenticationStoreContract } from '@nestjs/authentication/testing';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { DrizzleRefreshTokenStore } from '../src/auth/drizzle-refresh-token.store.js';

// A real PostgreSQL with a pool, where parallel calls really race.
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('DrizzleRefreshTokenStore', () => {
  const pool = new Pool({ connectionString: url });
  const db = drizzle({ client: pool });

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
  });
  afterAll(() => pool.end());

  /** The store on an empty table, registered nowhere: the suite builds its own registry. */
  async function emptyStore() {
    await pool.query('TRUNCATE refresh_tokens');
    return { refreshTokens: new DrizzleRefreshTokenStore(db, new AuthenticationStorage()) };
  }

  for (const c of authenticationStoreContract(emptyStore, { contracts: ['refreshTokens'], concurrent: true })) {
    it(c.name, c.run);
  }
});
Enter fullscreen mode Exit fullscreen mode

That's the whole application. The docs version of this article, kept up to date, is Build an e-commerce backend in Node.js.

Top comments (0)