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 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" 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 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= 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; } 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 }; 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; Most of the bugs a shop can have are decided by a few lines of that file:
- Prices are integers, in cents.
19.99has no exact floating-point representation, and a total of many of them drifts.1999doesn't. Every price and total in this API is a whole number of cents, and aCHECKkeeps 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
activeflag and noDELETE /products/:id. -
stockcan't go below zero. That's theproducts_stock_not_negativeconstraint. 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 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) ); 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 {} 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.control...