ShortIQ

ShortIQ

AI

50 AI Prompts for NestJS and TypeScript Backend Development

A practical set of 50 prompts for building production NestJS APIs with TypeScript. Covers modules, controllers, services, TypeORM, Prisma, JWT guards, pipes, interceptors, testing, and Docker deployment.

June 10, 2026ShortIQ Editorial Team

Advertisement

How to Use These Prompts Effectively

NestJS has a steeper learning curve than Express, but its decorator-based architecture, built-in dependency injection, and opinionated module system make it the right choice for teams building production TypeScript APIs. The challenge is that generating correct boilerplate for modules, guards, interceptors, and pipes is tedious without a clear mental model of how the pieces connect.

These 50 prompts cover the full NestJS development workflow. They are designed to be used with any capable model: ChatGPT, Claude, GitHub Copilot Chat, or Cursor. The more context you provide about your existing project structure, package versions, and naming conventions, the closer the output will be to something you can use directly.

  • Paste in your existing module or service file before running a prompt that modifies it
  • Specify your NestJS version and whether you are using TypeORM or Prisma
  • For complex prompts, split them: one for the service, one for the controller
  • Run setup prompts first if starting a new project; later prompts reference earlier files

Project Setup and Structure (Prompts 1-6)

Prompt 1: Generate a NestJS project structure for a SaaS API with four feature modules: users, auth, organisations, and billing. Show the folder structure, the AppModule importing all feature modules, and the main.ts with global pipes, CORS configuration, and a Swagger setup using @nestjs/swagger. Use NestJS 10 with TypeScript strict mode.

Prompt 2: Write a complete NestJS ProductsModule with ProductsController, ProductsService, and Product entity using TypeORM. Include all five CRUD endpoints with proper HTTP decorators, response codes, and TypeScript interfaces for request DTOs. Use class-validator for DTO validation. Prompt 3: Create a NestJS ConfigModule setup using @nestjs/config with a typed configuration service. Define an AppConfig interface with database, JWT, and SMTP config groups. Show how to validate environment variables on startup using Joi and how to inject the typed config into any service.

  • Prompt 4: Write the TypeORM configuration for a NestJS app connecting to PostgreSQL using ConfigService to read DATABASE_URL, entity auto-discovery, synchronize only in development, and connection pool settings for production.
  • Prompt 5: Create a NestJS global exception filter that catches all HttpExceptions and unknown errors, logs the full error context, and returns a consistent JSON error response with statusCode, message, and timestamp. Register it globally using APP_FILTER.
  • Prompt 6: Write a NestJS LoggingInterceptor that logs the HTTP method, route, response status code, and response time in milliseconds for every incoming request. Use NestJS Logger and register it globally as APP_INTERCEPTOR.

Controllers and Routes (Prompts 7-14)

Prompt 7: Write a NestJS UsersController with endpoints for GET /users with query params for page, limit, search, and sortBy; GET /users/:id; POST /users; PATCH /users/:id; and DELETE /users/:id. Use ParseIntPipe for the :id param, ValidationPipe for the body DTOs, and add Swagger decorators for all endpoints.

Prompt 8: Create a NestJS controller endpoint for handling file uploads using @nestjs/platform-express and multer. Accept a single image file (JPEG, PNG, WebP only, max 5MB), validate the file type and size with a custom FileInterceptor filter, save to a local uploads directory, and return the saved file URL. Prompt 9: Write a NestJS setup for API versioning using URI versioning. Show how to configure versioning in main.ts, how to apply a default version at the controller level, and how to override it at the route level for specific endpoints.

  • Prompt 10: Create a custom NestJS @CurrentUser() parameter decorator that extracts the authenticated user from the request object. Show the decorator implementation, how to type the returned user with a UserPayload interface, and an example controller using it alongside a JwtAuthGuard.
  • Prompt 11: Write a NestJS rate limiting setup using @nestjs/throttler. Configure a global limit of 60 requests per minute, a stricter limit on auth routes, and show how to skip rate limiting for health check endpoints using @SkipThrottle.
  • Prompt 12: Create a NestJS controller that handles short link redirection. Look up the short code in the database, increment the click count asynchronously, redirect to the destination URL with 302 status, and return 404 Not Found or 410 Gone for invalid or expired codes.
  • Prompt 13: Write a NestJS endpoint that streams a large CSV file from disk to the HTTP response without loading the entire file into memory. Use Node.js createReadStream, set Content-Disposition headers for download, and handle stream errors gracefully.
  • Prompt 14: Create a NestJS endpoint that accepts a batch of up to 100 user IDs and returns their data. Validate with @IsArray and @IsUUID, query with TypeORM findByIds, and return results in the same order as the input with null for any IDs not found.

Services and Business Logic (Prompts 15-22)

Prompt 15: Write a NestJS UsersService that injects a TypeORM repository using @InjectRepository(User). Implement findAll with cursor-based pagination, findByEmail, create with bcrypt password hashing, updateProfile, softDelete, and a helper that maps a User entity to a UserResponseDto excluding the password field.

Prompt 16: Write a NestJS service method that transfers credits between two user accounts inside a TypeORM transaction. Use EntityManager to run both updates atomically, roll back on failure, throw a custom InsufficientCreditsException when the sender balance is too low, and log the transaction with a correlation ID. Prompt 17: Create a NestJS email queue using @nestjs/bull and Redis. Define an EmailProcessor with @Process handlers for welcome, password-reset, and invoice emails. Show the EmailService that adds jobs to the queue with retry configuration and error handling.

  • Prompt 18: Write a NestJS service that caches expensive database queries using @nestjs/cache-manager with a Redis store. Cache a getUserById query with a 5-minute TTL, invalidate the cache on user update, and use a key pattern that covers all cached entries for a specific user.
  • Prompt 19: Create a NestJS event-driven pattern using @nestjs/event-emitter. When an order is created emit an OrderCreatedEvent. Write three async listeners: one sends a confirmation email, one updates inventory, one creates a Stripe invoice. Isolate failures so one listener does not block the others.
  • Prompt 20: Write a NestJS service that calls an external REST API using @nestjs/axios. Include retry logic with exponential backoff (max 3 retries), a 5-second timeout, error transformation mapping HTTP errors to NestJS HttpExceptions, GET request caching, and a health check method.
  • Prompt 21: Create a NestJS scheduled task using @nestjs/schedule that runs every day at 2am UTC. Find all users with expired trial accounts, mark them inactive, send them an email via a queue, log the count processed, and update a LastRunStats record with the run time and count.
  • Prompt 22: Write a NestJS Stripe webhook handler. Accept raw body for signature verification, verify the webhook signature, handle payment_intent.succeeded and customer.subscription.deleted events in background jobs, and return 200 immediately to avoid Stripe retries.

Database: TypeORM and Prisma (Prompts 23-30)

Prompt 23: Write TypeORM entities for a blog system with User (one-to-many with Post), Post (many-to-one with User, many-to-many with Tag), and Tag (many-to-many with Post). Include all relation decorators, cascade options, eager loading for Tag, and proper indexes on foreign keys and the post slug column.

Prompt 24: Write a TypeORM migration that adds an organisations table with UUID id, name, unique slug, planType enum (free, pro, enterprise), maxUsers with default 5, and timestamps. Then add an organisationId foreign key to the users table and backfill by creating an organisation record for each existing user.

Prompt 25: Write a TypeORM query builder that returns paginated analytics data: a list of short links with their total clicks, unique clicks, top country, and clicks in the last 7 days and 30 days. Join the links and clicks tables, use subqueries for time-filtered counts, filter by userId, and sort by total clicks descending.

  • Prompt 26: Implement soft delete in a TypeORM NestJS entity using @DeleteDateColumn. Write service methods for softDelete, restore, findAll (excludes deleted), findAllIncludingDeleted, and hardDelete. Include a subscriber that logs both events to an audit_log table.
  • Prompt 27: Write a complete Prisma integration for a NestJS app. Include a PrismaService extending PrismaClient that connects on init, disconnects on destroy, and implements soft-delete middleware. Show the PrismaModule setup and how to inject PrismaService into feature services.
  • Prompt 28: Write a NestJS service method using Prisma interactive transactions that creates an organisation, creates an admin user, creates a billing record, and sends a welcome event. Distinguish Prisma constraint violations (P2002 duplicate email) from unexpected errors.
  • Prompt 29: Write a NestJS database seed script using TypeORM that creates admin users with hashed passwords, 10 test users with faker, 5 organisations each with 2 users, and 50 sample products. Make it idempotent by skipping records that already exist.
  • Prompt 30: Implement full-text search for blog posts using PostgreSQL in a NestJS service. Use TypeORM query builder with to_tsvector, create a GIN index in a migration, rank results with ts_rank, and return paginated results with match snippets using ts_headline.

Authentication and Guards (Prompts 31-36)

Prompt 31: Write a complete NestJS AuthModule with JWT authentication. Include AuthService with login, register, and refreshToken methods; JwtStrategy that validates the access token; RefreshTokenStrategy; AuthController with login, register, refresh, and logout endpoints; and a JwtAuthGuard. Use @nestjs/jwt and @nestjs/passport.

Prompt 32: Create a NestJS RBAC system using a custom RolesGuard and @Roles() decorator. Define a UserRole enum with admin, manager, and member values. The guard reads required roles from route metadata, checks them against the authenticated user role, and throws ForbiddenException with a descriptive message if access is denied.

  • Prompt 33: Write a NestJS API key authentication strategy using Passport. Read the X-API-Key header, look up the hashed key in the database, verify the hash, update last_used_at, and return the user payload. Include the ApiKey entity and the service method to generate a new API key.
  • Prompt 34: Implement Google OAuth2 login in NestJS using passport-google-oauth20. Write the GoogleStrategy with profile mapping, the AuthService method that finds or creates a user, handles email conflicts with existing password accounts, and the callback controller that creates a JWT, sets it in a secure HttpOnly cookie, and redirects to the frontend.
  • Prompt 35: Write a NestJS resource ownership guard that checks whether the authenticated user owns the requested resource before allowing the operation. Read the resource ID from route params, query the database, and throw NotFoundException (not ForbiddenException) if the check fails to avoid leaking resource existence.
  • Prompt 36: Implement TOTP-based two-factor authentication in a NestJS AuthService. Include generateTwoFactorSecret with a QR code URI using otplib, enableTwoFactor that verifies the first code before saving, verifyTwoFactor that validates a submitted code, and the login flow changes needed to add the 2FA verification step.

Pipes, Interceptors, and Filters (Prompts 37-42)

Prompt 37: Write a NestJS TransformInterceptor that wraps all successful API responses in a consistent envelope: { success: true, data: <original response>, timestamp: <ISO string> }. Exclude streams and file downloads. Register globally and show how to opt out with a @NoTransform() decorator.

Prompt 38: Create a NestJS custom ValidationPipe that extends the built-in one, strips unknown properties, throws on unknown properties in strict mode, translates class-validator messages into a structured errors object with field name and message, and adds a request ID to each validation error response. Prompt 39: Write a custom NestJS ParseUUIDPipe that validates a route parameter is a valid UUID v4, throws BadRequestException if not valid, and also checks that the resource exists in the database using the ModuleRef pattern for repository injection.

  • Prompt 40: Create a NestJS AuditInterceptor that logs every state-changing request (POST, PUT, PATCH, DELETE) to an audit_logs table. Capture userId, HTTP method, endpoint, request body with sensitive fields redacted, response status, and timestamp. Use async database writes via rxjs tap operator.
  • Prompt 41: Write a NestJS exception filter for Prisma errors. Map P2002 (unique constraint) to 409 Conflict with the duplicate field name, P2025 (record not found) to 404, P2003 (foreign key constraint) to 400 Bad Request, and fall through to 500 for unknown Prisma errors.
  • Prompt 42: Write a NestJS TimeoutInterceptor that cancels requests taking longer than a configurable timeout (default 30 seconds). Use rxjs timeout and catchError, log a warning with the endpoint and elapsed time, and throw a 408 RequestTimeoutException. Make the timeout configurable per-route with a @Timeout(ms) decorator.

Testing (Prompts 43-47)

Prompt 43: Write Jest unit tests for a NestJS UsersService. Mock the TypeORM UserRepository using jest.fn(), test findAll with pagination, test that create hashes the password before saving, test that findByEmail returns undefined for unknown emails, and test that update throws NotFoundException when the user does not exist.

Prompt 44: Write a NestJS controller unit test using Test.createTestingModule. Mock the UsersService completely, test that GET /users returns the service result with a 200 status, test that POST /users with an invalid body returns 400, test that PATCH /users/:id calls the service with the correct parameters, and test DELETE returns 204. Prompt 45: Write unit tests for a NestJS JwtAuthGuard. Test that a valid JWT in the Authorization header sets the user on the request and returns true. Test that a missing token throws UnauthorizedException. Test that an expired token throws UnauthorizedException with an expiry message.

  • Prompt 46: Write a NestJS integration test for the UsersModule using an in-memory SQLite database with TypeORM. Create the test module with the real UsersService and UsersController, seed a test user before each test, test the full create and findOne flow without mocking the database, and clean up after each test.
  • Prompt 47: Write an end-to-end test for a NestJS authentication flow using Supertest. Test the full sequence: register a new user, attempt to register the same email (expect 409), login with correct credentials (expect JWT), access a protected endpoint with the JWT, access the same endpoint without a JWT (expect 401), and call the logout endpoint.

Docker and Deployment (Prompts 48-50)

Prompt 48: Write a multi-stage Dockerfile for a NestJS application. Stage 1 installs all dependencies and builds the TypeScript. Stage 2 copies only the dist folder and production node_modules into a minimal Node.js Alpine image. Set NODE_ENV to production, create a non-root user, expose port 3000, and add a health check that calls /health.

Prompt 49: Write a docker-compose.yml for local NestJS development with hot reload. Include services for the NestJS app with ts-node-dev and src volume mount, PostgreSQL 16 with a named volume, Redis 7 for the Bull queue and cache, and pgAdmin for database management. Add a health check dependency so the app waits for Postgres to be ready. Prompt 50: Write a GitHub Actions workflow for a NestJS application that runs lint, unit tests, and e2e tests in parallel jobs; builds and pushes a Docker image on merge to main; SSHes into a production VPS, pulls the new image, runs database migrations, and restarts the container with zero downtime using a rolling update strategy.

FAQ

Can I use these prompts with Claude or ChatGPT?

Yes. They work with any capable model. Claude tends to follow structural instructions more precisely, which helps with NestJS module patterns. Paste in your existing files and specify your NestJS version for the best output.

Do these prompts work with older NestJS versions?

They are written for NestJS 10, but most work fine with NestJS 8 and 9. The main differences are in some decorator imports and the @nestjs/config module API. If you get TypeScript errors, add your specific version to the prompt and ask the model to adjust.

Should I use TypeORM or Prisma with NestJS?

Prisma is the better choice for new projects in 2026. It generates a fully typed client from your schema, has better TypeScript inference, and simpler migration tooling. TypeORM is still widely used and better supported for legacy projects. The prompts in this list cover both.

How do I pick the right number of Gunicorn workers for a NestJS API?

NestJS runs on Node.js, so you do not use Gunicorn (that is Python). For Node.js clustering, use PM2 with the cluster mode. A common starting point is one worker per CPU core. For I/O-heavy NestJS applications, a single process with async handlers is often sufficient.

Do I need to add Swagger to every NestJS project?

Not required, but strongly recommended for any API that other developers or clients will consume. Prompt 1 in this list includes Swagger setup. The @ApiProperty() decorators on your DTOs also serve as living documentation that helps when debugging request validation issues.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.