typehook
v2.0.0
Published
Type-safe webhook handler for TypeScript : verify, route, and handle webhooks from any provider
Maintainers
Readme
typehook
The problem
Every time you integrate Stripe, GitHub, or Clerk webhooks, you write the same boilerplate: verify the signature, parse the payload, route by event type, handle errors. For every provider. In every project.
typehook does all of that in one setup.
Install
npm install typehookQuickstart
import { createTypehook } from 'typehook';
const th = createTypehook({
providers: {
stripe: { secret: process.env.STRIPE_WEBHOOK_SECRET! },
github: { secret: process.env.GITHUB_WEBHOOK_SECRET! },
clerk: { secret: process.env.CLERK_WEBHOOK_SECRET! },
},
});
// Fully typed : TypeScript knows exactly what each event contains
th.on('stripe', 'payment_intent.succeeded', async (event) => {
console.log(event.payload.data.object.amount); // number
});
th.on('github', 'push', async (event) => {
console.log(event.payload.commits); // Commit[]
});
th.on('clerk', 'user.created', async (event) => {
console.log(event.payload.data.email_addresses); // EmailAddress[]
});Framework integration
Express
import { typehookExpress } from 'typehook/express';
// Raw body required : add express.raw() before this route
app.use('/webhooks/:provider', express.raw({ type: '*/*' }));
app.post('/webhooks/:provider', typehookExpress(th));Hono
import { typehookHono } from 'typehook/hono';
app.post('/webhooks/:provider', typehookHono(th));Fastify
import { typehookFastify } from 'typehook/fastify';
fastify.post('/webhooks/:provider', typehookFastify(th));Next.js App Router
import { typehookNext } from 'typehook/nextjs';
export const POST = typehookNext(th);
// route: app/webhooks/[provider]/route.tsWhat it handles for you
Signature verification - every provider uses a different algorithm. typehook handles HMAC-SHA256, Svix, and timestamp tolerance out of the box.
Full type inference - payment_intent.succeeded and customer.deleted return different types. TypeScript knows which is which without a single cast.
Idempotency - duplicate events are detected and ignored automatically. Memory adapter by default, Redis or Prisma optionally.
Retry with backoff - if your handler throws, typehook retries with exponential backoff. Configurable per handler.
Middleware pipeline - run logic before or after every event, globally or per provider.
Event replay - re-process any stored event by ID.
Supported providers
| Provider | Events | |----------|--------| | Stripe | payment_intent, customer, subscription, invoice, checkout, refund, dispute | | GitHub | push, pull_request, issues, release, workflow_run, star, fork | | Clerk | user, session, organization, organizationMembership | | Shopify | orders, products, customers, fulfillments | | Linear | Issue, Comment, Project, IssueLabel, Cycle | | Resend | email.sent, email.delivered, email.bounced, email.complained, email.clicked |
Middleware
// Global - runs before every handler
th.use(async (event, next) => {
console.log(`[${event.provider}] ${event.type}`);
await next();
});
// Per provider
th.use('stripe', async (event, next) => {
if (!event.livemode) return; // ignore test events in production
await next();
});Handler options
th.on('stripe', 'invoice.payment_failed', handleFailedPayment, {
retries: 3,
onSuccess: (event) => logger.info('invoice handled', event.id),
onError: (err, event) => logger.error(err, event.id),
onRetry: (attempt, event) => logger.warn(`retry ${attempt}`, event.id),
});Idempotency adapters
// Default - in-memory, zero config
const th = createTypehook({ providers: { stripe: { secret: '...' } } });
// Redis
import { RedisAdapter } from 'typehook/adapters';
const th = createTypehook({
providers: { stripe: { secret: '...' } },
adapter: new RedisAdapter({ url: process.env.REDIS_URL! }),
});
// Prisma
import { PrismaAdapter } from 'typehook/adapters';
const th = createTypehook({
providers: { stripe: { secret: '...' } },
adapter: new PrismaAdapter({ client: prisma }),
});Event replay and inspection
// Replay a stored event
await th.replay('evt_001');
// List failed events
const failed = await th.failed();
// List events by provider
const stripeEvents = await th.events('stripe', { limit: 50 });License
MIT -- built by bbenito# typehook
