typescript
import { http, HttpResponse } from 'msw';

export interface Product {
  id: number;
  name: string;
}

MSW for frontend API mocking in tests

testing frontend react
by codesnips 4 tabs
typescript
import { readFileSync } from 'fs';
import { join } from 'path';
import Handlebars from 'handlebars';
import mjml2html from 'mjml';
import { htmlToText } from 'html-to-text';

Email sending with nodemailer + templates

node email nodemailer
by codesnips 3 tabs
typescript
type AsyncTask = () => Promise<void>;

export interface GuardOptions {
  name: string;
  logger?: Pick<Console, "info" | "warn" | "error">;
}

Cron scheduling with node-cron (with guard)

reliability node-cron cron
by codesnips 3 tabs
typescript
import { Queue } from "bullmq";
import { createHash } from "crypto";

export const connection = { host: "127.0.0.1", port: 6379 };

export interface ChargePayload {

BullMQ job idempotency via dedupe id

node redis background-jobs
by codesnips 3 tabs
sql
CREATE TABLE subscriptions (
    id                  BIGGENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id         BIGINT       NOT NULL,
    plan_code           TEXT         NOT NULL,
    status              TEXT         NOT NULL DEFAULT 'active',
    current_period_end  TIMESTAMPTZ  NOT NULL,

Partial index for “active” rows in Postgres

postgres performance sql
by codesnips 3 tabs
typescript
import { Pool } from "pg";

async function keyFor(pool: Pool, name: string): Promise<string> {
  const { rows } = await pool.query<{ key: string }>(
    "SELECT hashtextextended($1, 0) AS key",
    [name]

Postgres advisory lock for one-at-a-time work

postgres concurrency reliability
by codesnips 3 tabs
sql
CREATE TABLE password_reset_tokens (
  id          BIGSERIAL PRIMARY KEY,
  user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  token_hash  TEXT NOT NULL,
  expires_at  TIMESTAMPTZ NOT NULL,
  used_at     TIMESTAMPTZ,

Password reset tokens: hash + expiry

security express authentication
by codesnips 3 tabs
typescript
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";

const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";

JWT access + refresh token rotation (conceptual)

security node jwt
by codesnips 3 tabs
typescript
const rawOrigins = process.env.ALLOWED_ORIGINS ?? "";

export const allowedOrigins = new Set(
  rawOrigins
    .split(",")
    .map((o) => o.trim())

CORS configuration that’s explicit (no *)

security http express
by codesnips 3 tabs
typescript
import { createHash } from "crypto";
import { Request, Response } from "express";

export function computeEtag(body: string): string {
  const digest = createHash("sha1").update(body).digest("base64");
  return `"${digest}"`;

ETag + conditional GET for read-heavy endpoints

performance express http-caching
by codesnips 3 tabs
typescript
import { Agent as HttpAgent } from 'http';
import { Agent as HttpsAgent } from 'https';

const shared = {
  keepAlive: true,
  keepAliveMsecs: 1_000,

HTTP keep-alive agent for outbound calls

http performance nodejs
by codesnips 3 tabs
typescript
export class TimeoutError extends Error {
  constructor(public readonly ms: number) {
    super(`Request timed out after ${ms}ms`);
    this.name = "TimeoutError";
  }
}

HTTP client timeout with AbortController (fetch)

fetch abortcontroller timeout
by codesnips 3 tabs