All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- Nestjs NotificationKeep the FCM payload small and flat. Put routing identifiers and a stable notification type in `data`; convert every value, including dates, to strings. ```ts { token, notification: { title: 'Appointment reminder', body: 'Your appointment starts soon.' }, data: { notificationId: String(id), type: NotificationType.APPOINTMENT_REMINDER, appointmentId: String(appointmentId), occurredAt: occurredAt.toISOString(), }, } ``` Do not embed a full domain object or sensitive data. The client should fetc...Votes: 0GitHub stars: 549
- Nestjs ObservabilityUse `nestjs-pino` for high-throughput structured JSON logging. It integrates with Nest's logger and can attach request context, unlike scattered `console.log` calls. Configure it at bootstrap/module level, use a class context such as `new Logger(MyService.name)`, and emit structured fields for identifiers and outcomes. Include redaction for secrets and tokens, and choose `error` for 5xx failures versus `warn` for client errors. Keep performance benchmark headers behind a development feature f...Votes: 0GitHub stars: 549
- Nestjs ObservabilityGenerate or accept an `x-request-id` at the HTTP boundary, bind it to the request context with `nestjs-pino`/`AsyncLocalStorage`, and include it in every log line. Propagate the same ID to downstream HTTP/RPC calls and, where supported, database/query telemetry. Use structured fields rather than string concatenation: ```ts this.logger.info({ reqId, userId, orderId }, 'Order created'); ``` Return the ID in the response so a client can report it. Do not put tokens or sensitive payloads into the...Votes: 0GitHub stars: 549
- Nestjs ObservabilityExpose a Prometheus scrape endpoint such as `/metrics` with `@willsoto/nestjs-prometheus`, and register counters/histograms for request totals, errors, and latency. Keep labels bounded; never label by arbitrary user IDs or URLs. Also add Terminus health checks with separate liveness and readiness semantics. Liveness answers whether the process is alive; readiness checks dependencies such as PostgreSQL/Redis and can fail when heap is unsafe. Scrape `/metrics` from Prometheus and protect or iso...Votes: 0GitHub stars: 549
- Nestjs PerformanceMeasure first, then optimize the main buckets: total duration, database execution, and API overhead. A practical sequence is to switch to `FastifyAdapter`, enable compression, audit accidental request-scoped provider chains, and project only the columns each query needs. ```ts const app = await NestFactory.create(AppModule, new FastifyAdapter()); ``` Use keep-alive for upstream calls, indexes and bounded pagination for reads, and prevent N+1 queries with deliberate relations/DataLoader. For h...Votes: 0GitHub stars: 549
- Nestjs PerformanceUse the default singleton scope unless a provider genuinely needs request-local state such as tenant context or request caching. Request scope has a transitive cost: one request-scoped provider can make its dependency chain request-scoped and increase allocation/GC overhead on every request. Measure before opting in and document the reason. For multi-tenant context, consider durable providers or an explicit context carrier that avoids making the whole graph request-scoped. Do not use `REQUEST...Votes: 0GitHub stars: 549
- Nestjs PerformanceMove CPU-heavy work such as image processing, expensive crypto, or large transformations out of the HTTP event loop. Use `worker_threads` for CPU-bound local work, or enqueue a job to BullMQ/RabbitMQ when it should be retried and scaled independently. The request path should validate input, persist a job record, enqueue a job, and return a queued status. The worker performs the work and updates the record. Do not block the controller waiting for completion; make jobs idempotent and configure ...Votes: 0GitHub stars: 549
- Nestjs Real TimeChoose based on communication direction and scaling needs: - WebSockets are bidirectional and fit chat, collaboration, games, and frequent client-to-server events. They need handshake authentication and a Redis adapter when Socket.IO is spread across pods. - SSE is unidirectional server-to-client streaming and fits notifications, live feeds, tickers, and CI logs. It uses normal HTTP and is simpler to secure; use HTTP/2 at scale to avoid HTTP/1.1 browser connection limits. In NestJS, use `@Web...Votes: 0GitHub stars: 549
- Nestjs Real TimeUse Socket.IO's Redis adapter so every pod publishes events through Redis and clients connected to another pod receive them. Without it, a broadcast emitted on pod A is invisible to a client connected to pod B. Create shared Redis pub/sub clients, configure `@socket.io/redis-adapter`, and authenticate the handshake in `handleConnection()` before joining rooms. Configure the load balancer for WebSocket upgrades and use sticky sessions if the chosen transport/session design requires them. Test ...Votes: 0GitHub stars: 549
- Nestjs Real TimeAuthenticate during the WebSocket handshake, typically in `handleConnection()`, by extracting the token from the agreed handshake location and validating its signature and claims. Disconnect immediately when the token is missing or invalid; do not assume an HTTP guard protected the socket upgrade. ```ts handleConnection(client: Socket) { try { const token = client.handshake.auth?.token; const user = this.jwt.verify<UserClaims>(token, { audience: 'api', issuer: 'auth' }); client.data.user = us...Votes: 0GitHub stars: 549
- Nestjs SchedulingEvery pod registers and runs `@Cron()`, so three replicas naturally execute the job three times. Wrap the handler with a Redis distributed lock using an atomic `SET key randomValue NX PX ttl`; only the lock holder proceeds, and release only when the stored value still belongs to that holder. Register `ScheduleModule.forRoot()`, use a lock TTL longer than the expected enqueue operation, and test with at least two instances. Keep the cron handler short: enqueue a job ID to BullMQ, where a worke...Votes: 0GitHub stars: 549
- Nestjs SchedulingRegister `ScheduleModule.forRoot()`, use a named `CronExpression`, and wrap all scheduler logic in `try/catch`. In a multi-pod deployment, acquire a Redis/redlock lease before doing work so only one instance runs a given schedule. For anything expensive, have the cron handler enqueue an idempotent BullMQ job and let a worker handle retries, backoff, and execution. Set a lease TTL and renewal/release policy deliberately, add metrics for lock acquisition and failures, and verify behavior with m...Votes: 0GitHub stars: 549
- Nestjs SchedulingNo. A cron handler should schedule and enqueue work, not perform long-running processing on the Node event loop. Put the job ID or minimal payload on BullMQ and let a worker process it with retries, backoff, and bounded retention. The cron path still needs a distributed Redis lock in Kubernetes, `try/catch`, and idempotent enqueueing. This keeps schedule execution short, prevents duplicate work across pods, and lets worker capacity scale independently.Votes: 0GitHub stars: 549
- Nestjs SearchTreat PostgreSQL as the source of truth and synchronize Elasticsearch asynchronously. Avoid `await db.save(); await es.index()` in the request because a partial failure leaves the two systems inconsistent. Use an outbox/domain event or CDC: commit the database change, emit `EntityUpdated`, enqueue an indexing job, and let a worker transform the entity into a flatter search document with retries and idempotent document IDs. Debezium CDC is the strongest consistency option when operational comp...Votes: 0GitHub stars: 549
- Nestjs SearchUse a database index for structured equality/range/order queries and Elasticsearch when you need full-text relevance, fuzzy matching, complex filtering, or aggregations over a search document. Keep PostgreSQL/MySQL as the write source of truth and project flatter read documents into the search engine through an event-driven or CDC pipeline. Do not introduce Elasticsearch merely to replace a missing database index. Add the appropriate relational index first, measure query behavior, and accept ...Votes: 0GitHub stars: 549
- Nestjs SearchRun critical search E2E tests against a real `elasticsearch:8` container rather than mocking the client. Start the app and container in the test harness, apply the index mapping, write a database record, wait for the asynchronous indexing job, then query Elasticsearch and assert the result. Clean both the database and index between tests, use deterministic document IDs, and test retry/failure behavior. Unit tests may mock the `SearchService` for application logic, but mocks cannot verify mapp...Votes: 0GitHub stars: 549
- Nestjs Security IsolationEnforce tenant boundaries in both the application and database. Every child/family-linked table must enable PostgreSQL RLS in its creation migration, with policies based on a transaction-local setting such as `current_setting('app.current_user_id')`. Set that value in a trusted transaction context before queries. At the service boundary, call the centralized `ChildrenService.validateChildAccess(childId, userId)` before every persistence operation. Use nested routes such as `/children/:childId...Votes: 0GitHub stars: 549
- Nestjs Security IsolationTreat the new child-linked table as a security change. In its creation migration enable RLS and add policies that derive access from `current_setting('app.current_user_id')`; verify the application role cannot bypass the policy. Add indexes needed by policy predicates. Before every read/write, call the centralized `ChildrenService.validateChildAccess(childId, userId)` and expose the resource under `/children/:childId/...`, not a root ID route. Add the entity security JSDoc and document the ta...Votes: 0GitHub stars: 549
- Nestjs Security IsolationAvoid an unscoped `/users/:id` route for child data. A root ID makes it easy to forget the tenant/child boundary and can turn an identifier lookup into an authorization bypass. Use nested routes such as `/children/:childId/records/:recordId`, validate the authenticated user's membership through the centralized `ChildrenService`, and enforce PostgreSQL RLS as defense in depth. Every new child-linked table needs RLS policies and corresponding security documentation. Return DTOs, not raw entitie...Votes: 0GitHub stars: 549
- Nestjs SecurityUse `@nestjs/passport` with `passport-jwt`, enforce a signed algorithm such as RS256, and validate issuer and audience in the strategy. Register authentication globally as an `APP_GUARD`, then mark only deliberate public routes with a `@Public()` decorator. Access tokens should be short-lived (for example 15 minutes); keep refresh tokens long-lived and HTTP-only when cookie-based. Reject `none`, keep signing secrets/keys in a vault, and test unauthenticated requests return 401. Add Helmet, ex...Votes: 0GitHub stars: 549
- Nestjs SecurityImplement RBAC with metadata plus a guard. Define a typed roles decorator, bind the guard globally, and use `Reflector.getAllAndOverride` so method metadata overrides class metadata. ```ts export const Roles = (...roles: Role[]) => SetMetadata('roles', roles); canActivate(context: ExecutionContext) { const required = this.reflector.getAllAndOverride<Role[]>('roles', [ context.getHandler(), context.getClass(), ]); if (!required?.length) return true; const user = context.switchToHttp().getReque...Votes: 0GitHub stars: 549
- Nestjs SecurityApply a layered baseline: `app.use(helmet())` with an intentional CSP/HSTS policy, explicit CORS origins, a global auth guard with `@Public()` exceptions, Redis-backed throttling, and `ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })`. Use Passport JWT with RS256 (or a deliberately configured HS256), validate `iss`/`aud`, reject `none`, and keep access/refresh tokens short/HTTP-only as appropriate. Hash passwords with Argon2id, use CSRF protection for cookie auth, sanitize seri...Votes: 0GitHub stars: 549
- Nestjs TestingBuild a unit test module with the service under test and typed mocks for every dependency. Follow Arrange–Act–Assert and clear mocks after each test. ```ts const repo = { findById: jest.fn() } satisfies Pick<UserRepository, 'findById'>; const module = await Test.createTestingModule({ providers: [UsersService, { provide: UserRepository, useValue: repo }], }).compile(); const service = module.get(UsersService); afterEach(() => jest.clearAllMocks()); it('returns a user', async () => { repo.findB...Votes: 0GitHub stars: 549
- Nestjs TestingDo not mock the database in a critical NestJS E2E test. Start the app against a real isolated test database, because mocking removes the ORM, migrations, constraints, transactions, and query behavior that the E2E test is meant to verify. Create the app in `beforeAll`, close it and the database in `afterAll`, and clean state after each test with a transaction rollback or `TRUNCATE` in dependency order. Mocks are appropriate for unit tests; they should not replace the database in a full applica...Votes: 0GitHub stars: 549
- Nestjs TestingOverride the guard in the E2E testing module with a typed pass-through implementation: ```ts const moduleRef = await Test.createTestingModule({ imports: [AppModule], }) .overrideGuard(AuthGuard) .useValue({ canActivate: () => true }) .compile(); ``` If the application uses a global `APP_GUARD`, override that concrete guard/provider (or configure the test module with the same token) rather than assuming a route-level override is enough. Keep the real database for E2E tests, initialize/close th...Votes: 0GitHub stars: 549
- Nestjs TransportUse gRPC for synchronous, low-latency request/response calls between trusted internal services with a strongly typed `.proto` contract. Use RabbitMQ (or Kafka) for asynchronous domain events and fire-and-forget work where producers should be decoupled from consumer availability. gRPC makes the caller wait and needs service availability/timeouts; RabbitMQ adds broker operations and eventual consistency but supports buffering, retries, and multiple consumers. Keep `.proto`, DTOs, and interfaces...Votes: 0GitHub stars: 549
- Nestjs TransportUse transport-specific `RpcException` and a global RPC exception filter; an HTTP `HttpException` does not preserve the intended error contract over TCP/RPC. ```ts throw new RpcException({ code: 'ORDER_NOT_FOUND', message: 'Order not found' }); ``` The filter should map the error to a stable microservice response and log it with a correlation ID. Configure `ValidationPipe({ transform: true })` in the `MicroserviceOptions` bootstrap, not only in the HTTP app. Keep business errors transport-neut...Votes: 0GitHub stars: 549
- Nestjs TransportPut shared contracts in a dedicated `libs/contracts` package within the monorepo: DTOs, interfaces, event schemas, and `.proto` files. Each service imports only from that package, never from a sibling service's source tree. Version messages semantically and preserve existing field types; add optional fields for compatible evolution instead of changing a field in place. Generate gRPC clients/types from the versioned proto where appropriate, apply validation at each service boundary, and test c...Votes: 0GitHub stars: 549
- Nextjs App RouterCreate `app/dashboard/page.tsx` as the route UI, `app/dashboard/loading.tsx` for the Suspense skeleton, and `app/dashboard/error.tsx` as a Client Component error boundary: ```tsx // app/dashboard/error.tsx 'use client' export default function Error({ reset }: { reset: () => void }) { return <button onClick={reset}>Try again</button> } ``` Keep the page and layout as Server Components, and put interactive behavior only in leaf components. Add a `layout.tsx` when the dashboard needs persistent ...Votes: 0GitHub stars: 549
- Nextjs App RouterPlace the auth pages under a parenthesized route group, for example: ```text app/ (auth)/ login/page.tsx register/page.tsx forgot-password/page.tsx ``` The `(auth)` segment organizes layouts and code but is excluded from the URL, so the routes remain `/login`, `/register`, and `/forgot-password`. Add `app/(auth)/layout.tsx` for shared auth UI; route groups must not define conflicting paths.Votes: 0GitHub stars: 549
- Nextjs App RouterIn Next.js 15, request APIs are promises. Await `cookies()` wherever it is read, and apply the same migration to `headers()`, `params`, and `searchParams`: ```tsx import { cookies } from 'next/headers' export default async function Page() { const cookieStore = await cookies() const session = cookieStore.get('session') return <Dashboard session={session?.value ?? null} /> } ``` Update middleware, layouts, route handlers, and server actions too; run the async request API codemod or search for u...Votes: 0GitHub stars: 549
- Nextjs ArchitectureBecause the app has grown beyond a small project, group code by business domain rather than by file type. Introduce layers such as: ```text src/ shared/ # reusable UI, API clients, utilities entities/ # reusable domain data and logic features/ # user-facing actions, e.g. auth/login widgets/ # composed page sections app/ # routing only ``` Create slices with `ui/`, `model/`, `api/`, `lib/`, or `config/` segments and expose each slice through its top-level `index.t...Votes: 0GitHub stars: 549
- Nextjs ArchitectureMove data fetching and business logic out of `page.tsx`. In the App Router, keep the page as a thin composition of widgets or features; place data access in a DAL/service module and interactive logic in Client Components at leaf boundaries. Server Components can be async and call the DAL directly, while client-only behavior belongs behind `'use client'`. This preserves the App layer’s routing responsibility and avoids page-level `useEffect`/`fetch` waterfalls.Votes: 0GitHub stars: 549
- Nextjs ArchitectureDirect mutual imports violate the FSD rule that slices in the same layer cannot import one another. Break the cycle by moving shared domain data or behavior into a lower layer, usually `entities` or `shared`, and expose it through that slice’s public API. If the behavior is a higher-level user interaction, compose both features in a widget instead. Keep imports through each slice’s top-level `index.ts`, and verify that dependencies only point downward through the layer hierarchy.Votes: 0GitHub stars: 549
- Nextjs AuthenticationStore the JWT in an `HttpOnly`, `Secure` cookie with `SameSite: 'Lax'` or `'Strict'` and an appropriate expiration. Do not put access tokens in `localStorage`, `sessionStorage`, or Client Component props. Read and verify the cookie in middleware and in a server-side DAL/session helper before rendering protected data. For Server Actions and Route Handlers, also validate the request origin to reduce CSRF risk.Votes: 0GitHub stars: 549
- Nextjs AuthenticationUse middleware to read and verify the session cookie, then redirect unauthenticated requests: ```ts // middleware.ts import { NextResponse, type NextRequest } from 'next/server' export function middleware(request: NextRequest) { const session = request.cookies.get('session')?.value if (!session || !verifySession(session)) { const login = new URL('/login', request.url) login.searchParams.set('next', request.nextUrl.pathname) return NextResponse.redirect(login) } return NextResponse.next() } ex...Votes: 0GitHub stars: 549
- Nextjs AuthenticationYes. Treat every Server Action as a public server entry point: verify the session and authorize the operation inside the action, validate the input, and check the `Origin` (or trusted `Referer`) against the application origin before changing state. Keep the session in an `HttpOnly`, `Secure` cookie with `SameSite: 'Lax'` or `'Strict'`; SameSite is defense in depth, not a replacement for server-side checks.Votes: 0GitHub stars: 549
- Nextjs CachingInvalidate the cache owned by the profile mutation, then refresh the affected UI. Prefer a data tag when the profile is fetched in several places: ```ts revalidateTag(`profile:${userId}`) ``` Use `revalidatePath('/profile')` when the route itself is the correct ownership boundary, and `router.refresh()` when a Client Component needs to request a fresh server render. Ensure the read uses the same tag and that user-specific data is never placed in a shared cache. Test the complete mutation -> i...Votes: 0GitHub stars: 549
- Nextjs CachingUse ISR rather than per-request SSR: the posts are mostly static but need periodic freshness. Fetch with a revalidation interval, for example `next: { revalidate: 3600 }`, or configure an equivalent route revalidation policy. Use tags when posts are published or edited and need immediate on-demand invalidation. Reserve `no-store`/SSR for personalized or highly time-sensitive data, and verify that the chosen cache is not shared across user-specific responses.Votes: 0GitHub stars: 549
- Nextjs CachingDo not assume five Server Components necessarily produce five database calls, but make the deduplication boundary explicit. Wrap the shared server read with React `cache()` so repeated calls with the same arguments are deduplicated within one render pass: ```ts import { cache } from 'react' export const getUser = cache(async (id: string) => db.user.findUnique({ where: { id } })) ``` Use the Data Cache only when the data may be shared and cached safely; keep personalized data private or uncach...Votes: 0GitHub stars: 549
- Nextjs Data Access LayerYes, especially when multiple Server Components need the same authorization, DTO, caching, and error behavior. Put database/API access in a server-only module such as `lib/data.ts` or `services/`, import `'server-only'`, authenticate inside every DAL function, and return plain DTOs rather than ORM instances. Wrap repeated reads in React `cache()`. Client Components must not import the DAL; expose a Server Action or Route Handler as the bridge.Votes: 0GitHub stars: 549
- Nextjs Data Access LayerDo not return raw Prisma model objects. They can contain sensitive fields, ORM behavior, non-serializable values, and an unstable persistence shape. Select only required fields and map them to a plain DTO: ```ts return user && { id: user.id, name: user.name, email: user.email } ``` Keep the transformation and authorization inside the DAL, mark the module `server-only`, and taint sensitive references or values where the experimental taint API is enabled. Never pass password hashes or other pri...Votes: 0GitHub stars: 549
- Nextjs Data Access LayerA Client Component must not import the DAL or database client. Keep the query in a server-only DAL function, authenticate and authorize there, and return a minimal serializable DTO through one of these bridges: - Fetch it in a parent Server Component and pass the DTO as props. - Use a Server Action for a mutation or user-triggered read. - Use a Route Handler when the client needs an HTTP boundary. Do not fetch your own internal API from a Server Component; call the DAL directly on the server.Votes: 0GitHub stars: 549
- Nextjs Data FetchingMake the Server Component async and fetch data directly where it is needed: ```tsx export default async function Page() { const data = await fetch('https://example.com/data', { cache: 'force-cache' }).then((r) => r.json()) return <pre>{JSON.stringify(data)}</pre> } ``` For database access, call the DAL/service directly rather than your own `/api` route. Use `no-store` or revalidation settings according to freshness, and stream slow reads behind `Suspense` instead of blocking the entire route.Votes: 0GitHub stars: 549
- Nextjs Data FetchingUse `force-cache` for public/static data that can be reused, and `no-store` for request-specific or highly fresh data: ```ts fetch(url, { cache: 'force-cache' }) fetch(url, { cache: 'no-store' }) ``` For periodic freshness, use `next: { revalidate: 60 }`; for targeted mutations, use tags and `revalidateTag`. Do not put user-specific responses in a shared cache, and verify behavior after mutations instead of relying on cache assumptions.Votes: 0GitHub stars: 549
- Nextjs Data FetchingChoose the policy from freshness needs: `cache: 'force-cache'` for static data, `next: { revalidate: N }` for ISR, and `cache: 'no-store'` for request-time data. For mutations, call `revalidatePath('/route')` for route ownership or `revalidateTag('data-key')` for data ownership. Use `router.refresh()` when a Client Component needs a fresh server render, and test the full write/invalidate/read sequence.Votes: 0GitHub stars: 549
- Nextjs Data FetchingStart independent server reads together with `Promise.all()`: ```tsx const [products, categories] = await Promise.all([ getProducts(), getCategories(), ]) ``` This prevents an avoidable sequential waterfall. Keep dependent reads sequential, deduplicate repeated reads with React `cache()`, and wrap especially slow components in `Suspense` so the route can stream its shell.Votes: 0GitHub stars: 549
- Nextjs Data FetchingCall the database or service layer directly from the async Server Component; do not make an HTTP request to the application’s own `/api` route: ```tsx export default async function Page() { const products = await productService.list() return <ProductList products={products} /> } ``` Prefer a server-only DAL that authenticates, authorizes, returns DTOs, and applies caching policy. Use an internal Route Handler only when an actual HTTP boundary is required by a client or external consumer.Votes: 0GitHub stars: 549
- Nextjs Data FetchingUse Server Components for initial, SEO-relevant, or server-owned data: fetch close to the consuming component, keep secrets on the server, and use cache/revalidation policies. Use SWR for live, per-user, or frequently refreshed client data that benefits from focus revalidation, polling, or optimistic client updates. Do not mirror server data into `useState` with `useEffect`; choose SWR/React Query for client server-state behavior and keep UI-only state local.Votes: 0GitHub stars: 549
- Nextjs I18nUse a single URL-first locale convention, such as `/en/...` and `/fr/...`, with `next-intl`. Add `messages/en.json` and `messages/fr.json`, detect or redirect locales in `middleware.ts`, and place pages under `app/[lang]/`. Load messages in Server Components, generate locale params with `generateStaticParams`, and emit correct `hreflang` metadata. Run `next build` and verify both locale trees render.Votes: 0GitHub stars: 549