Frameworki

Node.js SMS API — wysyłka SMS w Express i TypeScript

Tomasz Lewandowski - Lead Developer, SMSIK 11 min czytania

Node.js napędza tysiące aplikacji backendowych. Dowiedz się, jak dodać SMS-y do swojego projektu — z użyciem fetch, TypeScript, Express i BullMQ.

Node.js napędza backendy tysięcy aplikacji — od startupów po duże platformy SaaS. Jeśli budujesz aplikację w Node.js (Express, Fastify, NestJS) i chcesz wysyłać SMS-y, ten artykuł pokaże Ci, jak to zrobić dobrze: z użyciem natywnego fetch, TypeScript, Express i BullMQ (kolejki).

Wymagania

  • Node.js 20+ (natywny fetch, --env-file)
  • TypeScript 5+ (opcjonalnie, ale zalecane)
  • Konto SMSIK z kluczem API
  • Opcjonalnie: BullMQ + Redis (dla kolejki)

Krok 1: Konfiguracja klucza API

W .env:

SMSIK_API_KEY=sk_live_TWOJ_KLUCZ
SMSIK_API_URL=https://smsik.pl/api/v1

W package.json dodaj skrypt startowy z --env-file (Node 20+):

{
  "scripts": {
    "start": "node --env-file=.env dist/index.js",
    "dev": "tsx watch --env-file=.env src/index.ts"
  }
}

Krok 2: Typy TypeScript

Utwórz src/types/sms.ts:

export interface SmsRequest {
  to_number: string;
  message: string;
  idempotency_key?: string;
}

export interface SmsResponse {
  id: number;
  status: 'queued' | 'scheduled' | 'sent' | 'delivered' | 'failed';
  to_number: string;
  price_grosze: number;
  scheduled_at?: string | null;
  expires_at?: string | null;
}

export class SmsikError extends Error {
  constructor(
    message: string,
    public readonly statusCode?: number,
    public readonly body?: string,
  ) {
    super(message);
    this.name = 'SmsikError';
  }
}

Krok 3: Serwis SMS (natywny fetch)

Utwórz src/services/smsik.ts:

import {
  SmsRequest,
  SmsResponse,
  SmsikError,
} from '../types/sms.js';

const API_URL = process.env.SMSIK_API_URL ?? 'https://smsik.pl/api/v1';
const API_KEY = process.env.SMSIK_API_KEY ?? '';

if (!API_KEY) {
  throw new Error('Brak SMSIK_API_KEY w zmiennych środowiskowych');
}

/**
 * Wysyła SMS przez SMSIK API.
 *
 * @throws {SmsikError} gdy API zwróci błąd lub wystąpi błąd sieci.
 */
export async function sendSms(request: SmsRequest): Promise<SmsResponse> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 30_000);

  try {
    const response = await fetch(`${API_URL}/sms/send`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
      signal: controller.signal,
    });

    const bodyText = await response.text();

    if (!response.ok) {
      console.error('SMSIK API error', {
        status: response.status,
        body: bodyText,
        to_number: request.to_number,
      });
      throw new SmsikError(
        `SMSIK API error ${response.status}`,
        response.status,
        bodyText,
      );
    }

    return JSON.parse(bodyText) as SmsResponse;
  } catch (err) {
    if (err instanceof SmsikError) {
      throw err;
    }
    if (err instanceof Error && err.name === 'AbortError') {
      throw new SmsikError('SMSIK timeout (30s)');
    }
    throw new SmsikError(
      `Błąd połączenia z SMSIK: ${err instanceof Error ? err.message : String(err)}`,
    );
  } finally {
    clearTimeout(timeoutId);
  }
}

Krok 4: Użycie w Express

Utwórz src/routes/orders.ts:

import { Router, Request, Response } from 'express';
import { sendSms } from '../services/smsik.js';
import { SmsikError } from '../types/sms.js';
import { orderQueue } from '../queues/orderQueue.js';

export const ordersRouter = Router();

ordersRouter.post('/orders', async (req: Request, res: Response) => {
  const { phone, product } = req.body as { phone: string; product: string };

  if (!phone || !product) {
    return res.status(400).json({ error: 'Brak phone lub product' });
  }

  // Utwórz zamówienie w bazie
  const orderId = Math.floor(Math.random() * 1_000_000);

  // Wyślij SMS w tle (BullMQ)
  await orderQueue.add(
    'send-confirmation-sms',
    {
      toNumber: phone,
      message: `Zamowienie #${orderId} przyjete. Dziekujemy!`,
      idempotencyKey: `order-${orderId}-confirmation`,
    },
    {
      attempts: 3,
      backoff: { type: 'exponential', delay: 60_000 },
    },
  );

  return res.status(201).json({ order_id: orderId });
});

Krok 5: BullMQ — kolejka

Utwórz src/queues/orderQueue.ts:

import { Queue } from 'bullmq';
import { Redis } from 'ioredis';

const connection = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379', {
  maxRetriesPerRequest: null,
});

export const orderQueue = new Queue('orders', { connection });

I worker src/workers/orderWorker.ts:

import { Worker, Job } from 'bullmq';
import { Redis } from 'ioredis';
import { sendSms } from '../services/smsik.js';

interface SmsJobData {
  toNumber: string;
  message: string;
  idempotencyKey: string;
}

const connection = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379', {
  maxRetriesPerRequest: null,
});

const worker = new Worker<SmsJobData>(
  'orders',
  async (job: Job<SmsJobData>) => {
    const { toNumber, message, idempotencyKey } = job.data;
    console.log(`[worker] Wysyłam SMS do ${toNumber}...`);
    const result = await sendSms({
      to_number: toNumber,
      message,
      idempotency_key: idempotencyKey,
    });
    console.log(`[worker] SMS ID: ${result.id}, status: ${result.status}`);
  },
  { connection, concurrency: 10 },
);

worker.on('failed', (job, err) => {
  console.error(`[worker] Job ${job?.id} failed:`, err.message);
});

console.log('Worker uruchomiony, czekam na zadania...');

Krok 6: Alternatywa — axios

Jeśli wolisz axios zamiast natywnego fetch:

import axios, { AxiosError } from 'axios';
import { SmsRequest, SmsResponse, SmsikError } from '../types/sms.js';

export async function sendSmsAxios(request: SmsRequest): Promise<SmsResponse> {
  try {
    const { data } = await axios.post<SmsResponse>(
      `${process.env.SMSIK_API_URL}/sms/send`,
      request,
      {
        headers: {
          'X-API-Key': process.env.SMSIK_API_KEY,
          'Content-Type': 'application/json',
        },
        timeout: 30_000,
      },
    );
    return data;
  } catch (err) {
    if (err instanceof AxiosError) {
      throw new SmsikError(
        `SMSIK API error ${err.response?.status}`,
        err.response?.status,
        JSON.stringify(err.response?.data),
      );
    }
    throw err;
  }
}

Krok 7: Testy

Użyj vitest lub jest. Przykład z vitest i mockiem fetch:

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { sendSms } from './smsik.js';

describe('sendSms', () => {
  beforeEach(() => {
    global.fetch = vi.fn();
  });

  it('wysyła SMS i zwraca odpowiedź', async () => {
    (global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
      ok: true,
      status: 200,
      text: async () =>
        JSON.stringify({
          id: 123,
          status: 'queued',
          to_number: '+48512017029',
          price_grosze: 1,
        }),
    });

    const result = await sendSms({
      to_number: '+48512017029',
      message: 'Test',
    });

    expect(result.id).toBe(123);
    expect(result.status).toBe('queued');
    expect(global.fetch).toHaveBeenCalledOnce();
  });

  it('rzuca SmsikError przy 400', async () => {
    (global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
      ok: false,
      status: 400,
      text: async () => '{"detail":"Invalid phone"}',
    });

    await expect(
      sendSms({ to_number: 'zły', message: 'Test' }),
    ).rejects.toThrow('SMSIK API error 400');
  });
});

Obsługa błędów — co robić?

HTTPCo robić
400Nie retry — błąd walidacji (zły numer, treść)
401Nie retry — zły klucz API
402Nie retry — doładuj konto
429Retry po Retry-After
5xxRetry z backoffem (3 próby, 60s, 2min, 10min)

Podsumowanie

  • ✅ Serwis sendSms() — reużywalny klient HTTP (natywny fetch)
  • ✅ Typy TypeScript — pełna kontrola nad żądaniem i odpowiedzią
  • ✅ Express — routing i obsługa requestów
  • ✅ BullMQ — wysyłka w tle, retry z backoffem
  • ✅ Testy — vitest z mockiem fetch
  • ✅ Alternatywa — axios dla tych, którzy wolą klasyczne biblioteki

Zarejestruj się bezpłatnie — 5 groszy na start.

Wyprobuj SMSIK bezplatnie

Rejestracja zajmuje 2 minuty. Otrzymasz 5 groszy na start.

Utworz darmowe konto