@the_shujaa/link-shortener
v0.1.1
Published
A self-hosted link shortener Convex component for custom domains. Create, update, and revoke short codes with built-in redirect handling, click analytics, UTM parameter tracking, and configurable rate limiting.
Downloads
177
Maintainers
Readme
@the_shujaa/link-shortener
A self-hosted link shortener Convex component for custom domains. Create short links with click analytics, UTM tracking, rate limiting, password protection, and configurable redirects -- all running on your own Convex deployment.
https://yourdomain.com/r/abc1234 --> https://example.com/very/long/pathFeatures
- Short link CRUD -- auto-generated 7-char codes (3.5 trillion combinations) or custom codes
- Click analytics -- clicks over time, top referrers, geographic breakdown, unique visitors
- UTM parameter handling -- capture, strip, or passthrough modes per link
- Password-protected links -- SHA-256 hashed with per-link salt, constant-time comparison
- Configurable redirects -- 301 (permanent) or 302 (temporary) per link
- Link expiration -- optional TTL with lazy expiration checks
- Rate limiting -- configurable per-user sliding window
- IP privacy -- IPs are SHA-256 hashed with a daily rotating salt, never stored in plaintext
- Link metadata -- optional title and tags for organization
Installation
npm install @the_shujaa/link-shortener1. Register the component
Create or update convex/convex.config.ts:
// convex/convex.config.ts
import { defineApp } from "convex/server";
import linkShortener from "@the_shujaa/link-shortener/convex.config.js";
const app = defineApp();
app.use(linkShortener);
export default app;2. Mount the redirect handler
Create or update convex/http.ts:
// convex/http.ts
import { httpRouter } from "convex/server";
import { registerRoutes } from "@the_shujaa/link-shortener";
import { components } from "./_generated/api";
const http = httpRouter();
registerRoutes(http, components.linkShortener, {
pathPrefix: "/r/",
});
export default http;Short links will be accessible at
https://<your-deployment>.convex.site/r/<code>.
For custom domain setups, use pathPrefix: "/" to serve codes at the root.
3. Expose functions to your frontend
Use exposeApi() to create authenticated Convex functions that your React app
can call directly:
// convex/links.ts
import { exposeApi } from "@the_shujaa/link-shortener";
import { components } from "./_generated/api";
export const {
createLink,
getLink,
listMyLinks,
revokeLink,
updateLink,
deleteLink,
getLinkStats,
getClicksOverTime,
getTopReferrers,
getGeoBreakdown,
checkPassword,
initConfig,
getConfig,
} = exposeApi(components.linkShortener, {
auth: async (ctx, _operation) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Not authenticated");
return identity.subject;
},
});Then call these from React:
import { useMutation, useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
function App() {
const links = useQuery(api.links.listMyLinks, {});
const createLink = useMutation(api.links.createLink);
return (
<button
onClick={() => createLink({ destinationUrl: "https://example.com" })}
>
Shorten Link
</button>
);
}4. Initialize config
Call initConfig once to set up the component's configuration table. This is
idempotent and safe to call multiple times:
// In your app initialization, or from a client mutation:
await createLink.initConfig({});Or from the React client:
const initConfig = useMutation(api.links.initConfig);
// Call once on first load
useEffect(() => {
initConfig({});
}, []);Usage
Direct component calls
For more control, call component functions directly from your Convex functions:
// convex/myFunctions.ts
import { mutation, query } from "./_generated/server";
import { components } from "./_generated/api";
import { v } from "convex/values";
export const createShortLink = mutation({
args: {
url: v.string(),
customCode: v.optional(v.string()),
expiresInHours: v.optional(v.number()),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Not authenticated");
const expiresAt = args.expiresInHours
? Date.now() + args.expiresInHours * 60 * 60 * 1000
: undefined;
return ctx.runMutation(components.linkShortener.links.create, {
destinationUrl: args.url,
createdBy: identity.subject,
code: args.customCode,
expiresAt,
});
},
});
export const getAnalytics = query({
args: { code: v.string() },
handler: async (ctx, args) => {
const [stats, clicks, referrers, geo] = await Promise.all([
ctx.runQuery(components.linkShortener.analytics.linkStats, args),
ctx.runQuery(components.linkShortener.analytics.clicksOverTime, {
...args,
granularity: "day",
}),
ctx.runQuery(components.linkShortener.analytics.topReferrers, {
...args,
limit: 10,
}),
ctx.runQuery(components.linkShortener.analytics.geoBreakdown, args),
]);
return { stats, clicks, referrers, geo };
},
});Class-based client
For apps that prefer an object-oriented interface:
import { LinkShortener } from "@the_shujaa/link-shortener";
import { components } from "./_generated/api";
const linkShortener = new LinkShortener(components.linkShortener, {
defaultRedirectType: 302,
defaultUtmConfig: "passthrough",
rateLimitPerMinute: 60,
rateLimitEnabled: true,
});
// In a mutation handler:
export const createLink = mutation({
args: { url: v.string() },
handler: async (ctx, args) => {
await linkShortener.initConfig(ctx);
return linkShortener.createLink(ctx, {
destinationUrl: args.url,
createdBy: "user-id",
});
},
});API Reference
Link operations
| Function | Type | Description |
| --------------------- | -------- | ---------------------------------------------- |
| links.create | mutation | Create a short link |
| links.update | mutation | Update destination, redirect type, expiration |
| links.revoke | mutation | Soft-delete (preserves analytics) |
| links.hardDelete | mutation | Permanently delete link + all clicks |
| links.resolve | query | Resolve code to destination URL |
| links.get | query | Get full link details (excludes password hash) |
| links.listByUser | query | List all links for a user |
| links.checkPassword | query | Verify password for a protected link |
Analytics
| Function | Type | Description |
| -------------------------- | ----- | --------------------------------------------------- |
| analytics.clicksOverTime | query | Click counts grouped by hour, day, or week |
| analytics.topReferrers | query | Top referring domains with counts |
| analytics.geoBreakdown | query | Click counts by country code |
| analytics.linkStats | query | Summary: total clicks, unique visitors, top sources |
Configuration
| Function | Type | Description |
| --------------- | -------- | ---------------------------------------------- |
| config.init | mutation | Initialize config (idempotent) |
| config.get | query | Get current config (excludes daily salt) |
| config.update | mutation | Update default redirect type, UTM, rate limits |
create arguments
| Argument | Type | Required | Description |
| ---------------- | --------------------------------------- | -------- | --------------------------------------------------------------- |
| destinationUrl | string | yes | Target URL (must be http/https, max 8192 chars) |
| createdBy | string | yes | User ID (provided by auth in exposeApi) |
| code | string | no | Custom short code (alphanumeric, hyphens, underscores, max 128) |
| redirectType | 301 \| 302 | no | Override default redirect type |
| expiresAt | number | no | Expiration timestamp (ms since epoch) |
| password | string | no | Password to protect the link |
| utmConfig | "capture" \| "strip" \| "passthrough" | no | UTM parameter handling mode |
| metadata | { title?: string, tags?: string[] } | no | Optional metadata for organization |
UTM Parameter Modes
| Mode | Behavior |
| --------------- | ------------------------------------------------------------------------- |
| "passthrough" | UTM params in the redirect URL are forwarded to the destination (default) |
| "capture" | UTM params are extracted and stored in click records for analytics |
| "strip" | UTM params are removed from the destination URL before redirecting |
Security
- URL validation: Only
http:andhttps:schemes are allowed.javascript:,data:,file:, and other dangerous schemes are rejected. URLs with embedded credentials (user:pass@host) are also rejected. - Password protection: Passwords are SHA-256 hashed with a unique random salt per link. Comparison uses constant-time equality to prevent timing attacks.
- IP privacy: Visitor IPs are SHA-256 hashed with a daily rotating salt before storage. Raw IPs are never persisted. Historical hashes cannot be correlated across days.
- Rate limiting: Configurable per-user sliding window prevents link creation abuse.
- Component isolation: All data is stored in isolated Convex component tables, separate from your app's database.
- Code generation: Short codes use cryptographically random generation with a 62^7 keyspace (~3.5 trillion combinations).
Testing
The component ships with a test helper for use with convex-test:
// In your test setup file:
import { convexTest } from "convex-test";
import component from "@the_shujaa/link-shortener/test";
import schema from "./schema";
export function initConvexTest() {
const t = convexTest(schema, modules);
component.register(t);
return t;
}Run the component's own test suite:
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage reportExample App
The example/ directory contains a complete React + Vite dashboard
demonstrating all features:
npm install
npm run devThis starts the Convex backend, frontend dev server, and codegen watcher. The dashboard includes link creation with all options, link management (revoke, delete, update), click analytics visualization, and configuration management.
Publishing Automation (CI + Local)
CI/CD with npm trusted publishing (no tokens, no OTP prompts)
- Open npm package settings for
@the_shujaa/link-shortener. - In Trusted publishing, add this GitHub repository and workflow file:
.github/workflows/publish.yml. - Push a tag that matches
package.jsonversion (for examplev0.1.1). - GitHub Actions publishes automatically with provenance via OIDC.
You can also publish manually from the Actions tab with workflow_dispatch.
Local publishing without repeated web login
- Create a granular npm token with publish permissions (and bypass 2FA if your npm org/package policy requires OTP for interactive logins).
- Set the token in your shell and save it once:
$env:NPM_TOKEN = "npm_xxx"
npm run npm:login:token- Publish locally without interactive auth:
npm run publish:localTo clear the saved token later:
npm config delete //registry.npmjs.org/:_authToken --location=userDevelopment
npm install # Install dependencies
npm run build:codegen # Generate component types
npm run dev # Start dev server (backend + frontend + codegen watcher)
npm test # Run tests
npm run typecheck # Type-check all configsSee example/convex/links.ts for complete usage examples and example/convex/http.ts for HTTP router setup.
Found a bug? Feature request? File it here.
