A small toolkit for profile URLs
Sociurl recognizes social platforms from profile URLs, checks that the host, path, and username follow supported rules, and returns a canonical HTTPS URL. It also includes optional React components and a hook.
Install and validate a URL
Install Sociurl in your project. Add React only if you use the React entry point.
npm install sociurlimport { validateSocialUrl } from "sociurl";
const result = validateSocialUrl("instagram.com/ahmad");
if (result.valid) {
console.log(result.platform); // "instagram"
console.log(result.username); // "ahmad"
console.log(result.normalizedUrl); // "https://www.instagram.com/ahmad"
} else {
console.log(result.error.code, result.error.message);
}Results are a discriminated union. Check result.valid before reading fields: valid results contain a username and normalized URL; invalid results contain an error.
Core API
detectPlatform(url, options?)
Detects a supported platform from the hostname. It can detect a platform even when the profile username is missing. Returns a platform ID or null.
detectPlatform("www.instagram.com/"); // "instagram"
detectPlatform("https://twitter.com/ahmad"); // "x"
detectPlatform("https://instagram.com.fake.com/ahmad"); // nullvalidateSocialUrl(url, options?)
Validates the host, profile path, username, and protocol. Returns the full valid or invalid result.
validateSocialUrl("https://github.com/ahmad", {
platform: "instagram", // Optional: require a specific platform
});
validateSocialUrl(url, {
registry, // Optional custom PlatformRegistry
messages, // Optional error message overrides
});extractUsername(url, options?)
Returns the validated profile identifier, or null when parsing or validation fails. YouTube channel URLs return the channel ID; Facebook numeric profile URLs return the numeric ID.
extractUsername("https://reddit.com/u/ahmad"); // "ahmad"
extractUsername("https://instagram.com/"); // nullnormalizeSocialUrl(url, options?)
Returns the canonical HTTPS profile URL, or null when the URL is not a valid profile.
normalizeSocialUrl("HTTP://instagram.com/ahmad/");
// "https://www.instagram.com/ahmad"getSupportedPlatforms(options?) and getPlatformInfo(id, options?)
Read all definitions in a registry or retrieve one platform definition. With no registry option, both use the built-in definitions.
const platforms = getSupportedPlatforms();
const instagram = getPlatformInfo("instagram");How normalization works
- Missing protocols become HTTPS. HTTP input is accepted and upgraded to HTTPS.
- Aliases and canonical domains are normalized, such as Twitter to X.
- Extra trailing slashes and duplicate empty path segments are removed.
- Required path prefixes are kept, such as LinkedIn’s
/in/and Reddit’s/user/. - Tracking query parameters and fragments are dropped. Query parameters are kept only when the username is stored there.
- Username casing is preserved. Encoded usernames are safely decoded and re-encoded.
normalizeSocialUrl("https://m.instagram.com/ahmad?hl=en#top");
// "https://www.instagram.com/ahmad"
normalizeSocialUrl("https://reddit.com/u/ahmad");
// "https://www.reddit.com/user/ahmad"Supported platforms
Platform matching is based on explicit hostnames, profile patterns, username rules, and reserved paths. Content URLs are not treated as profiles.
| Platform | ID | Profile format |
|---|---|---|
instagram | /username | |
facebook | /username or /profile.php?id=123 | |
linkedin | /in/username | |
| GitHub | github | /username |
| X | x | /username (twitter.com alias) |
| YouTube | youtube | /@handle, /c/name, /user/name, /channel/ID |
| TikTok | tiktok | /@username |
pinterest | /username | |
reddit | /user/name or /u/name | |
| Twitch | twitch | /username |
| Medium | medium | /@username |
| Dribbble | dribbble | /username |
| Behance | behance | /username |
| Telegram | telegram | /username (telegram.me alias) |
| Threads | threads | /@username (threads.com alias) |
Examples of rejected content paths include Instagram posts, YouTube watch pages, and Reddit community pages. Use getSupportedPlatforms() to inspect the installed definitions and icon metadata.
Custom platforms and registries
Custom definitions are scoped to a registry instance. Registering one never changes Sociurl’s shared built-ins.
import { createPlatformRegistry, validateSocialUrl } from "sociurl";
import type { PlatformDefinition } from "sociurl";
const devTo: PlatformDefinition = {
id: "devto",
name: "DEV Community",
domains: ["dev.to"],
canonicalDomain: "dev.to",
profilePatterns: [{
handle: "at", // /@username
username: { pattern: /^[A-Za-z0-9_]{2,30}$/ },
}],
reservedPaths: ["about", "settings"],
};
const registry = createPlatformRegistry({ platforms: [devTo] });
validateSocialUrl("https://dev.to/@ahmad", { registry });Registry creation options
createPlatformRegistry()includes all built-ins by default.includeBuiltIns: falsestarts with only the custom definitions you pass.platformsregisters definitions during creation.
Registry instance methods
register(definition, options?) | Adds a definition. Duplicate IDs throw by default; use { overwrite: true } to replace one. |
|---|---|
unregister(id) | Removes a definition and returns whether one existed. |
has(id) | Checks whether an ID is registered. |
get(id) | Returns one definition or null. |
getAll() | Returns a copy of all registered definitions. |
findByHostname(hostname) | Finds a definition by exact host and permitted subdomain. |
Profile patterns
Path patterns can declare a literal prefix, plain or @ handles, and a canonical prefix. Query patterns declare an exact pathname and the query parameter containing the identifier.
{
kind: "query",
pathname: "profile",
queryParam: "id",
username: { pattern: /^\d+$/ },
}Username regular expressions must not use the global or sticky flags. Keep them anchored so they validate the full identifier.
Error codes and message overrides
| Code | Meaning |
|---|---|
INVALID_URL | The input is empty or malformed, contains credentials, uses a non-standard port, or has ambiguous encoding. |
UNSUPPORTED_PLATFORM | The hostname is not supported, or does not match the required platform. |
MISSING_USERNAME | The URL has a profile-shaped path but no username. |
INVALID_USERNAME | The username violates the platform’s rules or is reserved. |
INVALID_PROFILE_PATH | The URL points to a content page, reserved route, or unsupported path shape. |
INVALID_PROTOCOL | The URL uses a scheme other than HTTP or HTTPS. |
Each failed validation has an error.code and readable error.message. Override selected messages without changing validation behavior.
validateSocialUrl(url, {
messages: {
MISSING_USERNAME: "Add your {platform} handle",
INVALID_USERNAME: ({ platform, defaultMessage }) =>
platform ? "That is not a valid " + platform.name + " handle" : defaultMessage,
},
});String overrides support the {platform} token. Function overrides receive code, platform, and the original defaultMessage.
Error factory helpers are also exported: createValidationError, invalidUrl, unsupportedPlatform, missingUsername, invalidUsername, invalidProfilePath, and invalidProtocol.
React integration
Install React and React DOM if you use the React entry point:
npm install react react-domimport { SocialInput, SocialIcon, SocialLinks, useSocialValidator } from "sociurl/react";SocialInput
A platform-aware input with controlled or uncontrolled value, validation, accessible labeling, and customizable messages.
<SocialInput
platform="instagram"
label="Instagram profile"
value={url}
onChange={(value, event) => setUrl(value)}
onValidationChange={setResult}
validateOn="change" // or "blur"
messages={messages}
/>Pass native input props such as placeholder, disabled, name, and aria-*. The callback receives the new string first and the input event second.
It ships without CSS. Customize the wrapper, label, field, icon, input, and error with the matching *ClassName and *Style props. showIcon, showError, iconSize, iconColor, colorStyle, and renderError control presentation.
SocialIcon
Renders the package’s bundled platform icon data. It returns null when the platform has no icon. Default fill inherits currentColor; colorStyle="brand" opts into the platform brand color, and an explicit color takes precedence.
<SocialIcon platform="instagram" size={28} colorStyle="brand" />
<SocialIcon platform="github" color="#ffffff" decorative />Props include platform, size, color, colorStyle, label, decorative, and registry.
SocialLinks
Validates each item and renders only supported profile URLs. Invalid items are omitted. Links open in a new tab by default with safe rel values.
<SocialLinks
links={[
{ platform: "instagram", url: "instagram.com/ahmad" },
{ platform: "github", url: "github.com/ahmad" },
]}
showLabels
colorStyle="brand"
/>Customize list, item, link, and icon styling; set newTab; or replace icon/item rendering with renderIcon and renderItem. iconColor takes precedence over colorStyle.
useSocialValidator
A React hook that returns validate, validateOnBlur, reset, result, isValid, error, and touched.
const { validate, validateOnBlur, reset, result, isValid, error, touched } =
useSocialValidator({
platform: "github",
value: url, // optional automatic validation
validateOn: "change", // or "blur"
registry,
messages,
});Use validate for immediate/manual validation, validateOnBlur for touched blur behavior, and reset to clear the result and touched state.
Types and package entry points
The package includes declaration files for both the core and React entry points. Useful core types include:
PlatformIdBuiltInPlatformIdPlatformDefinitionProfilePathPatternPathProfilePatternQueryProfilePatternUsernameRuleValidationResultValidValidationResultInvalidValidationResultValidationErrorValidationErrorCodeValidationMessagesRegisterPlatformOptionsCreatePlatformRegistryOptionsimport type { PlatformDefinition, ValidationResult } from "sociurl";
import type { SocialInputProps, SocialLinksProps } from "sociurl/react";PlatformId includes the built-in IDs and remains open to custom IDs.
Security, compatibility, and known limits
- Hostnames are matched exactly; lookalike domains and unlisted subdomains are rejected.
- Credential-bearing URLs, non-standard ports, raw backslashes, whitespace/control characters, and encoded path separators are rejected.
- Reserved routes and content pages are not treated as user profiles.
- Only HTTP and HTTPS are accepted. Normalized links always use HTTPS.
- Validation does not perform network requests or verify account existence.
Platform-specific scope
LinkedIn support covers personal /in/ profiles, not company pages. Medium supports medium.com/@handle, not publication subdomains. Facebook supports vanity paths and numeric profile.php?id= profiles, not every legacy route. YouTube supports handles and common legacy channel paths; short youtu.be links are not profiles.
Package outputs
Published builds include ESM, CommonJS, TypeScript declarations, and source maps. React is external to the React build. The package is tree-shakeable.
Explore the API live.
Change the input, create a custom registry, and see the result in the playground.
docs